首先,我可以为下面的类声明一个映射迭代器吗
class obj {
public:
map<int,double> m1;
};
map<int,obj> m;
作为m::iterator it = m.begin();
或者我应该声明为 map<int,obj>::iterator it = m.begin();
其次,我想打印 map m
.
如何打印上面给定的 map ,其值数据类型为类,并且该类包含另一个 map ?
最佳答案
您始终可以使用这个名为 auto
的便捷小功能。它可以在某些上下文中代替类型使用,例如在声明变量时。
在您的代码中,它看起来像这样:
struct obj {
map<int,double> m1;
};
map<int,obj> m;
// Here! The compiler will replace the `auto` placeholder by `map<int,obj>::iterator`
auto it = m.begin();
如果你真的想把它写下来 m
的 ::iterator
成员,你可以使用 decltype
:
// Here! The compiler will replace the `decltype(m)` placeholder by `map<int,obj>`
decltype(m)::iterator it = m.begin();
至于问题的第二部分,只需两个 range for 循环即可:
for (auto&& [key1, value1] : m) {
std::cout << key1;
for (auto&& [key2, value2] : value1.m1) {
std::cout << key2 << value2;
}
}
上面这段代码会在一行中输出 map 的所有数据,没有空格。
上面的代码使用了auto&&
。它与 auto
非常相似,但它会将类型推导为引用。
关于c++ - 如何使用 map 名称和打印 map<int.class> 在 C++ 中定义 map 迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41972076/