ceth
ceth

Reputation: 45295

Find value in vector of pairs

Here is my code (I cannot change the signature of the function):

using VectorOfPair = std::vector<std::pair<std::string, std::string>>;

bool some_find(VectorOfPair data, const std::string& k, std::string *value) {
    sort(data.begin(), data.end());
    auto element = std::lower_bound(data.begin(), data.end(),
                                    std::make_pair(k, ""));
    if (element != data.end()) {
        *value = element->second;
        return true;
    }
    return false;
}

Test:

TEST_CASE("MyTest") {
    std::string value;
    VectorOfPair data = {{"b", "1"}, {"a", "2"}};
    bool result = some_find(data, "b", &value);
    REQUIRE(result == true);
}

Error:

/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/algorithm:702:71: error: invalid operands to binary expression ('const std::__1::pair<std::__1::basic_string<char>, std::__1::basic_string<char> >' and 'const std::__1::pair<std::__1::basic_string<char>, const char *>')
    bool operator()(const _T1& __x, const _T2& __y) const {return __x < __y;}
                                                                  ~~~ ^ ~~~
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/algorithm:4208:13: note: in instantiation of member function 'std::__1::__less<std::__1::pair<std::__1::basic_string<char>, std::__1::basic_string<char> >, std::__1::pair<std::__1::basic_string<char>, const char *> >::operator()' requested here
        if (__comp(*__m, __value_))
            ^
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/algorithm:4226:12: note: in instantiation of function template specialization 'std::__1::__lower_bound<std::__1::__less<std::__1::pair<std::__1::basic_string<char>, std::__1::basic_string<char> >, std::__1::pair<std::__1::basic_string<char>, const char *> > &, std::__1::__wrap_iter<std::__1::pair<std::__1::basic_string<char>, std::__1::basic_string<char> > *>, std::__1::pair<std::__1::basic_string<char>, const char *> >' requested here
    return __lower_bound<_Comp_ref>(__first, __last, __value_, __comp);

Why I have an error here and how can I fix it?

Upvotes: 0

Views: 56

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

std::make_pair(k, "")

is not a pair of std::string and std::string but a pair of std::string and const char*.

Try

std::make_pair(k, std::string(""))

instead.

Upvotes: 3

Related Questions