1. 程式人生 > 其它 >關聯容器的插入操作簡單舉例

關聯容器的插入操作簡單舉例

技術標籤:c++

set.insert()

map.insert()

共有三種方法,返回值各不相同,注意!

Extends the container by inserting new elements, effectively increasing the containersizeby the number of elements inserted.

Because element keys in amapare unique, the insertion operation checks whether each inserted element has a key equivalent to the one of an element already in the container, and if so, the element is not inserted, returning an iterator to this existing element (if the function returns a value).


For a similar container allowing for duplicate elements, seemultimap.

An alternative way to insert elements in amapis by using member functionmap::operator[].

Internally,mapcontainers keep all their elements sorted by their key following the criterion specified by itscomparison object. The elements are always inserted in its respective position following this ordering.

The parameters determine how many elements are inserted and to which values they are initialized:

複製程式碼

/*single element (1)*/    
pair<iterator,bool> insert (const value_type& val);

/*with hint (2)    */
iterator insert (iterator position, const value_type& val);

/*range (3)    */
template <class InputIterator>
  void insert (InputIterator first, InputIterator last);
#include <string>
#include <iostream>
#include <list>
#include <vector>
#include <set>
#include <map>
#include <fstream>
using namespace std;
void print(const set<int> &);
void print(const map<string,size_t> &);
int main()
{
//c.insert(v)
//c.emplace(v)
//*single element (1)*/  
//function 's return type is:  
//pair<iterator,bool> insert (const value_type& val);
set<int> s1;
map<string,size_t> m1;
pair<set<int>::iterator,bool> it1 =s1.insert(1);
cout << *it1.first << endl;
cout << it1.second << endl;
s1.emplace(2);
m1.insert({"abc",3});
 /*  this is wrong,why?   m1.emplace({"abcd",5}); */
print(s1);
print(m1);

//c.insert(p,v)
//c.emplace(p,v)
// /*with hint (2) */
//iterator insert (iterator position, const value_type& val);
set<int>::iterator it2 = s1.insert(s1.begin(),123);
m1.insert({"abcd",3});

//c.insert(b,e)
//c.insert(il)
/*range (3)    */
//template <class InputIterator>
//  void insert (InputIterator first, InputIterator last);

s1.insert({111,222,333,444});
m1.insert({{"aaaa",1},{"bbbb",2},{"cccc",3},{"dddd",6}});

	return 0;

}

void print(const map<string,size_t> &m)
{
map<string,size_t>::const_iterator it;
cout << "-------------------------begin----------------------------"<< endl;
for(it = m.begin();it != m.end();++ it)
 {
 cout << it->first << endl;
 cout << it->second <<endl;
 }
cout << "----------------------------end-----------------------------"<<endl;
}
void print(const set<int> &s)
{
cout << "------------------------set begin------------------------------"<<endl;
set<int>::const_iterator it;
for(it = s.begin();it != s.end(); ++it)
        cout << *it << endl;
cout << "---------------------------end---------------------------" <<endl;
}