说明
- 主要关注map的emplace、insert的返回类型 std::pair<iterator, bool> 和 emplace_hint的返回类型iterator。
template< class... Args >
std::pair<iterator,bool> emplace( Args&&... args );(since C++11)
- 如果插入成功,则iterator指向新插入元素,否则指向已存在的相同key元素;插入成功bool为true,否则为false。
template <class... Args>
iterator emplace_hint( const_iterator hint, Args&&... args ); (since C++11)
- iterator指向新插入元素或者已存在的相同key元素
例子
#include <iostream>
#include <string>
#include <map>
#include <algorithm>
#include <iterator>
template <typename C>
void print(const std::string &pre, const C &c)
{
std::cout << pre;
for (auto it = c.begin(); it != c.end(); ++it)
std::cout << " {" << it->first << ", " << it->second << "}";
std::cout << std::endl;
}
int main()
{
std::map<int, std::string> mp{{1, "john"}, {2, "tom"}};
print("map: ", mp);
auto pr = mp.emplace(std::pair<const int, std::string>(1, "ketty"));
print("map: ", mp);
if (pr.second)
{
std::cout << "aready empalced: return data: " << pr.first->second << std::endl;
}
else
{
std::cout << "not empalced: return data: " << pr.first->second << std::endl;
}
pr = mp.emplace(std::pair<const int, std::string>(3, "lily"));
print("map: ", mp);
if (pr.second)
{
std::cout << "aready empalced: return data: " << pr.first->second << std::endl;
}
else
{
std::cout << "not empalced: return data: " << pr.first->second << std::endl;
}
return 0;
}
lee@leedeMacBook-Pro map % ./main
map: {1, john} {2, tom}
map: {1, john} {2, tom}
not empalced: return data: john
map: {1, john} {2, tom} {3, lily}
aready empalced: return data: lily
参考