C ++ STL:使用std :: find查找字符串向量中的字符串不起作用

时间:2015-01-18 23:33:23

标签: c++ string c++11 vector stl

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
    vector<string> vs;
    vs.push_back("i");
    vs.push_back("like");
    vs.push_back("apples");
    vs.push_back("but");
    vs.push_back("am");
    vs.push_back("allergic");
    vs.push_back("to");
    vs.push_back("apples");

    string sbut("but");

    string s = find(vs.begin(), vs.end(), sbut);
    s = find(vs.begin(), vs.end(), "but");

    return 1;
}

这是我的测试代码。 我有一个场景,我在字符串中存储字符串,并且必须检查此向量中是否存在字符串。

我收到以下错误消息,但我无法理解,这两种情况的find会返回不同类型的错误:

stringfind.cpp:20:47: error: conversion from ‘__gnu_cxx::__normal_iterator<std::basic_string<char>*, std::vector<std::basic_string<char> > >’ to non-scalar type ‘std::string {aka std::basic_string<char>}’ requested
     string s = find(vs.begin(), vs.end(), sbut);

stringfind.cpp:21:7: error: no match for ‘operator=’ (operand types are ‘std::string {aka std::basic_string<char>}’ and ‘__gnu_cxx::__normal_iterator<std::basic_string<char>*, std::vector<std::basic_string<char> > >’)
     s = find(vs.begin(), vs.end(), "but");

使用-std = c ++ 11选项进行编译

有人可以告诉我发生了什么以及如何实现这种情况吗?

编辑:对不起我的意思是我使用

进行检查
if(vs.end()!=find(vs.begin(),vs.end(), "but")

过快地写了测试程序

1 个答案:

答案 0 :(得分:3)

find返回迭代器,而不是字符串。您需要检查迭代器是否有效以查看是否找到了该字符串。

vector<string>::iterator it = find(vs.begin(), vs.end(), sbut);
if (it != vs.end()) {
    // string found!
}