compilation problems with unordered set

dangerChihuahua007 picture dangerChihuahua007 · Jan 31, 2012 · Viewed 17.4k times · Source

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?

Answer

Kornel Kisielewicz picture Kornel Kisielewicz · Jan 31, 2012
  1. First of all, never do using namespace std -- it's a source of a thousand frustrating errors.
  2. done_before really doesn't name a type, it names a variable. To name a type you could use typedef unordered_set<int> done_before_type, then done_before_type::iterator will work.
  3. You need to include the header <unordered_set>
  4. Finally, you need a compiler that supports it (VS 2010+, GCC 4.4+) or a proper usage via Boost or TR1 libraries.