首页 > 编程语言 > 详细

C++ map insert 另一个map的子集

时间:2019-10-14 19:05:58      阅读:250      评论:0      收藏:0      [点我收藏+]

C++map中 会有insert操作,举个例子

存在map A,我们截取一部分到map B中,void insert (InputIterator first, InputIterator last) ,截取的部分是 first 到 last 前一个迭代器的值

 

// map::insert (C++98)
#include <iostream>
#include <map>

int main ()
{
  std::map<char,int> mymap;

  // first insert function version (single parameter):
  mymap.insert ( std::pair<char,int>(a,100) );
  mymap.insert ( std::pair<char,int>(z,200) );

  std::pair<std::map<char,int>::iterator,bool> ret;
  ret = mymap.insert ( std::pair<char,int>(z,500) );
  if (ret.second==false) {
    std::cout << "element ‘z‘ already existed";
    std::cout << " with a value of " << ret.first->second << \n;
  }

  // second insert function version (with hint position):
  std::map<char,int>::iterator it = mymap.begin();
  mymap.insert (it, std::pair<char,int>(b,300));  // max efficiency inserting
  mymap.insert (it, std::pair<char,int>(c,400));  // no max efficiency inserting

  // third insert function version (range insertion):
  std::map<char,int> anothermap;
  anothermap.insert(mymap.begin(),mymap.find(c));

  // showing contents:
  std::cout << "mymap contains:\n";
  for (it=mymap.begin(); it!=mymap.end(); ++it)
    std::cout << it->first << " => " << it->second << \n;

  std::cout << "anothermap contains:\n";
  for (it=anothermap.begin(); it!=anothermap.end(); ++it)
    std::cout << it->first << " => " << it->second << \n;

  return 0;
}

输出结果:

element z already existed with a value of 200
mymap contains:
a => 100
b => 300
c => 400
z => 200
anothermap contains:
a => 100
b => 300

详细信息可参考:  http://www.cplusplus.com/reference/map/map/insert/

C++ map insert 另一个map的子集

原文:https://www.cnblogs.com/r-yan/p/11673108.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!