C ++ map emplace_hint()函数用于通过使用提示作为元素位置将新元素插入到容器中来扩展map容器。元素是直接构建的(既不复制也不移动)。
通过给传递给该函数的参数args调用元素的构造函数。仅当密钥不存在时才进行插入。
template <class... Args> iterator emplace_hint (const_iterator position, Args&&...args); //从 C++ 11 开始
args:转发以构造要插入到映射中的元素的参数。
position:提示插入新元素的位置。
它将迭代器返回到新插入的元素。如果元素已经存在,则插入失败,并将迭代器返回到现有元素。
让我们看一个将元素插入map的简单示例。
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main(void) {
map<char, int> m = {
{'b', 20},
{'c', 30},
{'d', 40},
};
m.emplace_hint(m.end(), 'e', 50);
m.emplace_hint(m.begin(), 'a', 10);
cout << "Map包含以下元素" << endl;
for (auto it = m.begin(); it != m.end(); ++it){
cout << it->first << " = " << it->second << endl;
}
return 0;
}输出:
Map包含以下元素 a = 10 b = 20 c = 30 d = 40 e = 50
在上面的示例中,它只是将具有给定键值对和位置的元素插入到映射m中。
让我们看一个简单的实例。
#include <map>
#include <string>
#include <iostream>
using namespace std;
template <typename M> void print(const M& m) {
cout << m.size() << " elements: " << endl;
for (const auto& p : m) {
cout << "(" << p.first << "," << p.second << ") ";
}
cout << endl;
}
int main()
{
map<string, string> m1;
m1.emplace("Ram", "Accounting");
m1.emplace("Rakesh", "Accounting");
m1.emplace("Sunil", "Engineering");
cout << "map starting data: ";
print(m1);
cout << endl;
m1.emplace_hint(m1.end(), "Deep", "Engineering");
cout << "map已修改,现在包含 ";
print(m1);
cout << endl;
}输出:
map starting data: 3 elements: (Rakesh,Accounting) (Ram,Accounting) (Sunil,Engineering) map已修改,现在包含 4 elements: (Deep,Engineering) (Rakesh,Accounting) (Ram,Accounting) (Sunil,Engineering)
让我们看一个简单的示例,将元素插入到具有给定位置的map中。
#include <iostream>
#include <map>
using namespace std;
int main ()
{
map<char,int> mymap;
auto it = mymap.end();
it = mymap.emplace_hint(it,'b',10);
mymap.emplace_hint(it,'a',12);
mymap.emplace_hint(mymap.end(),'c',14);
cout << "mymap 包含:";
for (auto& x: mymap){
cout << " [" << x.first << ':' << x.second << ']';
cout << '\n';
}
return 0;
}输出:
mymap contains: [a:12] [b:10] [c:14]
让我们看一个插入元素的简单示例。
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
typedef map<string, int> city;
string name;
int age;
city fmly ;
int n;
cout<<"输入家庭成员人数 :";
cin>>n;
cout<<"输入每个成员的姓名和年龄: \n";
for(int i =0; i<n; i++)
{
cin>> name;
cin>> age;
fmly.emplace_hint(fmly.begin(),name,age);
}
cout<<"\n家庭总成员是:"<< fmly.size();
cout<<"\n家庭成员的详细信息: \n";
cout<<"\nName | Age \n ________________________\n";
city::iterator p;
for(p = fmly.begin(); p!=fmly.end(); p++)
{
cout<<(*p).first << " | " <<(*p).second <<" \n ";
}
return 0;
}输出:
输入家庭成员人数 : 3 输入每个成员的姓名和年龄: Ram 42 Sita 37 Laxman 40 家庭总成员是:3 家庭成员的详细信息: Name | Age __________________________ Laxman | 40 Ram | 42 Sita | 37
在上面的示例中,它只是根据用户的选择将元素插入map的开头。