无序集的编译问题

compilation problems with unordered set

本文关键字:问题 编译 无序      更新时间:2023-10-16

我正在尝试使用C++标准库中的unordered_set。我使用的是std命名空间。

using namespace std;

unordered_set在我的功能范围内。我想用它来记忆一些价值观。

int do_crazy_calculations(int n) {
    static unordered_set<int> done_before;
    done_before::iterator node_found = done_before.find(n);
    // n has not been seen before, so do calculations and memoize the result.
    if (node_found == done_before.end()) {
        int result = actually_do_calculations(n);
        done_before.insert(n, result);
        return result;
    }
    // n has already been seen before, just return the memoized value.
    else {
        return node_found.get();
    }
}

然而,我得到了这个编译错误:

CplusplusExperiment.cpp:在函数'int do_crazy_calculations(int)'中:
CplusplusExperiment.cpp:10:10:错误:'unordered_set'未命名类型
制造商:***[CplusplusExperiment.o]错误1

但是,我确实为unordered_set-int分配了一个类型,对吗?这个错误是什么意思?

  1. 首先,永远不要做using namespace std——它是一千个令人沮丧的错误的来源
  2. done_before实际上并没有命名类型,而是命名变量。要命名一个类型,可以使用typedef unordered_set<int> done_before_type,然后done_before_type::iterator就可以了
  3. 您需要包括标题<unordered_set>
  4. 最后,您需要一个支持它的编译器(VS 2010+,GCC 4.4+),或者通过Boost或TR1库进行正确使用

应为unordered_set<int>::iterator node_found = ...

我通常使用typedef来简化模板变量的命名:

typedef unordered_set<int> t_done_before;
static t_done_before done_before;
t_done_before::iterator node_found = ...

首先,unordered_set在TR1或C++11中。

其次,在函数中声明集合,然后测试其中的一些值。这有什么意义?每次调用函数时,集合都将为空。编辑:对不起,没有注意到它是静态的。