Question

I don't understand why the second block of code in this short example does not compile correctly. It is my understanding that the second parameter in the <> represents the value, which doesn't need to be unique. Why is the second block of code throwing a compiler error, and what do I need to do to remedy it?

// Unordered Map example .cpp

#include <stdio.h>
#include <string>
#include <cstring>
#include <unordered_map>

using namespace std;

int main(void) {

    // This works as expected
    unordered_map<std::string, int> m;
    m["foo"] = 42;
    printf("%i\n", m["foo"]);

    // This this doesn't compile
    unordered_map<std::string, std::string> m1;
    m1["foo"] = "42";
    printf("%s\n", m1["foo"]);

    return 0;
}

I am compiling this code on CentOS 5.8 using

g++44 -c -Wall -std=c++0x -g map_example.cpp

and these are the errors I am getting

map_example.cpp: In function ‘int main()’:
map_example.cpp:20: warning: cannot pass objects of non-POD type ‘struct std::basic_string<char, std::char_traits<char>, std::allocator<char> >’ through ‘...’; call will abort at runtime
map_example.cpp:20: warning: format ‘%s’ expects type ‘char*’, but argument 2 has type ‘int’

If I am having trouble with a basic c++ class such a std:string what do I need to do to have a custom class as a value, where can I find a fully implemented minimal example?

Was it helpful?

Solution

printf does not work with std::string. Either use cout << m1["foo"] or printf("%s", m1["foo"].c_str())

OTHER TIPS

printf("%s\n", m1["foo"]); is C.

For c++ you should use std::cout to have both the string and the int map's values printed out as expected.

The compiler cannot do a translation for a std::string object automatically to const char* (there is no conversion to const char* by default: Why does std::string not provide a conversion to const char*?)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top