[英]Push_back into map<int,vector<char>>*
c++ c++
map<int, vector>* maxcounts;地图<int,矢量>* 最大计数;
When I have a pointer to map maxcount how do I write this next statement correctly?当我有一个指向 map maxcount 的指针时,如何正确编写下一条语句?
maxcounts[-m.second]->push_back(m.first); maxcounts[-m.second]->push_back(m.first);
without referencing a pointer I write没有引用我写的指针
maxcounts[-m.second].push_back(m.first); maxcounts[-m.second].push_back(m.first);
map<int, vector<char>> maxcounts;
for (pair<char, int> m : counts) {
if (maxcounts.count(-m.second))
maxcounts[-m.second].push_back(m.first);
else
maxcounts.insert({ -m.second, {m.first} });
}
To figure out how to use a pointer to the map, first rewrite your loop this way:要弄清楚如何使用指向 map 的指针,首先以这种方式重写循环:
std::map<char, int> counts;
//...
std::map<int, std::vector<char>> maxcounts;
for (std::pair<char, int> m : counts)
maxcounts.insert({-m.second, std::vector<char>()}).first->second.push_back(m.first);
Note that the return value for std::map::insert is a std::pair
, where the first
of the pair is an iterator to the existing item if the item already is in the map, or the iterator to the newly inserted item.请注意, std::map::insert的返回值是
std::pair
,如果该项目已经在 map 中,则该对中的first
一个是现有项目的迭代器,或者是新插入项目的迭代器. Thus you can perform the test and insert in one line without need for an if
statement.因此,您可以在一行中执行测试并插入,而无需
if
语句。
The push_back
will occur, regardless of whether the item inserted in the map is new or if the item existed.无论插入到 map 中的项目是新的还是该项目存在,都会发生
push_back
。 Note that for a new entry, the std::vector
being inserted starts as empty.请注意,对于新条目,正在插入的
std::vector
开始为空。
Given this, the pointer to the map version is very simple:鉴于此,指向 map 版本的指针非常简单:
std::map<char, int> counts;
//...
map<int, vector<char>>* maxcounts;
//
for (pair<char, int> m : counts)
maxcounts->insert({-m.second, std::vector<char>()}).first->second.push_back(m.first);
Now, why you need a pointer to a map in the first place is another issue, but to answer your question, the above should work.现在,为什么你首先需要一个指向 map 的指针是另一个问题,但要回答你的问题,上面应该可以工作。
I would likely write something like:我可能会写如下内容:
std::map<int, std::vector<int>>* maxcounts = ...;
for (std::pair<char, int> m : counts)
(*maxcounts)[-m.second].push_back(m.first);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.