[英]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. 它保存文本文件中的所有单词,该对中的第一个int是单词的出现频率,第二个是其第一个字符在文本文件中的位置。 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. 好的,所以我将wordList更改为
vector<pair<string, pair<int, int> > >
现在我的副本可以了。 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. 可以通过使用
std::sort()
和自定义比较函数来更改顺序。
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; });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.