我正在尝试使用 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: In function
'int do_crazy_calculations(int)'
:
CplusplusExperiment.cpp:10:10: error:'unordered_set'
does not name a type
make: *** [CplusplusExperiment.o] Error 1
但是,我确实为 unordered_set
分配了一个类型 - int
对吧?这个错误是什么意思?
最佳答案
- 首先,永远不要做
using namespace std
——这是一千个令人沮丧的错误的根源。 -
done_before
实际上没有命名类型,它命名了一个变量。要命名一个类型,您可以使用typedef unordered_set<int> done_before_type
, 然后done_before_type::iterator
将工作。 - 您需要包含标题
<unordered_set>
- 最后,您需要一个支持它的编译器(VS 2010+、GCC 4.4+)或通过 Boost 或 TR1 库正确使用它。
关于c++ - 无序集的编译问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9086915/