如何在C ++中使用find(itr,itr,const tp)算法和map [英] How to use find(itr ,itr ,const tp) algorithm with map in C++

查看:163
本文介绍了如何在C ++中使用find(itr,itr,const tp)算法和map的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何使用地图查找(itr,itr,key)。此代码与我一起生成错误消息。

Hi, I was wondering how to use find(itr,itr,key) with a map. This code generates an error message with me.

#include <iostream>
#include <string>
#include <algorithm>
#include <map>

using namespace std;

int main()
{
    map<string, string> student_roster;
    student_roster.insert(pair<string,string>("John","a"));
    map<string, string>::iterator itr;
    itr = find( student_roster.begin() , student_roster.end() , "John" );//the error
    if (itr == student_roster.end())
        cerr << "John is not found" << endl;
    else
        cout << "Student : " << itr->first << " Grade : " << itr->second << endl;
}



然而,使用该算法是不合法的吗?



谢谢,山姆。


However, is it not legal to use that algorithm ?

Thanks, Sam.

推荐答案

您正在使用 std :: find [ ^ ]。这是一种适用于任何容器的通用算法,但它不了解容器元素的属性。地图的元素是(键,值)对,而不是字符串。因此,find无法将元素与您传递的字符串作为搜索值进行比较。它需要一个运算符来比较一个不存在的map元素类型和字符串。
You are using std::find[^]. This is a generic algorithm that works for any container, but it has no knowledge of the properties of the elements of the container. The elements of a map are (key,value) pairs, not strings. Therefore, find fails to compare the elements with the string you pass as the search value. It would need an operator to compare a map element type to string, which doesn't exist.


你没有正确使用find。请看下面



You are not using find correctly. Please see below

itr = student_roster.find( "John" );


这篇关于如何在C ++中使用find(itr,itr,const tp)算法和map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆