在字符串C ++中查找索引

时间:2015-11-13 13:21:51

标签: c++ string vector indexing

#include<iostream>
#include<vector>
#include<string>
using namespace std;

int contain(vector<string> &s_vector, string check)
    {
    cout<<"Input a string to check: ";
    cin>>check;
    if(s_vector=check) 
     return find(&s_vector);
    else
    return -1;
    }

int main(){
    vector<string>s_vector;

    cout<<"Input the size of string vector: ";
    int size;
    cin>>size;

    cout<<"Input "<<size<<"strings: \n"; 
    cin>>s_vector[size];

    cout<<"Strings in the string vector: ";
    for(int i=0; i<s_vector.size(); i++)
    cout<<s_vector[i]<<" ";

    contain(s_vector, string check);

    return 0;
} 

我正在尝试创建一个代码,您可以在其中找到字符串的索引。例如,输出将是:

Input the size of string vector: 3
Input 3 strings:
asd
lkj
qere
Input a string to check: lkj
1

但是int contains~部分似乎有一些错误,如果我取出int contains〜section并运行程序,每当我尝试输入字符串时,它就会一直说“运行已经停止”。我是C ++的新手,所以我真的可以帮助你了。

1 个答案:

答案 0 :(得分:1)

您的包含功能可能如下所示:

int contain(const vector<string>& s_vector)
{
    cout << "Input a string to check: ";
    string check;
    cin >> check;
    for (int i = 0; i < s_vector.size(); i++)
        if (s_vector[i] == check)
            return i;

    return -1;
}

无需将局部变量check传递给函数。我们使用operator []逐个比较向量内的字符串。 main会看起来像这样:

int main()
{
    vector<string>s_vector;

    cout<<"Input the size of string vector: ";
    int size;
    cin>>size;

    cout << "Input " << size << "strings: \n"; 
    for (int i = 0; i < size; i++)
    {
        string str;
        cin >> str;
        s_vector.push_back(str);
    }

    cout<<"Strings in the string vector: ";
    for(int i=0; i<s_vector.size(); i++)
    cout<<s_vector[i]<<" ";

    int i = contain(s_vector);
    cout << "Index: " << i;

    return 0;

}