Let's say I have a row vector, and I want to find all the lines starting with 'a'
, so I can do this:
struct cmp {
bool operator()( const std::string &s, char c ) const { return s.front() < c; }
bool operator()( char c, const std::string &s ) const { return s.front() < c; }
};
std::vector<std::string> strings;
...
std::sort( strings.begin(), strings.end() );
auto range = std::equal_range( strings.begin(), strings.end(), 'a', cmp{} );
...
This method is error prone since it is easy to make a mistake (for example, I think it should be c < s.front()
in the second method) and has code duplication.
So, is it possible to implement a comparison function with a common lambda instead of a structure using 2 methods?
The more general question is, why should the value for comparison be passed as an argument std::lower_bound
, std::upper_bound
and std::equal_range
when can it be easily captured by a lambda or passed to the comparison structure, and then this problem will not be there at all?
How could this work if it std::equal_range
did not require value?
struct cmp {
cmp( char lc ) : c( lc ) {}
bool operator()( const std::string &s ) const { return s.front() < c; }
char c;
};
std::vector<std::string> strings;
...
std::sort( strings.begin(), strings.end() );
auto range = std::equal_range( strings.begin(), strings.end(), cmp{'a'} );