Connor Schwinghammer Connor Schwinghammer - 27 days ago 4x
C++ Question

Transfer map<string, pair> to vector

So I have this map m

typedef pair<int,int>p;
map<string, p> m;

It holds all of the words in a text file, and the first int in the pair is the frequency of the word and the second is the position of its first character in the text file. These are all calculated and the map works fine.


I need to print these words out, sorted by frequency in descending order. I need the position counter because if two words have the same frequency, the one that comes first in the file should come first in the list.

How do I transfer this map into a vector?

I tried

copy(m.begin(), m.end(), back_inserter(wordList));

to no avail


Okay So I've changed wordList to
vector<pair<string, pair<int, int> > >

And my copy now works. Thank you guys


The simple method is to create a structure with all three fields:

struct Record
  std::string word;
  int         count;
  std::streampos file_position;

Next is to iterate through the map, creating instances of the above structure, filling them in and appending to the vector:

std::vector<Record> database;
for (map<string,p>::const_iterator iter = m.begin();
     iter != m.end();
  Record r;
  r.word = iter->first;
  r.count = iter->second.first;
  r.file_position = iter->second.second;

The vector is now filled, sorted order. The order can be changed by using std::sort() and a custom compare function.