Java hashmap.get() 在 C++ 中
Java hashmap.get() in c++
在 java 中你可以有这样的东西:
Map<Foo, List<Bar>> things;
for(Foo foo : things.getKeySet()){
List<bar> = things.get(foo);
}
是否有 c++ 的等效项,也许在 std::map 中?感谢您的帮助。
参见std::map and std::vector (ArrayList) and maybe std::unordered_map (HashMap) and std::list(链表)
例如:
#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; }
};
在 java 中你可以有这样的东西:
Map<Foo, List<Bar>> things;
for(Foo foo : things.getKeySet()){
List<bar> = things.get(foo);
}
是否有 c++ 的等效项,也许在 std::map 中?感谢您的帮助。
参见std::map and std::vector (ArrayList) and maybe std::unordered_map (HashMap) and std::list(链表)
例如:
#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; }
};