【发布时间】:2019-01-05 21:18:52
【问题描述】:
我正在尝试使用比较器函数从另一个映射创建映射,该比较器函数的键值对中的新值与存储在映射中的键值对中的先前值不同。
编译以下代码时出现编译错误。该代码有什么问题?还有更好的方法来实现这一点吗?
#include <iostream>
#include <map>
#include <set>
#include <algorithm>
#include <functional>
int main() {
// Creating & Initializing a map of String & Ints
std::map<std::string, int> mapOfWordCount = { { "aaa", 10 }, { "ddd", 41 },
{ "bbb", 62 }, { "ccc", 10} };
// Declaring the type of Predicate that accepts 2 pairs and return a bool
typedef std::function<bool(std::pair<std::string, int>, std::pair<std::string, int>)> Comparator;
// Defining a lambda function to compare two pairs. It will compare two pairs using second field
Comparator compFunctor =
[](std::pair<std::string, int> elem1 ,std::pair<std::string, int> elem2)
{
return elem1.second != elem2.second;
};
// Declaring a set that will store the pairs using above comparision logic
std::map<std::string, int, Comparator> setOfWords(
mapOfWordCount.begin(), mapOfWordCount.end(), compFunctor);
return 0;
}
第二张地图的预期输出是:
{ "aaa", 10 }
{ "ddd", 41 }
{ "bbb", 62 }
这意味着,{ "ccc", 10 } 必须被忽略。
错误摘录:
sortMap.cpp:25:70:从这里需要 /opt/tools/installs/gcc-4.8.3/include/c++/4.8.3/bits/stl_tree.h:1422:8: 错误:调用不匹配 '(std::function, int>, std::pair, int>)>) (const std::basic_string&, const key_type&)’ && _M_impl._M_key_compare(_S_key(_M_rightmost()), __k)) ^ 在 /opt/tools/installs/gcc-4.8.3/include/c++/4.8.3/bits/stl_algo.h:66:0 中包含的文件中, 来自/opt/tools/installs/gcc-4.8.3/include/c++/4.8.3/algorithm:62, 来自 sortMap.cpp:4:/opt/tools/installs/gcc-4.8.3/include/c++/4.8.3/functional:2174:11: 注:候选人是: 类函数<_res> ^ /opt/tools/installs/gcc-4.8.3/include/c++/4.8.3/functional:2466:5: 注意:_Res std::function<_res ...>::operator()(_ArgTypes ...) const [with _Res = bool; _ArgTypes = {标准::对, std::allocator >, int>, std::pair, std::allocator >, int>}] 函数<_res>:: ^
【问题讨论】:
-
std::map需要一个谓词来对键进行排序。您的compFunctor与所需谓词的类型不匹配。 (这可能是编译错误的原因。)但即使修复了这个问题,您也会遇到运行时问题,因为缺少对映射键的充分排序。 -
在您暴露错误文本后,请删除我上述评论的“可能”。 ;-)
-
能否请您描述一下您打算如何处理第二张地图?
-
基本上是假设您收到 Key = 3 和 Value = 4,这将被插入到地图中。现在,当我应该添加 Key = 5 和 Value = 4 时,不应将其插入到地图中。现在再次如果我收到 Key = 5 和 Value = 6,地图应该包含 {3,4} 和 {5,6}
-
假设你想对第一个映射的条目进行排序,你需要一个
std::map<int, string>。进一步假设,第一张地图的值是例如单词的出现,值可能不是唯一的。所以,std::multimap会更合适(或std::map<int, std::vector<std::string> >)。
标签: c++ dictionary stl