C ++ map emplace_hint()函數(shù)用于通過使用提示作為元素位置將新元素插入到容器中來擴(kuò)展map容器。元素是直接構(gòu)建的(既不復(fù)制也不移動(dòng))。
通過給傳遞給該函數(shù)的參數(shù)args調(diào)用元素的構(gòu)造函數(shù)。僅當(dāng)密鑰不存在時(shí)才進(jìn)行插入。
template <class... Args> iterator emplace_hint (const_iterator position, Args&&...args); //從 C++ 11 開始
args:轉(zhuǎn)發(fā)以構(gòu)造要插入到映射中的元素的參數(shù)。
position:提示插入新元素的位置。
它將迭代器返回到新插入的元素。如果元素已經(jīng)存在,則插入失敗,并將迭代器返回到現(xiàn)有元素。
讓我們看一個(gè)將元素插入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
在上面的示例中,它只是將具有給定鍵值對(duì)和位置的元素插入到映射m中。
讓我們看一個(gè)簡單的實(shí)例。
#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已修改,現(xiàn)在包含 ";
print(m1);
cout << endl;
}輸出:
map starting data: 3 elements: (Rakesh,Accounting) (Ram,Accounting) (Sunil,Engineering) map已修改,現(xiàn)在包含 4 elements: (Deep,Engineering) (Rakesh,Accounting) (Ram,Accounting) (Sunil,Engineering)
讓我們看一個(gè)簡單的示例,將元素插入到具有給定位置的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]
讓我們看一個(gè)插入元素的簡單示例。
#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<<"輸入家庭成員人數(shù) :";
cin>>n;
cout<<"輸入每個(gè)成員的姓名和年齡: \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家庭成員的詳細(xì)信息: \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;
}輸出:
輸入家庭成員人數(shù) : 3 輸入每個(gè)成員的姓名和年齡: Ram 42 Sita 37 Laxman 40 家庭總成員是:3 家庭成員的詳細(xì)信息: Name | Age __________________________ Laxman | 40 Ram | 42 Sita | 37
在上面的示例中,它只是根據(jù)用戶的選擇將元素插入map的開頭。