4

我正在尝试使用unordered_setC++ 标准库中的一个。我正在使用 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'未命名类型
make:*** [CplusplusExperiment.o] 错误 1

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

4

3 回答 3

13
  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 库正确使用。
于 2012-01-31T21:06:39.377 回答
4

应该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 = ...
于 2012-01-31T21:06:14.093 回答
2

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

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

于 2012-01-31T21:07:25.887 回答