c++ - String vector input and query operation -
in c++ code, acquire user-defined number of input strings. next user enters user-defined number of query strings. each query string, want output number of instances, in collection of strings input user.
here code:
#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 strings in vector cout << "enter strings:" << endl; (int = 0; < n; i++) { cin >> sbuf; strinp.push_back(sbuf); } // storing queries cout << "enter number of queries : "; cin >> q; vector <string> query(q); string qbuf; cout<<" enter query strings"<< endl; (int = 0; < q; i++) { cin >> qbuf; query.push_back(qbuf); } // counting instances of query strings // initializing 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(); (auto = start1; < end1; i++) { int count = 0; s1 = *i; (auto j = start2; j < end2; j++) { s2 = *j; if (s1 == s2) { count++; } } instances.push_back(count); } cout << "the number of instances of each query : " << endl; (unsigned int = 0; < instances.size(); i++) { cout << instances[i] << endl; } return 0; _getch(); }
on running code, have following output
enter number of inputs : 5 enter strings: apple apple apple ball cat enter number of queries: 3 enter query strings: apple ball cat number of instances of each query : 5 5 5 3 1 1
the expected output :
the number of instances of each query : 3 1 1
i appreciate if can point out doing wrong? thank you
when creating std::vector
constructor takes count, fill in amount of elements.
so example means strinp
{"","","","","","apple","apple","apple","ball","cat"}
, query
{"","","","apple","ball","cat"}
so need either write elements or create empty vector , use push_back.
so it's vector <string> strinp(n);
, vector <string> query(q);
strinp[i]=sbuf;
, query[i]=qbuf;
or it's
vector <string> strinp;
, vector <string> query;
strinp.push_back(sbuf);
, query.push_back(qbuf);
Comments
Post a Comment