1.at()
c++11
类似于 operator[ ]访问元素的操作,通过key找到和 key对应的value并将其返回。
当key不存在时,operator[ ]默认插入该<key,value>键值对,而at()会直接抛出异常。
使用eg:
int main ()
{
std::map<std::string,int> mymap = {{ "alpha", 0 },{ "beta", 0 },{ "gamma", 0 } };
mymap.at("alpha") = 10;
mymap.at("beta") = 20;
mymap.at("gamma") = 30;
for (auto& x: mymap)
std::cout << x.first << ": " << x.second << '\n';
return 0;
}
/*输出
alpha: 10
beta: 20
gamma: 30
*/
2.emplace()
c++11
用于通过在容器中插入新元素来扩展map容器。元素是直接构建的(既不复制也不移动)。通过给传递给该函数的参数args调用元素的构造函数。仅当键不存在时才进行插入
函数定义:
template <class...Args>
pair<iterator, bool> emplace (Args&&... args); //从 C++ 11 开始
参数args:转发以构造要插入到map中的元素的参数。
返回值:返回一个布尔对,它表示是否发生插入,并返回一个指向新插入元素的迭代器。
int main(void) {
map<char, int> m;
m.emplace('a', 1);
m.emplace('b', 2);
m.emplace('c', 3);
m.emplace('d', 4);
m.emplace('e', 5);
cout << "Map包含以下元素" << endl;
for (auto it = m.begin(); it != m.end(); ++it)
cout << it->first << " = " << it->second << endl;
return 0;
}
/*输出:
Map包含以下元素
a = 1
b = 2
c = 3
d = 4
e = 5
*/
3.emplace_hint()
c++11
功能:通过使用提示作为元素位置将新元素插入到容器中来扩展map容器。元素是直接构建的(既不复制也不移动)。通过给传递给该函数的参数args调用元素的构造函数。仅当密钥不存在时才进行插入。
函数定义:
template <class... Args>
iterator emplace_hint (const_iterator position, Args&&...args);
参数:
args:转发以构造要插入到映射中的元素的参数。
position:提示插入新元素的位置。(迭代器)
返回值:
它将迭代器返回到新插入的元素。如果元素已经存在,则插入失败,并将迭代器返回到现有元素。
eg:
#include <map>
#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.first << "," << p.second << ") ";
}
cout << endl;
}
int main()
{
map<string, string> m1;
m1.emplace("Ram", "Accounting");
m1.emplace("Rakesh", "Accounting");
m1.emplace("Sunil", "Engineering");
cout << "map starting data: ";
print(m1);
cout << endl;
m1.emplace_hint(m1.end(), "Deep", "Engineering");
cout << "map已修改,现在包含 ";
print(m1);
cout << endl;
}
/*输出:
map starting data: 3 elements:
(Rakesh,Accounting) (Ram,Accounting) (Sunil,Engineering)
map已修改,现在包含 4 elements:
(Deep,Engineering) (Rakesh,Accounting) (Ram,Accounting) (Sunil,Engineering)
*/
4.max_size()
size()函数返回的是map中的元素数。
max_size()返回的是map的最大容量。
eg:
int main()
{
map<char,char> s;
cout << "map的最大大小是 " << s.max_size() << "\n";
}
/*输出:
map的最大大小是 268435455
*/