问题描述
这是我通过地图定义的方式。
This is how I have defined by map.
std::map<std::pair<std::string,std::string>, int> edMap;
我很困惑如何插入值,我总是收到编译错误。
这是我要插入的方式。
I am confuse on how to insert values , I am getting compilation error always.This is how I am trying to insert.
std::pair<std::string,std::string> key;
edMap.insert(key,d);
编译错误
1>------ Build started: Project: spellsuggest, Configuration: Debug Win32 ------
1>Compiling...
1>breathalyzer.cpp
1>d:\personal\spellsuggest\spellsuggest\breathalyzer.cpp(70) : error C2664: 'std::_Tree<_Traits>::iterator std::_Tree<_Traits>::insert(std::_Tree<_Traits>::iterator,const std::pair<_Ty1,_Ty2> &)' : cannot convert parameter 1 from 'std::pair<_Ty1,_Ty2>' to 'std::_Tree<_Traits>::iterator'
1> with
1> [
1> _Traits=std::_Tmap_traits<std::pair<std::string,std::string>,int,std::less<std::pair<std::string,std::string>>,std::allocator<std::pair<const std::pair<std::string,std::string>,int>>,false>,
1> _Ty1=const std::pair<std::string,std::string>,
1> _Ty2=int
1> ]
1> and
1> [
1> _Ty1=std::string,
1> _Ty2=std::string
1> ]
1> and
1> [
1> _Traits=std::_Tmap_traits<std::pair<std::string,std::string>,int,std::less<std::pair<std::string,std::string>>,std::allocator<std::pair<const std::pair<std::string,std::string>,int>>,false>
1> ]
1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
1>Build log was saved at "file://d:\personal\spellsuggest\spellsuggest\Debug\BuildLog.htm"
1>spellsuggest - 1 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
推荐答案
让我们尝试:
typedef std::pair<std::string, std::string> my_key_type;
typedef std::map<my_key_type, int> my_map_type;
my_map_type m;
m.insert(my_map_type::value_type(my_key_type("A", "B"), 43));
观察到映射 value_type
code> std :: pair< const key_type,mapped_type> ,所以在你的情况下它的 std :: pair< my_key_type,int>
Observe that the map's value_type
is always std::pair<const key_type, mapped_type>
, so in your case it's std::pair<my_key_type, int>
-- a pair whose first member is itself a pair!
考虑到这一点,你也可以使用 make_pair
:
With that in mind you can alternatively use make_pair
:
m.insert(std::make_pair(my_key_type("C", "D"), -5));
最后,正如Sven指出的,可能有或没有一个对的比较运算符有,虽然);所以如果没有,你必须自己写一个。词汇比较两个要素应该做。 Sophie等待: - )
Finally, as Sven points out, there may or may not be a comparison operator for pairs (I think there is, though); so if there isn't, you have to write one yourself. Lexicographic comparison on the two elements should do. Sophie awaits :-)
(这里是词典对比较;你不需要这样写,它已经存在 p>
(Here's the lexicographic pair comparison; you don't need to write this, it's already there:)
template<typename S, typename T>
bool operator<(const std::pair<S, T> & a, const std::pair<S, T> & b)
{
return (a.first < b.first) || (a.first == b.first && a.second < b.second);
}
这篇关于C ++ STL map,std :: pair作为键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!