Lets say I have a vector of strings and I want to find all strings, that start 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, as it is easy to make mistake (for example I think it should be c < s.front()
in second method) and has code duplication.
So is it possible to implement comparison function with generic lambda instead of structure with 2 methods?
More generic question, why value to compare has to be passed as argument to std::lower_bound
, std::upper_bound
and std::equal_range
when it can easily be captured by lambda or passed to comparison structure, and then this issue will not be there at all?
How it could work if std::equal_range
would 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'} );