c++ - 如何使用 map 名称和打印 map<int.class> 在 C++ 中定义 map 迭代器

标签 c++

首先,我可以为下面的类声明一个映射迭代器吗

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/

相关文章:

c++ - KDevelop中如何查看变量的值?

c++ - 到达文件末尾后倒回 ifstream 对象

c++ - 变量在 Cocos2d-x for Blackberry 中失去值(value)

c++ - 为什么C++被称为语言联盟?

c++ - 在 C++ 中绘制到屏幕上的一个好的库是什么?

c++ - 什么是 undefined reference /未解析的外部符号错误,我该如何解决?

c++ - 如何确定缓存的阻塞因子

c++ - 从命令行使用范围

c++ - 在 C++ 中获取命名空间名称的任何可移植技巧?

c++ - 如何用 C++ 计算一个简单句子中的单词和数字