map::insert

5753 ワード

関数の形式:
1.pair<iterator,bool> insert(const value_type &x);
2.iterator insert(iterator position, const value_type &x);
3.template<class InputIterator>
void insert(InputIterator first, InputIterator last);

シーケンスコンテナのinsertと して、 コンテナはそれらの を して をどこに くかを するので、positionパラメータは されます.
パラメータ:
x: された 、タイプはpair、keyとTはそれぞれ するmap key_type,mapped_type
position: の の を します.このパラメータは、 を に する ではありません.
Position of the first element to be compared for the insertion operation.Notice that this does not force the new element to be in that position within the map container (elements in a set always follow a specific ordering), but this is actually an indication of a possible insertion position in the container that, if set to the element that precedes the actual location where the element is inserted, makes for a very efficient insertion operation.iterator is a member type, defined as a bidirectional iterator type.
first,last;
り :
1.pairを します.pair::secondはbool で、 に したかどうかを します(keyがmapにある は に します).pair::firstは を し、 しく した ( に した )またはmapに する ( に した )を します.
2. を し、 しく された またはmapに する するkeyの を します.
プログラムの :
//map::insert
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<char,int> mymap;
map<char,int>::iterator it;
pair<map<char,int>::iterator,bool> ret;
//first insert function version(single parameter):
mymap.insert(pair<char,int>('a',100));
mymap.insert(pair<char,int>('z',200));
ret = mymap.insert(pair<char,int>('z',500));
if (ret.second==false) {
cout << "element 'z' already existed";
cout << " with a value of " << ret.first->second << endl;
}
//second insert function version(with hint position):
it = mymap.begin();
mymap.insert(it, pair<char,int>('b',300));//max efficiency inserting
mymap.insert(it, pair<char,int>('c',400));//no max efficiency inserting
//third insert function version(range insertion)
map<char,int> anothermap;
anothermap.insert(mymap.begin(),mymap.find('c'));
//showing contents:
cout << "mymap contains:
";
for ( it=mymap.begin(); it!=mymap.end(); ++it) {
cout << it->first << "--->" << it->second << endl;
}
cout << "myanothermap contains:
";
for ( it=anothermap.begin(); it!=anothermap.end(); ++it) {
cout << it->first << "--->" << it->second << endl;
}
anothermap = mymap;
cout << "myanothermap contains:
";
for ( it=anothermap.begin(); it!=anothermap.end(); ++it) {
cout << it->first << "--->" << it->second << endl;
}
}

output:
mymap contains:
a--->100
b--->300
c--->400
z--->200
myanothermap contains:
a--->100
b--->300
myanothermap contains:
a--->100
b--->300
c--->400
z--->200