3

I'm not sure I completely understand hash tables/unordered maps. When I do the following, the code compiles and works properly:

#include <tr1/unordered_map>

int main() {
    tr1::unordered_map<string, int> base;
    string string1;
    int integer1;

    base["A"] = 0;

    string1 = "A";
    integer1 = base[string1];
    cout << integer1 << endl;
    return 0;
}

But this doesn't compile:

#include <tr1/unordered_map>

int main() {
    tr1::unordered_map<int, char> base;
    char char1;
    int integer1;

    base[1] = 'A';

    integer1 = 1;
    char1 = base[integer1];
    cout << char1 << endl;
    return 0;
}

This yields this error:

error: no match for call to '(std::tr1::unordered_map<int, char, std::tr1::hash<int>, s std::equal_to<int>, std::allocator<std::pair<const int, char> >, false>) (int*)'

Could someone explain to me this problem? I don't think I understand how unordered_map works. I'm compiling with gcc 4.2.1 on an Apple.

6
  • 4
    The second snippet with a couple of lines' fix compiles just fine with gcc. See this. What compiler are you on?
    – dirkgently
    Jun 14, 2012 at 19:19
  • @dirkgently I'm using g++ 4.2.1, maybe I should update? Jun 14, 2012 at 19:27
  • That is pretty old considering GCC released 4.7 (with a wonderful C++11 support). It could be a bug in the implementation. So, yes, I guess you will need to upgrade. Also, if you're on Apple, this may be a bit behind actual GCC 4.2.1!
    – dirkgently
    Jun 14, 2012 at 19:31
  • @dirkgently I am on an Apple. Is there any problem upgrading past what Apple "supports"? Jun 14, 2012 at 19:39
  • I can't really say, I haven't touched Apple in a while. But from what I hear, it should be fairly easy to keep both (the existing and a new one).
    – dirkgently
    Jun 14, 2012 at 19:42

1 Answer 1

0

The following compiles and works fine with both Visual C++ 10.0 and MinGW g++ 4.6.1:

#include <iostream>
#include <unordered_map>

int main()
{
    using std::unordered_map;
    using std::cout;  using std::endl;

    unordered_map<int, char> base;
    char char1;
    int integer1;

    base[1] = 'A';

    integer1 = 1;
    char1 = base[integer1];
    cout << char1 << endl;
    return 0;
}

TR is short for “Technical Report”. TR1 was the first technical report, and contained extensions to the standard library. Those extensions have already been adopted in the C++11 standard, and most have already been implemented in e.g. Visual C++ and g++.

So, just use the standard library directly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.