【问题标题】:std::tr1::unordered_map insert errorstd::tr1::unordered_map 插入错误
【发布时间】:2015-01-31 23:06:13
【问题描述】:

我无法对 std::tr1::unordered_map 使用插入函数,尝试构建时不断收到以下错误:

/usr/include/c++/4.2.1/tr1/hashtable:855:14: error: cannot initialize return object of type '_Node *' (aka '_Hash_node<std::pair<const unsigned long long, Order>, false> *') with an rvalue of type 'bool'
      return false;
         ^~~~~

我的精简代码如下:

#include <tr1/unordered_map>
#include "handler.h"
#include "endian_tools.h"

using namespace std::tr1;
using namespace std;

unordered_map<uint64_t, Order> book_by_id;

uint64_t ref_num = be64toh(msg);
Order order(ref_num);

book_by_id.insert(make_pair<uint64_t,Order>(ref_num, order));

我认为这可能与我使用 long long 作为键的事实有关,但即使将其更改为 int 后,我​​也会遇到相同的错误。有什么想法吗?我在网上的任何地方都找不到其他出现此错误的人。

【问题讨论】:

  • 你用的是什么编译器?
  • 仅供参考,使用std::make_pair 函数的原因是您不必显式指定类型(让模板类型推导为您完成工作)。相反,您只需执行 book_by_id.insert(make_pair(ref_num, order));
  • tr1::unordered_map ?你的编译器几岁了?
  • 您的tr1 实现是否有专门的std::hash&lt;uint64_t&gt;?自从我查看某人的 tr1 impl 以来就一直存在,但可能值得你花时间看看你的。
  • 我在 Eclipse 上使用 Mac OSX GCC 编译器。我使用 tr1 的原因是,如果我只执行 #include &lt;unordered_map&gt;,我在声明 unordered_map 时会收到 invalid template arguments 错误。我将其更改为 tr1 并解决了问题。我应该不使用 tr1 并尝试找到解决无效模板问题的另一种方法吗?

标签: c++ unordered-map tr1


【解决方案1】:

我认为问题出在我的 gcc 版本以及它缺乏对 C++11 的支持(Mac OSX 默认使用旧的 gcc 版本,这就是我在这种情况下的最终结果)。我使用 macports 将我的 gcc 升级到 4.8,将其设置为默认值,并按照以下说明使用 CrossGCC 编译器创建了一个新项目:use c++11 on mac os x mountain lion with eclipse (Juno or Kepler)。我删除了 tr1,现在只使用#include &lt;unordered_map&gt;。现在我使用 insert 方法没有问题了。

感谢大家的建议。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-29
    • 1970-01-01
    相关资源
    最近更新 更多