写个小程序,热热身:

 

#pragma warning(disable : 4786) //VC++6.0对map的支持不好,所以要把这个东东放在最前面,否则警告一大堆
#include <map>
#include <string>
#include <iostream>
using namespace std;

typedef map<int, string> MyMap;

int main()
{
	MyMap m;
	m.insert(make_pair<int, string>(1, "hello"));
	m.insert(make_pair<int, string>(2, "world"));

	MyMap::iterator it;
	for(it = m.begin(); it != m.end(); it++)
	{
		cout << it->first << it->second <<endl;
	}

	return 0;
}

      

 

       上述程序的结果和下面程序的结果是一样的:

 

#pragma warning(disable : 4786) //VC++6.0对map的支持不好,所以要把这个东东放在最前面,否则警告一大堆
#include <map>
#include <string>
#include <iostream>
using namespace std;

typedef map<int, string> MyMap;

int main()
{
	MyMap m;

	// 换一下插入的顺序
	m.insert(make_pair<int, string>(2, "world"));
	m.insert(make_pair<int, string>(1, "hello")); 

	MyMap::iterator it;
	for(it = m.begin(); it != m.end(); it++)
	{
		cout << it->first << it->second <<endl;
	}

	return 0;
}

      

 

      当然呢, 我们可以修改一下pair, 如下:

 

#pragma warning(disable : 4786) //VC++6.0对map的支持不好,所以要把这个东东放在最前面,否则警告一大堆
#include <map>
#include <string>
#include <iostream>
using namespace std;

typedef map<int, string> MyMap;

int main()
{
	MyMap m;

	// pair也是一个类模板, 下面有强制类型转换的过程
	m.insert(pair<int, string>(2, "world"));
	m.insert(pair<int, string>(1, "hello")); 

	MyMap::iterator it;
	for(it = m.begin(); it != m.end(); it++)
	{
		cout << it->first << it->second <<endl;
	}

	return 0;
}

 

       其实, 在新的C++ 11中有更简洁的方法, 在此, 我就不过多介绍了。

 

       下面, 我们来验证一下: map的first成员不可以修改(是常引用), 而second成员可以修改。(请注意: pair的first和second成员都可以修改)

 

#pragma warning(disable : 4786) //VC++6.0对map的支持不好,所以要把这个东东放在最前面,否则警告一大堆
#include <map>
#include <string>
#include <iostream>
using namespace std;

typedef map<int, string> MyMap;

int main()
{
	MyMap m;

	m.insert(pair<int, string>(2, "world"));
	m.insert(pair<int, string>(1, "hello")); 

	MyMap::iterator it = m.begin();
	
	
	it->first = 100; // error, first是不能修改的
	it->second = "good"; // ok, second是可以修改的

	return 0;
}

     

 

     说明一下, map在实际开发中是经常用到的, 后面我们还会继续介绍到。

 

 

 

 

 

 


 


本文转载:CSDN博客