简体   繁体   English

C++ STL映射一键二值

[英]c++ STL Map one key two values

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. std::map需要两个模板参数,一个键和一种值类型。 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请花点时间阅读cplusplus.com 上的示例

I like bkausbk's answer and would have commented on the answer but don't have rep.我喜欢 bkausbk 的答案,并且会对答案发表评论,但没有代表。 Map sometimes has a problem with needing a default constructor. Map 有时会遇到需要默认构造函数的问题。 I know this from another SO post .我从另一个 SO 帖子中知道这一点。 I got it to work by setting default arguments (the post has other solutions)我通过设置默认参数让它工作(帖子有其他解决方案)

So I changed the constructor in bkausbk's answer to:所以我将 bkausbk 的答案中的构造函数更改为:

TestValue(int v1 = 0, int v2 = 0, int v3 = 0) : Value1(v1), Value2(v2), Value3(v3) {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM