c++ map: 使用struct或者数组做value

Notice

  1. 如果是program中有两个map对象,可能你需要两个map iterator,但是注意两个iter object不能命名一样,可以分别为iter1, iter2

Example

#include <iostream>
#include <map>

using namespace std;

struct Triple
{
   int color [3];
};


struct student
{
	string name;
	int age;
};

int main()
{
	/*  Array as a map's value */
	Triple red = {1, 0, 0}, green = {0, 1, 0}, blue = {0, 0, 1};
	std::map<int, Triple> colors;
	colors.insert(std::pair<int, Triple>(0, red));
	colors.insert(std::pair<int, Triple>(1, green));
	colors.insert(std::pair<int, Triple>(2, blue));

	map<int, Triple>::iterator it;
	for(it = colors.begin(); it != colors.end(); it++) {
		printf("%d --- %d\n", it->first, it->second.color[0]);
	}


	student st1 = {"muahao", 20};
	student st2 = {"jack", 21};

	map<int, struct student> mp;
	mp.insert(pair<int, student>(0, st1));
	mp.insert(pair<int, student>(1, st2));

	map<int, student>::iterator it2;
	for (it2 = mp.begin(); it2 != mp.end(); it2++) {
		printf("%d-----age:%d \n", it2->first, it2->second.age);
		cout << "name:" << it2->second.name << endl;
	}


	return 0;
}
#./v3
0 --- 1
1 --- 0
2 --- 0
0-----age:20
name:muahao
1-----age:21
name:jack
posted @ 2018-04-14 15:04  苏小北1024  阅读(2781)  评论(0编辑  收藏  举报