C++——map_1

map(有key和value组成)的遍历,和其它STL的容器一样,都是通过迭代器实现的;
因此判断value(而不是key)是否存在:
方法一:你可以循环遍历map,然后按照second来取值判断;

方法二:当然也可以通过stl中的算法,比如find_if,并配合函数或函数对象来实现。
下面的例子:
1. 先输入一个字符串, 然后以空格分割装入的map中。
2. 循环遍历这个map,打印key和value(同上面的方法一,稍稍比较即可判断某个value是否存在);
3. 把两个string写入vector中,然后判断string的值是否map中已存在(例子里面一个存在,另一个不存在),其中的判断,用到了上面提及的方法二。
其它stl类和map的结合,如法炮制即可。

#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <functional> 

using namespace std;

struct FoundByValue 
{
    FoundByValue(string str):_s(str) {}
    bool operator() (const pair<int, string>& v) const
    {
        return v.second == _s;
    }
private:
   string _s;    
};

int main(int argc, char** argv) 
{
    char sz[] = "I am a map of int and string.";
    string token;
    stringstream ss (sz);    
    map<int, string> mis;
    map<int, string>::iterator itmap;    
    int i;

    i = 0;
    while (getline(ss, token, ' ')) 
    {    
        mis[i++] = token;
    }

    for (itmap = mis.begin(); itmap != mis.end(); ++itmap)
    {
        cout << (*itmap).first << " " << (*itmap).second << endl;
    }

    vector<string> vs;
    vs.push_back("int");
    vs.push_back("float");

    for (vector<string>::iterator it = vs.begin(); it != vs.end(); ++it)    
    {
        itmap = find_if(mis.begin(), mis.end(), FoundByValue(*it));
        if ( itmap != mis.end())
           cout << *it << " already exists." << endl;
        else
           cout << *it << " is not found." << endl;
    } 

    return 0;
}

转载自百度知道:http://zhidao.baidu.com/link?url=BRYIPGUHGlcr_wbHHvSCQI_RMXvEvJIZjfVGU8BrVZqMQf3hxO1tkf3VHm9zDQPn08v2bIqtZfqouZWQbkX-vq

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值