📅  最后修改于: 2020-10-20 08:01:22             🧑  作者: Mango
C++ set emplace()函数用于通过将新元素插入容器来扩展set容器。元素是直接构建的(既不复制也不移动)。
通过给传递给此函数的参数args调用元素的构造函数。
仅当密钥不存在时才进行插入。
template
pair emplace (Args&&... args); //since C++ 11
args:转发以构造要插入到集合中的元素的参数。
emplace()函数返回布尔对,该布尔对将指示是否发生插入,并返回指向新插入元素的迭代器。
容器大小的对数。
没有变化。
容器已修改。
尽管同时访问出口元素是安全的,但在容器中进行迭代范围并不安全。
如果引发异常,则容器中没有任何更改。
让我们看一下将元素插入到集合中的简单示例:
#include
#include
using namespace std;
int main(void) {
set m;
m.emplace('a');
m.emplace('b');
m.emplace('c');
m.emplace('d');
m.emplace('e');
cout << "Set contains following elements" << endl;
for (auto it = m.begin(); it != m.end(); ++it)
cout << *it<< ", ";
return 0;
}
输出:
Set contains following elements
a, b, c, d, e,
在上面的示例中,它只是将具有给定键值对的元素插入到集合m中。
让我们看一个简单的例子,插入元素并检查重复键:
#include
#include
#include
using namespace std;
template void print(const S& s) {
cout << s.size() << " elements: ";
for (const auto& p : s) {
cout << "(" << p << ") ";
}
cout << endl;
}
int main()
{
set s1;
auto ret = s1.emplace("ten");
if (!ret.second){
cout << "Emplace failed, element with value \"ten\" already exists."
<< endl << " The existing element is (" << *ret.first << ")"
<< endl;
cout << "set not modified" << endl;
}
else{
cout << "set modified, now contains ";
print(s1);
}
cout << endl;
ret = s1.emplace("ten");
if (!ret.second){
cout << "Emplace failed, element with value \"ten\" already exists."
<< endl << " The existing element is (" << *ret.first << ")"
<< endl;
}
else{
cout << "set modified, now contains ";
print(s1);
}
cout << endl;
}
输出:
set modified, now contains 1 elements: (ten)
Emplace failed, element with value "ten" already exists.
The existing element is (ten)
在上面的示例中,将元素插入到集合中,当您尝试使用相同的键“十”时,它将显示一条错误消息,提示键“十”已经存在。
让我们看一个简单的示例,查找插入元素的总和:
#include
#include
using namespace std;
int main()
{
// sum variable declaration
int sum = 0;
// set declaration
set myset{};
myset.emplace(1);
myset.emplace(7);
myset.emplace(4);
myset.emplace(8);
myset.emplace(2);
myset.emplace(5);
myset.emplace(3);
// iterator declaration
set::iterator it;
// finding sum of elements
while (!myset.empty()) {
it = myset.begin();
sum = sum + *it;
myset.erase(it);
}
// printing the sum
cout << "Sum of elements is: "<
输出:
Sum of elements is: 30
让我们看一个插入元素的简单示例:
#include
#include
#include
using namespace std;
int main() {
typedef set 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> name; // Get key
fmly.emplace(name);
}
cout<<"\nTotal member of family is:"<< 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 family members: 3
Enter the name of each member:
Bob
Robin
David
Total member of family is: 3
Details of family members:
Name
________________________
Bob
David
Robin
在上面的示例中,它只是根据用户的选择插入元素。