Hello so i have this error while using unordered maps:
no known conversion for argument 1 from 'std::string {aka std::basic_string<char>}' to 'const key_type& {aka const int&}'
what i am trying to do is to find a pair in a map
1 2 3 4 5 6 7 8 9 10 11
//(private attribute of class)
std::unordered_map<int, std::string> titles;
//in a function¨
void function(std::string title)
{
std::unordered_map<int, std::string>::const_iterator it = titles.find(title);
std::cout<<it->first<< std:endl;
//other stuff
}
PLEASE ALWAYS USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post. http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.
Thanks for the link.
However i still don't see how i can solve this.
I have a string passed as a parameter and i need to find the int associated with it ...
There are 2 ways to approach your problem. The first is to change titles so that the string is the key and the int is the value: std::unordered_map<std::string, int> titles;
In order to make this change you will actually change the meaning of the map. However, if you are looking for an integer based on a title, maybe you have created the map incorrectly. It all depends on how you intended to use the map.
The second is to iterate through the unordered_map and check each value against the title. When you find a match, print the key value. You can either break out of your loop when you find one or go through the entire unordered map and print out all keys that map to the desired title.
As indicated, std::unordered_map associates a key with a value, not a value with a key. Indeed, it's quite possible that multiple keys map to the same value.
no match for 'operator==' (operand types are 'const std::basic_string<char>' and 'const std::initializer_list<const char*>')
http://cpp.sh/2sg4d
since your program runs at coliru it's probably complier specific?
however i still wanted to know your reasons behind passing the search key as uniform reference and using std::forward instead of const reference with its resultant lamba capture by reference, something like:
The paper apparently was considered late in the standardization process, but I still have no clue what papers were accepted when, and when those changes were implemented.
As far as I can tell, it's a compiler support issue, and that snippet is well-formed since C++14.
I still wanted to know your reasons behind passing the search key as uniform reference
I can't think of any reasons to use a forwarding reference. The forwarding process incurs only one copy or move, which reduces generality and maybe reduces performance. It simultaneously reduces const-correctness, since of course the referent is possibly mutable.
I need to learn to pay more attention while reading my posts. Thanks for that - the version you present is much superior ;)