Java hashmap.get() in c++

Java hashmap.get() in c++

本文关键字:in c++ hashmap get Java      更新时间:2023-10-16

在java中你可以这样写:

Map<Foo, List<Bar>> things;
for(Foo foo : things.getKeySet()){
    List<bar> = things.get(foo);
}

在c++中是否有一个等价的,也许在std::map中?谢谢你的帮助。

参见std::map和std::vector (ArrayList),或者std::unordered_map (HashMap)和std::list (LinkedList)

例如:

#include <map>
#include <vector>
struct Foo {};
struct Bar {};
int main()
{
    std::map<Foo, std::vector<Bar>> things;
    for(auto& thing: things) {
        const Foo& foo = thing.first; // key
        std::vector<Bar>& bars = thing.second; // value
        // use foo & bars here
    }
}

注意: std::map要求为用户定义的类型定义比较操作符,如Foo:

struct Foo
{
    int i = 0;
    Foo(int i): i(i) {}
    // need a comparison operator for ordered containers
    bool operator<(const Foo& foo) const { return i < foo.i; }
};