无序集的编译问题
我正在尝试使用 C++ std 库中的 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'
未命名类型
make: *** [CplusplusExperiment.o] 错误 1
但是,我确实为 unordered_set
- int
分配了一个类型,对吗?这个错误是什么意思?
I am trying to use an unordered_set
from the C++ std library. I am using the std namespace.
using namespace std;
The unordered_set
is within a function of mine. I would like to use it to memoize some values.
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();
}
}
However, I am getting this compilation error:
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
However, I did assign a type to unordered_set
- int
right? What does this error mean?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
using namespace std
——这会导致上千个令人沮丧的错误。done_before
实际上并不命名类型,而是命名变量。要命名类型,您可以使用 typedef unordered_setdone_before_type::iterator
就会起作用。using namespace std
-- it's a source of a thousand frustrating errors.done_before
really doesn't name a type, it names a variable. To name a type you could usetypedef unordered_set<int> done_before_type
, thendone_before_type::iterator
will work.<unordered_set>
应该是
unordered_set::iterator node_found = ...
我通常使用 typedef 来简化模板化变量的命名:
should be
unordered_set<int>::iterator node_found = ...
I usually use a typedef to simplify naming of templated variables:
首先,unordered_set是TR1或C++11中的。
其次,您在函数内声明该集合,然后测试其中的某些值。有什么意义?每次调用该函数时,集合都会为空。编辑:抱歉,没有注意到它是静态的。
First of all, unordered_set is in TR1 or C++11.
And second, you are declaring the set inside your function and then testing for some value in it. What's the point? The set's gonna be empty each time you call the function. EDIT: sorry, didn't notice it was static.