C ++ set emplace()函数用于通过将新元素插入容器来扩展set容器。元素是直接构建的(既不复制也不移动)。
通过给传递给该函数的参数args调用元素的构造函数。
仅当键不存在时才进行插入。
语法
template <class.... Args>
pair<iterator, bool> emplace (Args&&... args); //C++ 11 之后
参数
args:传递来构造要插入到集合中的元素的参数。
返回值
emplace()函数返回一个布尔对,它将指示是否发生了插入,并返回一个指向新插入元素的迭代器。
复杂
容器大小的对数。
迭代器有效性
没有变化。
数据争用
容器已修改。
尽管同时访问出口元素是安全的,但在容器中进行迭代范围并不安全。
异常安全
如果引发异常,则容器中没有任何更改。
实例1
让我们看一下将元素插入到集合中的简单示例:
#include <iostream>
#include <set>
using namespace std;
int main(void) {
set<char> m;
m.emplace('a');
m.emplace('b');
m.emplace('c');
m.emplace('d');
m.emplace('e');
cout << "集合包含以下元素" << endl;
for (auto it = m.begin(); it != m.end(); ++it)
cout << *it<< ", ";
return 0;
}
输出:
集合包含以下元素
a, b, c, d, e,
在上面的示例中,它只是将具有给定键值对的元素插入到集合m中。
实例2
让我们看一个简单的实例,插入元素并检查重复键:
#include <set>
#include <string>
#include <iostream>
using namespace std;
template <typename S> void print(const S& s) {
cout << s.size() << " 元素: ";
for (const auto& p : s) {
cout << "(" << p << ") ";
}
cout << endl;
}
int main()
{
set<string> s1;
auto ret = s1.emplace("ten");
if (!ret.second){
cout << "Emplace失败,值为“ten”的元素已经存在。"
<< endl << " 现有元素是 (" << *ret.first << ")"
<< endl;
cout << "set没有被修改" << endl;
}
else{
cout << "集合已修改,现在包含 ";
print(s1);
}
cout << endl;
ret = s1.emplace("ten");
if (!ret.second){
cout << "Emplace失败,值为“ten”的元素已经存在。"
<< endl << " 现有元素是 (" << *ret.first << ")"
<< endl;
}
else{
cout << "集合已修改,现在包含 ";
print(s1);
}
cout << endl;
}
输出:
集合已修改,现在包含 1 元素: (ten)
Emplace失败,值为“ten”的元素已经存在。
现有元素是 (ten)
在上面的示例中,将元素插入到集合中,当您尝试使用相同的键“十”时,它将显示一条错误消息,提示键“十”已经存在。
实例3
让我们看一个简单的示例,查找插入元素的总和:
#include <iostream>
#include <set>
using namespace std;
int main()
{
// sum变量声明
int sum = 0;
// set 声明
set<int> myset{};
myset.emplace(1);
myset.emplace(7);
myset.emplace(4);
myset.emplace(8);
myset.emplace(2);
myset.emplace(5);
myset.emplace(3);
// iterator 声明
set<int>::iterator it;
// 求元素之和
while (!myset.empty()) {
it = myset.begin();
sum = sum + *it;
myset.erase(it);
}
// 打印总和
cout << "元素的总和为: "<<sum;
return 0;
}
输出:
元素的总和为: 30
实例4
让我们看一个插入元素的简单示例:
#include <iostream>
#include <set>
#include <string>
using namespace std;
int main() {
typedef set<string> city;
string name;
city fmly ;
int n;
cout<<"输入家庭成员的数量 :";
cin>>n;
cout<<"输入每个成员的姓名: \n";
for(int i =0; i<n; i++)
{
cin>> name; // Get key
fmly.emplace(name);
}
cout<<"\n家庭的总成员是:"<< 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;
}
输出:
输入家庭成员的数量: 3
输入每个成员的姓名:
Bob
Robin
David
家庭的总成员是: 3
家庭成员列表:
Name
________________________
Bob
David
Robin
在上面的示例中,它只是根据用户的选择插入元素。
C++ set emplace_hint() C++ std 运算符 <=
展开全部