字符串矢量输入和查询操作
String vector input and query operation
在我的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);
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 查询SQLite数据库中的日期
- 重载操作程序时出错>>用于类中的字符串 memebr
- 对字符串进行位操作
- 如何在ArangoDb AQL查询中指定数据库
- 我可以在 C++ 中的函数体之外进行操作吗?
- MPI突然停止了对多个核心的操作
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- 对字符数组中的元素执行逐位操作
- 如何在directx/c++中进行平移/缩放操作
- 逐位操作的隐式类型转换
- Qt SQLite没有查询或参数计数不匹配
- 如何使用c++在VS 2019上运行SQL查询
- 为什么一个向量上的多线程操作很慢
- 排序时无法执行交换操作.我做的时候它会崩溃.为什么
- 从返回的顶点缓冲区查询顶点结构
- 位移操作和位掩码未检测到重复字符
- C++删除操作相关查询
- 字符串矢量输入和查询操作