下面的代码不起作用,它给出了以下错误:
No matching function for call to object of type 'const comparer'
and
Call to object of type 'value_compare' (aka 'std::_1::_map_value_compare, int, comparer, true>') is ambiguous
代码如下:
struct comparer
{
bool operator()(const std::string x, const std::string y)
{
return x.compare(y)<0;
}
};
int main(int argc, char **argv)
{
vector< map<string,int,comparer> > valMapVect;
map<string,int,comparer> valMap;
valMapVect.push_back(valMap);
}
它是用 Xcode 5.x 编译的(在 Mac 上也是如此)。
有人知道哪里出了问题吗?当我在 Linux 上编译它时,我认为它在一段时间前工作。可能吗?
最佳答案
好像libc++希望 comparer
中的函数调用运算符是一个 const
成员函数:
struct comparer
{
bool operator()(const std::string x, const std::string y) const
{ // ^^^^^ fixes the problem
return x.compare(y)<0;
}
};
我个人会将参数作为 std::string const&
(注意 &
)传递,但这不会改变 libc++ 是否喜欢比较对象。我还不确定标准是否要求 const
存在。我没有发现这样的要求,这意味着比较函数必须保留为 mutable
成员。然而,考虑到它通常是无状态的,因此希望从中派生出来不浪费任何内存(即利用空基优化),这可能是 libc++ 所做的。尚不清楚
- 这是 libc++ 中的一个错误,即比较函数对象必须存储在一个
mutable
成员中。 - 在标准中不强制函数调用运算符为
const
。 - 在代码中使用它使函数调用运算符
const
。
但是,最简单的解决方法是使函数调用运算符成为 const
。
关于c++ - 无法将 map 插入 vector 内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19746903/