c++vectoriteratorequal-range

Find equal range for container with string with prefix


I am having 2 iterators range_begin,range_end, which are my container. I need to find all string which start with char prefix. Here is my code:

template <typename RandomIt>
pair<RandomIt, RandomIt> FindStartsWith(
RandomIt range_begin, RandomIt 
range_end,char prefix){
auto it=equal_range(range_begin,range_end,prefix,
[prefix](const string& city){return city[0]==prefix;});
return it;}

For example, for

const vector<string> sorted_strings = {"moscow", "murmansk", "vologda"};
auto it=FindStartsWith(strings.begin(),strings.end(),'m');

I want to get iterator with first on "moscow" and last after "murmansk".

I am getting strange compilier errors. What is wrong and how can I solve this?I cannot write correct lambda comporator.


Solution

  • Your errors might be due to strings.begin() and .end() which do not have sorted_. I do not think you should use a template either. Errors aside, I recommend you use a different std function. A simpler solution is to use foreach:

    #include <algorithm>
    #include <iterator>
    #include <list>
    #include <string>
    #include <utility>
    #include <vector>
    
    typedef std::vector<std::string>::const_iterator RandomIt;
    
    std::vector<std::string> FindStartsWith(RandomIt start, RandomIt end, const char prefix) {
        std::vector<std::string> result;
    
        std::for_each(start, end, [&](auto city) {
            if (city.front() == prefix) {
              result.push_back(city);
            }
        });
    
        return result;
    }
    
    int main(int argc, char* argv[]) {
        const std::vector<std::string> sorted_strings = { "moscow", "murmansk", "vologda" };
        auto prefix_cities = FindStartsWith(sorted_strings.begin(), sorted_strings.end(), 'm');
    
        return 0;
    }
    

    Definitely could use a refactor, but I'm assuming you need to implement it in the FindStartsWith for some other reason...

    Thanks for posting, this taught me a lot about equal_range :)