天天看點

C++ 那些被遺漏的細節2 map emplace emplace_hint

說明

  • 主要關注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;
}
           
  • 結果
[email protected]-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
           

參考

  • emplace
  • emplace_hint

繼續閱讀