C++ STL中的ESPACE与INSERT

在C++中,所有容器 矢量 , 堆栈 , 队列 , 设置 , 地图 等)支持插入和安放操作。 emplace的优点是,它可以就地插入,并避免不必要的对象副本。对于原始数据类型,使用哪种类型无关紧要。但对于对象,出于效率考虑,最好使用emplace()。

null

CPP

// C++ code to demonstrate difference between
// emplace and insert
#include<bits/stdc++.h>
using namespace std;
int main()
{
// declaring map
multiset<pair< char , int >> ms;
// using emplace() to insert pair in-place
ms.emplace( 'a' , 24);
// Below line would not compile
// ms.insert('b', 25);
// using insert() to insert pair in-place
ms.insert(make_pair( 'b' , 25));
// printing the multiset
for ( auto it = ms.begin(); it != ms.end(); ++it)
cout << " " << (*it).first << " "
<< (*it).second << endl;
return 0;
}


输出:

 a 24 b 25

请参考 在std::map中插入元素(插入、放置和操作符[]) 详细信息。

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享