在我的C ++代码中,我获取了用户定义数量的输入字符串。接下来,用户输入用户定义数量的查询字符串。对于每个查询字符串,我想在用户最初输入的字符串集合中输出其实例的数量。
这是我的代码:
#include<iostream>
#include<vector>
#include<string>
#include<conio.h>
using namespace std;
int main(int argc, char ** argv) {
int N, Q;
cout << "Enter number of strings : ";
cin >> N;
vector <string> strInp(N);
string sbuf;
// Storing the strings in the vector
cout << "Enter the strings:" << endl;
for (int i = 0; i < N; i++) {
cin >> sbuf;
strInp.push_back(sbuf);
}
// Storing the queries
cout << "Enter the number of queries : ";
cin >> Q;
vector <string> query(Q);
string qbuf;
cout<<" Enter the query strings"<< endl;
for (int i = 0; i < Q; i++) {
cin >> qbuf;
query.push_back(qbuf);
}
// Counting the instances of the query strings
// Initializing the instances vector
vector <int> instances;
string s1, s2;
int flag = 0;
vector <string> ::iterator start1 = query.begin();
vector <string> ::iterator end1 = query.end();
vector <string> ::iterator start2 = strInp.begin();
vector <string> ::iterator end2 = strInp.end();
for (auto i = start1; i < end1; i++) {
int count = 0;
s1 = *i;
for (auto j = start2; j < end2; j++) {
s2 = *j;
if (s1 == s2) {
count++;
}
}
instances.push_back(count);
}
cout << "The number of instances of each query are : " << endl;
for (unsigned int i = 0; i < instances.size(); i++) {
cout << instances[i] << endl;
}
return 0;
_getch();
}
在运行代码时,我有以下输出
Enter the number of inputs : 5
Enter the strings:
apple
apple
apple
ball
cat
Enter the number of queries: 3
Enter the query strings:
apple
ball
cat
The number of instances of each query are :
5
5
5
3
1
1
预期的输出实际上是:
The number of instances of each query are :
3
1
1
如果有人能指出我做错了什么,我真的很感激吗? 谢谢
答案 0 :(得分:1)
当您使用构造函数创建std::vector
时,您已经填充了这些元素。
因此,对于您的示例,这意味着strInp
为{"","","","","","apple","apple","apple","ball","cat"}
query
是{"","","","apple","ball","cat"}
所以你需要写入这些元素或创建一个空向量并使用push_back。
所以它是
vector <string> strInp(N);
和vector <string> query(Q);
同
strInp[i]=sbuf;
和query[i]=qbuf;
或者是
vector <string> strInp;
和vector <string> query;
同
strInp.push_back(sbuf);
和query.push_back(qbuf);