wyszukiwanie w wektorze par

1

Hej
Mam problem z wektorem par. Nie chce mi się taki program przykładowy skompilować. Ktoś coś?

#include <stdio.h>
#include <string>
#include <set>
#include <utility>
#include <algorithm>
#include <vector>

int main()
{
    std::vector<std::pair<std::string, bool>> sponsorNames;
    auto it = std::find(sponsorNames.begin(), sponsorNames.end(), [](auto& item) {return item.first == std::string("saaaas");});
    if (it != sponsorNames.end())
    {
        it->second = true;
    }
    

    return 0;
}

Error:
/usr/include/c++/11/bits/predefined_ops.h:270:24: error: no match for ‘operator==’ (operand types are ‘std::pair, bool>’ and ‘const main()::’)
270 | { return *__it == _M_value; }

Ja natomiast wedle statycznej analizy kodu to widzę, że porównuję stringa ze stringiem. item.first to jest string a item.second to bool. Ale kompilator to widzi inaczej. No ale wiadomo to C++ silnie typowany język, więc czegoś pewnie nie dostrzegam w składni.

5

Użyj std::find_if - std::find nie przyjmuje lambd

3

C++20 ranges, ranges ma coś co się nazywa "projection" i tam można wsadzić, wskaźnik na pole, funkcję lub lambdę:

#include <algorithm>
#include <iostream>
#include <string>
#include <utility>
#include <vector>

int main()
{
    std::vector<std::pair<std::string, bool>> sponsorNames {
        { "a", false },
        { "boo", true },
        { "foo", false },
        { "cell", true },
        { "zzz", false },
    };

    std::string s;
    while (getline(std::cin, s)) {
        auto it = std::ranges::find(
            sponsorNames,
            s,
            &std::pair<std::string, bool>::first);

        if (it != sponsorNames.end()) {
            std::cout << s << ' ' << std::exchange(it->second, true) << '\n';
        } else {
            std::cout << s << " - not found\n";
        }
    }

    return 0;
}

https://godbolt.org/z/x3zb46YaY

Swoją drogą patrząc na ten twój kod to bardziej wygląda na to, że potrzebna ci mapa.

1
TomaszLiMoon napisał(a):

Użyj std::find_if - std::find nie przyjmuje lambd

a rzeczywiście czeski błąd z mojej strony:)

1 użytkowników online, w tym zalogowanych: 0, gości: 1