首先,我可以为下面的类声明一个map迭代器吗
class obj {
public:
map<int,double> m1;
};
map<int,obj> m;作为m::iterator it = m.begin();,还是应该声明为map<int,obj>::iterator it = m.begin();
其次,我想打印地图m。如果上面给定的映射的值数据类型为class,并且该类包含另一个映射,我该如何打印该映射?
发布于 2017-02-01 13:00:09
您可以随时使用这个名为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;
}
}上面的代码将在一行中输出地图的所有数据,不带空格。
上面的代码使用auto&&。它非常类似于auto,但它会将类型推导为引用。
发布于 2017-02-01 13:05:31
迭代器可以声明为- std::map<int, obj>iterator it = m.begin()
要打印它们-
for (std::map<int, obj>::iterator it = m.begin(); it != m.end(); ++it) {
std::cout << it->first;
for (std::map<int, double>::iterator it1 = it->second.m1.begin(); it1 != it->second.m1.end(); ++it1) {
std::cout << it1->first << it1->second;
}
}https://stackoverflow.com/questions/41972076
复制相似问题