MagoNick MagoNick - 3 months ago 30
C++ Question

Copy subset of a std::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?

sji sji
Answer

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);