复制std :: map的子集 [英] Copy subset of a std::map

查看:75
本文介绍了复制std :: map的子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以最有效的方式将std :: map结构的子集复制到新的map结构.我只能想到这样简单的香草解决方案:

I am trying to copy a subset of a std::map structure to a new map structure in the most efficient way. I can only think to a plain vanilla solution like this:

// Example program
#include <iostream>
#include <string>
#include <map>

int main()
{
  // build map
  std::map<int, int> mymap;
  size_t num_el = 10;


  for(size_t i = 0; i < num_el; ++i)
  {
      mymap.insert(std::pair<int,int>(i,i));
  }

 // copy submap
 int start_index = 5;
 std::map<int,int> output_map;
 std::map<int,int>::const_iterator it;

  for(it = mymap.find(start_index); it != mymap.end(); ++it)
  {
       output_map.insert(*it);
  }


  //print result
  std::map<int,int>::const_iterator pit;
  for(pit = output_map.begin(); pit != output_map.end(); ++pit)
  {
     std::cout << pit->second << " , ";   
  }

  std::cout << std::endl;
}

是否有更好的方法来做到这一点?

Is there a better way to do this?

推荐答案

insert方法可让您指定如下范围:

The insert method allows you to specify a range like so:

auto range_start = mymap.find(5);
auto range_end = mymap.end();

output_map.insert(range_start, range_end);

这篇关于复制std :: map的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆