gpt4 book ai didi

c++ - 字符串 vector 输入和查询操作

转载 作者:行者123 更新时间:2023-11-28 05:36:31 27 4
gpt4 key购买 nike

在我的 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

如果有人能指出我做错了什么,我将不胜感激?谢谢你

最佳答案

当您创建 std::vector 时使用需要计数的构造函数,那么您已经填充了该数量的元素。

因此对于您的示例,这意味着 strInp{"","","","","","apple","apple","apple","ball","cat"}query{"","","","apple","ball","cat"}

因此您需要写入这些元素或创建一个空 vector 并使用 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);

关于c++ - 字符串 vector 输入和查询操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38187786/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com