std::map help

And I need to do one thing with the map that I haven't figured out yet.

Implement this C# code into C++

map.TryGetValue(oldValue, out newValue)

In the C# code map is a dictionary, so I want to do the same thing with a map file, from my understanding the TryGetValue() function looks for the first parameter, in the keys, and if it finds it will store the value into the reference newValue. Any help? Ty :)

Usually anything with Try in front of it in C# checks to see if the retrieval/conversion/etc. is valid so you can use the call in an if statement.

Since the bool is returned, the value is returned by reference in the second parameter (C# has the designation of "out" to indicate that the parameter will be given a value within the method call). You can modify ravenous's code slightly to attain the same features.

Here, TryGetValue() returns true if it can set newValue to the value of the element indicated by the key oldValue . You are using the ! operator on this, so the body of the if only get executed if oldValueisn't a key in the map . If oldValueis in the map, then newValue is set to whatever the value of the element indicated by the key oldValue and the body of the if isn't executed.

So you only need one if statement. I think that the default value comes in when you try to use a key that doesn't exist. In this case, you're using std::map::find to look for elements, so I don't think you have to worry about that (although someone correct me if I'm wrong!). One thing that can happen with maps is if you use the [] operator with a key that doesn't exist, then that element is generated, with the element at the default value. So

int main()
{
map< int, int > m;
cout << m[2] << endl;
return 0;
}

would print 0 , but it will also put the key-value pair 2,0 into the map. So, if you subsequently do cout << m.size(); you will get a size of 1.