compilation problems with unordered set
-
21-04-2021 - |
문제
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?
해결책
- First of all, never do
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.- You need to include the header
<unordered_set>
- Finally, you need a compiler that supports it (VS 2010+, GCC 4.4+) or a proper usage via Boost or TR1 libraries.
다른 팁
should be unordered_set<int>::iterator node_found = ...
I usually use a typedef to simplify naming of templated variables:
typedef unordered_set<int> t_done_before;
static t_done_before done_before;
t_done_before::iterator node_found = ...
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.