C++ set emplace_hint()函数用于通过使用提示作为元素位置将新元素插入集合来扩展set集合。元素是直接构建的(既不复制也不移动)。
通过给传递给该函数的参数args调用元素的构造函数。
template <class.... Args> iterator emplace_hint (const_iterator position, Args&&... args); //since C++ 11
args - 转发来构造要插入到集合中的元素的参数。
position - 提示插入新元素的位置。
它将迭代器返回到新插入的元素。如果元素已经存在,则插入失败,并将迭代器返回到现有元素。
让我们看一下将元素插入到集合中的简单示例:
#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 << "Set contains following elements" << endl; for (auto it = m.begin(); it != m.end(); ++it) cout << *it<< endl; return 0; }
输出:
Set contains following elements 10 20 30 40 50 60
在上面的示例中,它只是将元素以给定位置的给定值插入集合m中。
让我们看一个简单的例子:
#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; //Emplace some test data m1.emplace("Ram"); m1.emplace("Rakesh"); m1.emplace("Sunil"); cout << "set starting data: "; print(m1); cout << endl; //Emplace with hint //m1.end() should be the "next" element after this emplacement m1.emplace_hint(m1.end(), "Deep"); cout << "set modified, now contains "; print(m1); cout << endl; }
输出:
set starting data: 3 elements: Rakesh Ram Sunil set modified, now contains 4 elements: Deep Rakesh Ram Sunil
让我们看一个简单的示例,将元素插入给定位置的集合中:
#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]
让我们看一个插入元素的简单示例:
#include <iostream> #include <set> #include <string> using namespace std; int main() { typedef set<string> city; string name; city fmly ; int n; cout<<"Enter the number of family members :"; cin>>n; cout<<"Enter the name of each member: \n"; for(int i =0; i<n; i++) { cin>> name; //Get key fmly.emplace_hint(fmly.begin(),name); } cout<<"\nTotal memnbers in family are:"<< fmly.size(); cout<<"\nDetails of family members: \n"; cout<<"\nName \n ________________________\n"; city::iterator p; for(p = fmly.begin(); p!=fmly.end(); p++) { cout<<(*p) <<" \n "; } return 0; }
输出:
Enter the number of fmly members : 4 Enter the name of each member: Deep Sonu Ajeet Bob Total memnber of fmly is:4 Details of fmly members: Name ________________________ Ajeet Bob Deep Sonu
在上面的示例中,它只是根据用户的选择将元素插入集合的开头。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)