public
Created

This is how you can insert elements in a container, without repetition, and obtaining unique ids. Useful for inserting vertexes in Boost.Graph. See http://stackoverflow.com/questions/3950841

  • Download Gist
unique_insert_with_ids.cpp
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include <string>
#include <map>
 
using namespace std;
 
int main (int argc, char const *argv[])
{
string array[] = { "zero", "one", "one", "zero", "two", "three", "zero" };
map<string, unsigned int> numbers;
for(size_t i = 0; i < 7; ++i)
{
pair<string, unsigned int> p(array[i], numbers.size());
int id = numbers.insert(p).first->second;
cout << array[i] << "\t" << id << endl;
}
return 0;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.