I have a situation where I have a map with one key and two values ex.
std::map<std::string, std::pair<double, double> > myMultiValueMap
depending on a condition I need to either update one value or the other.
I'd am looking for syntax to insert/ find the key and update either values in this map
yes I have used the insert on Maps before, but was not sure on multivalue map
std::map<std::string,double> myMap;
myMap.insert(std::make_pair("12345",0.00));
and find and update too
std::map<std::string,double>::iterator it = myMap.find(("12345");
std::map
requires two template arguments, one key and one value type. But it is up to you to use arbitrary type for "value".
struct TestValue {
int Value1;
int Value2;
int Value3;
TestValue(int v1, int v2, int v3) : Value1(v1), Value2(v2), Value3(v3) {}
};
std::map<std::string, TestValue> myMap;
myMap["test"] = TestValue(1, 2, 3);
Inserting an item into the map:
myMultiValueMap[strKey] = make_pair(firstDouble, secondDouble);
Checking if an item exists:
if( myMultiValueMap.find(strKey) != myMultiValueMap.end() ) {
// Item Exists
}
Updating an item:
myMultiValueMap[strKey].first = newFirstDouble;
myMultiValueMap[strKey].second = newSecondDouble;
You should use this for these to work
using namespace std;
Please take time and read the examples from cplusplus.com
I like bkausbk's answer and would have commented on the answer but don't have rep. Map sometimes has a problem with needing a default constructor. I know this from another SO post . I got it to work by setting default arguments (the post has other solutions)
So I changed the constructor in bkausbk's answer to:
TestValue(int v1 = 0, int v2 = 0, int v3 = 0) : Value1(v1), Value2(v2), Value3(v3) {}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.