gpt4 book ai didi

C++ 可以重载 `operator<<` 来显示 map 吗?

转载 作者:行者123 更新时间:2023-11-30 05:19:19 26 4
gpt4 key购买 nike

我重载了我的 operator<<如下所示:

friend ostream& operator<<(ostream& os, Data& e)
{
// possible code for printing map..
return os;
}

我有一个 map<string, vector<int>> table ,我的问题是,是否可以通过e.table访问并打印出 map ? ?

最佳答案

是的,你可以。例如。

#include <iostream>
#include <map>
#include <string>
#include <vector>

std::ostream & operator <<(std::ostream &os,
const std::map<std::string, std::vector<int>> &m)
{
for (const auto &p : m)
{
os << p.first << ": ";
for (int x : p.second) os << x << ' ';
os << std::endl;
}

return os;
}

int main()
{
std::map<std::string, std::vector<int>> m =
{
{ "A", { 1, 2, 3, 4, 5 } },
{ "Z", { 5, 4, 3, 2, 1 } }
};

std::cout << m << std::endl;
}

程序输出为

A: 1 2 3 4 5
Z: 5 4 3 2 1

或者

#include <iostream>
#include <map>
#include <string>
#include <vector>

class Data
{
public:
friend std::ostream & operator <<(std::ostream &os, const Data &d);

private:
std::map<std::string, std::vector<int>> m =
{
{ "A",{ 1, 2, 3, 4, 5 } },
{ "Z",{ 5, 4, 3, 2, 1 } }
};
};

std::ostream & operator <<(std::ostream &os, const std::map<std::string, std::vector<int>> &m)
{
for (const auto &p : m)
{
os << p.first << ": ";
for (int x : p.second) os << x << ' ';
os << std::endl;
}

return os;
}

std::ostream & operator <<(std::ostream &os, const Data &d)
{
return os << d.m;
}

int main()
{
Data d;
std::cout << d << std::endl;
}

关于C++ 可以重载 `operator<<` 来显示 map 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41201712/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com