Re: std::map insert element issue
On Feb 5, 5:51 am, zs0723 <zs0...@gmail.com> wrote:
I need to changed the value of a key in std::map, i have written the
following code :
#include <map>
#include <iostream>
#include <string>
using namespace std;
int main()
{
typedef map<string,string> TABLE;
typedef TABLE::iterator ITERATOR;
TABLE table;
table.insert(TABLE::value_type("zs","victor"));
if(table.insert(TABLE::value_typezs","xiao v")).second) // this
will failed , i can't overwirte the exist key's value
cout<<"insert success\n";
else
cout<<"insert failied\n";
// but use like array 's [] , it's ok
// table["zs"]="victor";
// table["zs"]="xiao v";
for(ITERATOR itr=table.begin();itr != table.end() ; ++itr)
{
cout<<itr->first <<":"<<itr->second;
cout<<endl;
}
cout<<std::endl;
}
My question is :
Why insert method can't overwrite the value of the existing key=
..
Thanks
Basically there two ways of inserting item in terms of std::map.
1>
The first and more traditional way is call insert() which applies to
all unique associative containers , e.g std::set , std::map.
When doing a a.insert(t),inserts t into a if and only if a does not
already contain an element whose key is the same as the key of t.
2>
The second way is unique for std::map , called operator[], which is
only for convenience, not necessary needed.
It merely equals to (*(a.insert(t, data_type()).first)).second .
Gob00st