Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does map<string, string> accept ints as values?

Tags:

c++

dictionary

I've recently been jarred by this:

#include <map>
#include <string>
#include <iostream>

using namespace std;

int main() {
    map<string, string> strings;
    strings["key"] = 88;  // surprisingly compiles
    //map<string, string>::mapped_type s = 88;  // doesn't compile as expected

    cout << "Value under 'key': '" << strings["key"] << "'" << endl;

    return 0;
}

It prints 'X' which is 88 in ASCII.

Why does a string map accept ints as values? The documentation for map's operator[] says it returns mapped_type& which is string& in this case and it doesn't have an implicit conversion from int, does it?

like image 823
Tomek Sowiński Avatar asked Mar 25 '15 12:03

Tomek Sowiński


People also ask

Can I use int in HashMap?

In the ArrayList chapter, you learned that Arrays store items as an ordered collection, and you have to access them with an index number ( int type). A HashMap however, store items in "key/value" pairs, and you can access them by an index of another type (e.g. a String ).

Can we store String in map?

Hi Naveen, *You can Create map of both String and Integer, just keep sure that your key is Unique.

Can we convert map to String?

Use Object#toString() . String string = map. toString(); That's after all also what System.


2 Answers

This is because, as you say, operator[] returns a std::string&, which defines an operator= (char c). Your commented-out example does not call the assignment operator, it is copy-initialization, which will try to call explicit constructors of the class, of which there are no applicable ones in std::string.

like image 174
TartanLlama Avatar answered Nov 14 '22 10:11

TartanLlama


To complete the picture, note that:

strings[88] = "key"; 

does not compile as there is no std::string constructor from char/int. For char, std::string only defines the assignment operator.

like image 21
Antonio Avatar answered Nov 14 '22 10:11

Antonio