Thursday, 15 April 2010

c++ - Looping through std::vector to find matches from std::string array, easier way? -



c++ - Looping through std::vector to find matches from std::string array, easier way? -

i looping through std::vector , std::string array find matches vector.

example:

#include <iostream> #include <vector> #include <string> int main() { std::cout << "searching...\n"; std::vector<std::string> myvector; myvector.push_back("word"); myvector.push_back("word2"); myvector.push_back("word4"); myvector.push_back("word6"); myvector.push_back("word7"); std::string mystringarr[] = { "word", "word1", "word2", "word3", "word4", "word5", "word6", "word7" }; (auto vec : myvector) { for(auto str : mystringarr) { if(vec == str) { std::cout << "found: " << vec << std::endl; } } } std::cin.ignore(2); homecoming 0; }

this works fine. coming c language(trying c++ 11), , not sure if best solution.

platform windows, , not (currently) utilize external libraries boost, can see code.

is there improve / cleaner way accomplish same result?

your solution works fine , long vector , string array not long. little improvement on code: don't utilize auto simple types, it's less readable (you utilize const string& instead). more efficient: algorithm complexity o(nxm) n , m sizes of vector , array. storing values of vector in hash_set , checking if in array o(n+m).

c++ arrays windows c++11 vector

No comments:

Post a Comment