Sep 19, 2017 at 7:20pm UTC
I have what may seem like a trivial problem but it os something I can not get to work. How can I alter the match function to take an integer enabling different matches...
At the moment it is matching against the hardcoded number 3 in the function.
Any help is appreciated!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
#include <iostream>
#include <algorithm>
#include <vector>
//declare function to match strings
bool match(const std::string test){
return test.size() == 3;
}
int main(int argc, const char * argv[]) {
std::vector<std::string> texts;
texts.push_back("one" );
texts.push_back("two" );
texts.push_back("three" );
texts.push_back("two" );
texts.push_back("four" );
texts.push_back("two" );
texts.push_back("three" );
std::cout << std::count_if(texts.begin(), texts.end(), match) << std::endl;
return 0;
}
Last edited on Sep 19, 2017 at 7:20pm UTC
Sep 19, 2017 at 8:42pm UTC
You can add another parameter and use a for loop to check the vector instead of using count_if
Last edited on Sep 19, 2017 at 8:47pm UTC
Sep 19, 2017 at 8:50pm UTC
You can use a functor. A functor, in non-technical terms, is an object that acts like a function.
I modified this from
https://stackoverflow.com/questions/13525361/can-you-pass-an-additional-parameter-to-a-predicate
so please read that for more context
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
#include <iostream>
#include <algorithm>
#include <vector>
/*
//declare function to match strings
bool match(const std::string test){
return test.size() == 3;
}
*/
struct match
{
match(const size_t N) : n(N) {}
const size_t n;
bool operator ()(const std::string& test)
{
return test.size() == n;
}
};
int main(int argc, const char * argv[]) {
std::vector<std::string> texts;
texts.push_back("one" );
texts.push_back("two" );
texts.push_back("three" );
texts.push_back("two" );
texts.push_back("four" );
texts.push_back("two" );
texts.push_back("three" );
std::cout << std::count_if(texts.begin(), texts.end(), match(3)) << std::endl;
return 0;
}
It certainly adds some boilerplate to the code, but it makes the end-user code look spotless.
You can also use lambdas to minimize boilerplate, as seen in the SO link.
Last edited on Sep 19, 2017 at 9:06pm UTC