Home > OS >  Comparator for lower_bound for vector of pairs
Comparator for lower_bound for vector of pairs

Time:07-02

I wanna make lower_bound for vector of pairs but I wanna use it only for first elements of pairs. I tried to make my own comparator like this:

bool find(const std::string& key) const {
        auto finder = std::lower_bound(words_.begin(), words_.end(), key,
                                       [](const std::string& key, std::vector<std::pair<std::string, std::string>>::iterator it)
                                       {return key != it->first;});
    }

but it doesn't work. How I should use comparator to compare only first elements of pairs?

CodePudding user response:

Your lambda is the wrong signature and comparison for lower_bound(). It is expected to compare a container element against the provided value. Which means it does not accept an iterator as input at all.

The 1st parameter of the lambda needs to accept the container element, and the 2nd parameter needs to accept the input value. So, you are probably looking for something more like this instead:

bool find(const std::string& key) const {
    auto finder = std::lower_bound(words_.begin(), words_.end(),
        key,
        [](const std::pair<std::string, std::string> &elem, const std::string &value) {
            return elem.first < value;
        }
    );
    ...
}

That being said, if all you are trying to do is find an exact match to the specified key, std::find_if() would make more sense:

bool find(const std::string& key) const {
    auto finder = std::find_if(words_.begin(), words_.end(),
        [&key](const std::pair<std::string, std::string> &elem) {
            return elem.first == key;
        }
    );
    ...
}

CodePudding user response:

The lower_bound function (see here) defines the comparator (aka the predicate) as taking in two values to compare (in your case, two const std::string &). Change your predicate from accepting a const std::string & and an iterator:

[](const std::string& key, std::vector<std::pair<std::string, std::string>>::iterator it) {...}

to a lambda accepting two const std::string &:

[](const std::string& first, const std::string &second) {...}

  • Related