繁体   English   中英

转移地图 <string, pair> 矢量

[英]Transfer map<string, pair> to vector

所以我有这张地图

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

它保存文本文件中的所有单词,该对中的第一个int是单词的出现频率,第二个是其第一个字符在文本文件中的位置。 这些都是经过计算的,地图工作正常。

然而

我需要将这些单词打印出来,并按频率降序排列。 我需要位置计数器,因为如果两个单词具有相同的频率,则文件中第一位的单词应该在列表中第一位。

如何将此地图转换为矢量?

我试过了

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

无济于事

++++++++++++++++++++++++++++++++++++++++++++++++++++ ++

好的,所以我将wordList更改为vector<pair<string, pair<int, int> > >现在我的副本可以了。 感谢大伙们

一种简单的方法是创建具有所有三个字段的结构:

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

接下来是遍历地图,创建上述结构的实例,将其填充并附加到向量中:

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

现在,将填充矢量,排序顺序。 可以通过使用std::sort()和自定义比较函数来更改顺序。

这是一个有点昂贵的解决方案,它通过引用映射来对字符串列表进行排序:

// 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.

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