简体   繁体   English

更改地图中特定键的值

[英]Changing values of a particular key in map

I have a map我有地图

std::map<int,int> Table;

Table.insert(pair<int, int>(5, 1)); 
Table.insert(pair<int, int>(4, 2)); 
Table.insert(pair<int, int>(3, 3)); 
Table.insert(pair<int, int>(2, 4)); 

I want to know how to change the value for a particular key.我想知道如何更改特定键的值。 For eg.例如。 For key 4, I want to increment the value to 3对于键 4,我想将值增加到 3

The documentation is your best friend in such cases.在这种情况下,文档是您最好的朋友。

You should use operator[] from std::map .您应该使用std::map operator[] It returns a reference to the value that is mapped to the given key.它返回对映射到给定键的值的引用。
Note that if the given key does not already exist in the map, it will be inserted.请注意,如果地图中不存在给定的键,则会插入它。

Your example (key: 4, increment by 1/set the value to 3) would be:您的示例(键:4,增加 1/将值设置为 3)将是:

++Table[4];

Or directly:或者直接:

Table[4] = 3;

Since , you have the at() member from std::map that performs the same as operator[]() except that it will not try to insert the key if it does not exist but will throw an std::out_of_range exception instead.,您拥有std::map中的at()成员,其执行与operator[]()相同,除了它不会尝试插入不存在的键,但会抛出std::out_of_range异常。

you can use operator[ ] to insert new key or change value of old key like:您可以使用 operator[ ] 插入新键或更改旧键的值,例如:

Note: If k does not match the key of any element in the container, the function inserts a new element with that key注意:如果 k 与容器中任何元素的键都不匹配,该函数会插入一个具有该键的新元素

std::map<int, int> Table;

Table[5] = 1;
Table[4] = 2;
Table[3] = 3;
Table[5] = 4;

also, you can use at() funnction for change value of key but with this function can't insert a new key like:此外,您可以使用 at() 函数更改键的值,但使用此函数无法插入新键,例如:

std::map<int, int> Table;

Table[5] = 1;
Table.at(5) = 10; // Note that Table.at(3) throws an exception when it does not exist.

If you only want to search the container for and element with a key equivalent to k and did not add a new key, I suggest using it:如果您只想在容器中搜索具有等效于 k 的键的 and 元素并且没有添加新键,我建议使用它:

std::map<int, int> table;

int k = 4; 

Table[5] = 1;
Table[4] = 2;
Table[3] = 3;

if (Table.find(k) != Table.end())
  Table.at(k)++; //or Table[k]++;

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

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