2015-11-13 140 views
-5
#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; 
} 

我在试图编写一个代码,您可以在其中找到字符串的索引。例如,输出会是这样:在字符串C++中查找索引

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

但似乎是在INT一些错误包含〜节,如果我拿出INT包含〜段和运行程序,它口口声声说“运行已经停止“每当我尝试输入字符串。我是C++的新手,所以我可以真正使用你的帮助谢谢。

+0

'CIN >> s_vector【尺寸】;'你不能这样做。此时s_vector有0个元素。你也需要一个循环来输入0 .. size -1。 – drescherjm

+0

'if(s_vector = check)'作业不是比较。看看你的C++书上运算符'=='和运算符'=' – drescherjm

+0

你需要将向量中的每个元素与搜索字符串进行比较,而不是向量本身。比较是用'=='完成的,目前你正在试图给一个向量赋一个字符串。 – Unimportant

回答

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 []来逐个比较向量中的字符串。 主要会是这个样子:

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; 

}

+0

正是我即将发布的内容。而且,局部变量检查从未被声明,也没有在主函数中赋值给它,并且通过使用'string check'作为参数来调用它肯定不起作用。 – Wilsu