C ++ set emplace_hint()函數(shù)用于通過(guò)使用提示作為元素位置將新元素插入容器來(lái)擴(kuò)展set容器。元素是直接構(gòu)建的(既不復(fù)制也不移動(dòng))。
通過(guò)給傳遞給該函數(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:傳遞來(lái)構(gòu)造要插入到集合中的元素的參數(shù)。
position:提示插入新元素的位置。
它將迭代器返回到新插入的元素。如果元素已經(jīng)存在,則插入失敗,并將迭代器返回到現(xiàn)有元素。
如果未指定位置,則容器大小的對(duì)數(shù)將為對(duì)數(shù)。
如果給出位置,則復(fù)雜度將攤銷常數(shù)。
沒(méi)有變化。
容器已修改。
盡管同時(shí)訪問(wèn)出口元素是安全的,但在容器中進(jìn)行迭代范圍并不安全。
如果引發(fā)異常,則容器中沒(méi)有任何更改。
讓我們看一下將元素插入到集合中的簡(jiǎn)單示例:
#include <iostream>
#include <set>
using namespace std;
int main(void) {
set<int> m = {60, 20, 30, 40};
m.emplace_hint(m.end(), 50);
m.emplace_hint(m.begin(), 10);
cout << "集包含以下元素" << endl;
for (auto it = m.begin(); it != m.end(); ++it){
cout << *it<< endl;
}
return 0;
}輸出:
集包含以下元素 10 20 30 40 50 60
在上面的示例中,它只是將元素以給定位置的給定值插入集合m中。
讓我們看一個(gè)簡(jiǎn)單的實(shí)例:
#include <set>
#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 << " " ;
}
cout << endl;
}
int main()
{
set<string> m1;
//放置一些測(cè)試數(shù)據(jù)
m1.emplace("Ram");
m1.emplace("Rakesh");
m1.emplace("Sunil");
cout << "設(shè)置起始數(shù)據(jù): ";
print(m1);
cout << endl;
//emplace_hint
m1.emplace_hint(m1.end(), "Deep");
cout << "set modified, now contains ";
print(m1);
cout << endl;
}輸出:
設(shè)置起始數(shù)據(jù): 3 元素: Rakesh Ram Sunil 設(shè)置已修改,現(xiàn)在包含 4 元素: Deep Rakesh Ram Sunil
讓我們看一個(gè)簡(jiǎn)單的示例,將元素插入給定位置的集合中:
#include <iostream>
#include <set>
using namespace std;
int main ()
{
set<char> myset;
auto it = myset.end();
it = myset.emplace_hint(it,'b');
myset.emplace_hint(it,'a');
myset.emplace_hint(myset.end(),'c');
cout << "myset contains:";
for (auto& x: myset){
cout << " [" << x << ']';
cout << '\n';
}
return 0;
}輸出:
myset contains: [a] [b] [c]
讓我們看一個(gè)插入元素的簡(jiǎn)單示例:
#include <iostream>
#include <set>
#include <string>
using namespace std;
int main() {
typedef set<string> city;
string name;
city fmly ;
int n;
cout<<"輸入家庭成員人數(shù) :";
cin>>n;
cout<<"輸入每個(gè)成員的姓名: \n";
for(int i =0; i<n; i++)
{
cin>> name; // Get key
fmly.emplace_hint(fmly.begin(),name);
}
cout<<"\n家庭成員總數(shù)為:"<< fmly.size();
cout<<"\n家庭成員資料: \n";
cout<<"\nName \n ________________________\n";
city::iterator p;
for(p = fmly.begin(); p!=fmly.end(); p++)
{
cout<<(*p) <<" \n ";
}
return 0;
}輸出:
輸入家庭成員人數(shù) : 4 輸入每個(gè)成員的姓名: Deep Sonu Ajeet Bob 家庭成員總數(shù)為:4 家庭成員資料: Name ________________________ Ajeet Bob Deep Sonu
在上面的示例中,它只是根據(jù)用戶的選擇將元素插入集合的開(kāi)頭。