简体   繁体   中英

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

The documentation is your best friend in such cases.

You should use operator[] from std::map . 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:

++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.

you can use operator[ ] to insert new key or change value of old key like:

Note: If k does not match the key of any element in the container, the function inserts a new element with that key

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:

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:

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]++;

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.

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