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?
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 ).
Hi Naveen, *You can Create map of both String and Integer, just keep sure that your key is Unique.
Use Object#toString() . String string = map. toString(); That's after all also what System.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With