您的位置:首页 > 编程语言 > C语言/C++

C++语法基础--关联容器--map(一)--constructor,operator[],insert

2013-07-09 13:49 495 查看
1关联容器类型




set和map类型的对象所包含的元素都具有不同的键,不允许为同一个键添加第二个元素

2.map类型(#include<map>)

原型:


template<class Key,class T,class Compare = std::less<Key>,

class Allocator = std::allocator<std::pair<const Key, T> >>

class map;



*map是键-值对的集合,可以用键作为下标来获取一个值

3.map的构造函数







原型:

empty:

explicit map (const key_compare& comp = key_compare(),

const allocator_type& alloc = allocator_type());

range:

template <class InputIterator>

map (InputIterator first, InputIterator last,

const key_compare& comp = key_compare(),

const allocator_type& alloc = allocator_type());

copy :

map (const map& x);



eg:

map<char,int> mp1;

mp1['a']=10;

mp1['b']=30;

map<char,int> mp2 (mp1.begin(),mp1.end());

map<char,int> mp3 (mp2);

4.键类型的约束

*默认情况下,标准库使用键类型定义的<操作符来实现键的比较

*键类型必须支持<操作符

5.map定义的类型






6.map迭代器进行解引用将产生pair类型的对象

*解引用获得的pair对象,它的值成员可以修改,但键成员不可以修改

eg:

typedef map<char,int> my_map;

my_map mp1;

mp1['a']=10;

mp1['b']=30;

my_map::iterator it=mp1.begin();

cout<<(*it).first<<endl;

cout<<it->second<<endl;

it->first='c'; //error

it->second=20;
//ok



7.使用下标访问map对象

原型:

mapped_type& operator[] (const key_type& k)

*用下标访问不存在的元素,将会在map容器中添加一个新的元素,它的键即为该下标值

eg:

typedef map<char,int> my_map;

my_map mp1;

mp1['a']=10;

cout<<mp1['a']<<endl; //10,查找的键'a'存在,返回map中对应的值


cout<<mp1['b']<<endl; //0,查找的键'b不'存在,在map容器中添加一个新的元素,并把内置类型初始化为 //0(如果是类类型则调用默认构造函数)

cout<<mp1.size()<<endl;//2

8.向map添加成员insert()






原型:

single element:

pair<iterator,bool> insert (const value_type& val);

with hint :

iterator insert (iterator position, const value_type& val);

range :

template <class InputIterator>

void insert (InputIterator first, InputIterator last);



eg:

int main ()

{

typedef map<string,int> mymap;

typedef map<string,int>::value_type myvalue;

mymap mp1;

// 第一种插入方法([b]single element)


mp1.insert ( myvalue(string("jack"),19) );

mp1.insert ( myvalue(string("tom"),20) );

pair<mymap::iterator,bool> res;

res = mp1.insert ( myvalue(string("tom"),21) );

if (res.second==false)
//检测insert的返回值

{

cout << "element 'tom' already existed";

cout << " with a value of " << res.first->second << '\n';
//20

}

// 第二种插入方法 (with hint position):

mymap::iterator it = mp1.begin();

mp1.insert (it, myvalue(string("jany"),17));



// 第三种插入方法 (range insertion):

mymap mp2;

mp2.insert(mp1.begin(),mp1.find(string("tom")));

//输出mp1的内容

cout << "mp1 contains:\n";

for (it=mp1.begin(); it!=mp1.end(); ++it)

cout << it->first << " : " << it->second << '\n';

//输出mp2的内容

cout << "mp2 contains:\n";

for (it=mp2.begin(); it!=mp2.end(); ++it)

cout << it->first << " : " << it->second << '\n';

return 0;

}



[/b]
运行结果:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: