c++ - 无法将 map 插入 vector 内?

标签 c++ vector dictionary

下面的代码不起作用,它给出了以下错误:

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/

相关文章:

c++ - 如何为类编写转换为引用到数组的运算符?

c++ - 如何将现有项目添加到 Geany

c++ - 没有用于调用 'merge(std::vector<int>&, std::vector<int>&) 的匹配函数

c++ - 对 vector 中的点进行排序以形成轮廓

java - android字典int,Imageview

c++ - 为什么 'insert' 在字符串填充中比 'append' 快?

c++ - 获取辅助监视器的友好名称

c++ - 如何根据参数的大小在函数内声明一个数组?

python - 带有可选字典键值的字符串格式

python - 方法作为字符串存储到运行的方法中