C++ multiset emplace()
C++ multiset emplace()
C++ multiset emplace()函数用于通过将新元素插入容器来扩展 multiset 容器。元素是直接构建的(既不能复制也不能移动)。
通过给传递给该函数的参数args来调用元素的构造函数。
语法
template <class? Args>
iterator emplace (Args&&? args); //since C++ 11
参数
参数: 为构造要插入到容器中的元素而转发的参数。
返回值
emplace()函数返回一个布尔对,它将指示是否发生插入,并返回一个指向新插入元素的迭代器。
复杂度
容器大小的对数。
迭代器有效性
无变化
数据竞争
容器已修改。
容器中的迭代范围并不安全,尽管同时访问出口元素是安全的。
异常安全性
如果引发异常,则 multiset 容器中没有任何更改。
示例1
让我们看一下将元素插入 multiset 中的简单示例:
#include <iostream>
#include <set>
using namespace std;
int main(void) {
multiset<char> m;
m.emplace('a');
m.emplace('b');
m.emplace('a');
m.emplace('c');
m.emplace('b');
cout << "Multiset contains following elements" << endl;
for (auto it = m.begin(); it != m.end(); ++it)
cout << *it<< ", ";
return 0;
}
输出:
Multiset contains following elements
a, a, b, b, c,
在上面的示例中,它只是将具有给定值的元素插入到 multiset m中。
示例2
让我们看一个简单的示例插入元素并检查重复键:
#include <set>
#include <string>
#include <iostream>
using namespace std;
template <typename S> void print(const S& s) {
cout << s.size() << " elements: ";
for (const auto& p : s) {
cout << "(" << p << ") ";
}
cout << endl;
}
int main()
{
multiset<string> s1;
s1.emplace("Deep");
s1.emplace("Nikita");
s1.emplace("Kesharwani");
cout << "multiset modified, now contains ";
print(s1);
cout << endl;
s1.emplace("Nikita");
cout << "multiset modified, now contains ";
print(s1);
cout << endl;
}
输出:
multiset modified, now contains 3 elements: (Deep) (Kesharwani) (Nikita)
multiset modified, now contains 4 elements: (Deep) (Kesharwani) (Nikita) (Nikita)
示例3
让我们看一个简单的示例来查找所插入元素的总和:
#include <iostream>
#include <set>
using namespace std;
int main()
{
// sum variable declaration
int sum = 0;
// multiset declaration
multiset<int> mymultiset{};
mymultiset.emplace(1);
mymultiset.emplace(3);
mymultiset.emplace(4);
mymultiset.emplace(1);
mymultiset.emplace(2);
mymultiset.emplace(2);
mymultiset.emplace(3);
// iterator declaration
multiset<int>::iterator it;
// finding sum of elements
while (!mymultiset.empty()) {
it = mymultiset.begin();
sum = sum + *it;
mymultiset.erase(it);
}
// printing the sum
cout << "Sum of elements is: "<<sum;
return 0;
}
输出:
示例4
让我们看一个插入元素的简单示例:
#include <iostream>
#include <set>
#include <string>
using namespace std;
int main() {
typedef multiset<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(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
在上面的示例中,它只是根据用户的选择插入元素。