字符串矢量输入和查询操作

String vector input and query operation

本文关键字:查询 操作 输入 字符串      更新时间:2023-10-16

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

所以你需要要么写这些元素,要么创建一个空向量并使用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);