简体   繁体   中英

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.

HOWEVER

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();
     ++iter)
{
  Record r;
  r.word = iter->first;
  r.count = iter->second.first;
  r.file_position = iter->second.second;
  database.push_back(r);
}

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

Here's a somewhat expensive solution that sorts the string list by reference to the map:

// Make word list
std::vector<std::string> words;
words.reserve(m.size());
for (const auto & p : m) words.push_back(p.first);

// Sort
std::sort(
    words.begin(), words.end(),
    [&m](const std::string & lhs, const std::string & rhs)
    { return m.find(lhs)->second < m.find(rhs)->second; });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM