Chinaunix首页 | 论坛 | 博客
  • 博客访问: 245851
  • 博文数量: 52
  • 博客积分: 1355
  • 博客等级: 中尉
  • 技术积分: 485
  • 用 户 组: 普通用户
  • 注册时间: 2008-11-06 12:23
文章分类

全部博文(52)

文章存档

2013年(5)

2012年(16)

2011年(26)

2010年(2)

2009年(1)

2008年(2)

我的朋友

分类: C/C++

2011-07-12 10:00:49

typedef pair value_type;

value_type 被声明为 pair <const , > 但并不是简单的 pair <key_type, mapped_type> 因为用一个非常量的迭代器或引用不能改变关联容器的Key

// map_value_type.cpp

// compile with: /EHsc

#include

#include

int main( )

{

using namespace std;

typedef pair cInt2Int;

map m1;

map :: key_type key1;

map :: mapped_type mapped1;

map :: value_type value1;

map :: iterator pIter;

// value_type can be used to pass the correct type

// explicitly to avoid implicit type conversion

m1.insert ( map :: value_type ( 1, 10 ) );

// Compare other ways to insert objects into a map

m1.insert ( cInt2Int ( 2, 20 ) );

m1[ 3 ] = 30;

// Initializing key1 and mapped1

key1 = ( m1.begin( ) -> first );

mapped1 = ( m1.begin( ) -> second );

cout << "The key of first element in the map is "

<< key1 << "." << endl;

cout << "The data value of first element in the map is "

<< mapped1 << "." << endl;

// The following line would cause an error because

// the value_type is not assignable

// value1 = cInt2Int ( 4, 40 );

cout << "The keys of the mapped elements are:";

for ( pIter = m1.begin( ) ; pIter != m1.end( ) ; pIter++ )

cout << " " << pIter -> first;

cout << "." << endl;

cout << "The values of the mapped elements are:";

for ( pIter = m1.begin( ) ; pIter != m1.end( ) ; pIter++ )

cout << " " << pIter -> second;

cout << "." << endl;

}

Output

The key of first element in the map is 1.

The data value of first element in the map is 10.

The keys of the mapped elements are: 1 2 3.

The values of the mapped elements are: 10 20 30.

阅读(787) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~