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

转载于:https://www.cnblogs.com/muahao/p/8831948.html

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值