gpt4 book ai didi

c++ - 如何创建不同类型的多维 vector/数组?

转载 作者:太空宇宙 更新时间:2023-11-04 15:46:00 24 4
gpt4 key购买 nike

我知道要创建一个多维 vector 你需要这样写

std::vector< std::vector <int> > name;
std::vector<int> firstVector;
firstVector.push_back(10);
numbers.push_back(thisVector);
std::cout << numbers[0][0]

输出将为 10。

但是我正在尝试创建三种不同类型的表格。第一列是字符串,第二列是整数,第三列是 double 。

这个表的输出看起来像这样

One     200    5.1%
Three 10 1.4%
Nine 5000 10.8%

最佳答案

我不确定我是否听懂了您的解释,但听起来您真正想要的是一个结构 vector :

struct whatever { 
std::string first; // The first column will be a string
int second; // ...the second would be ints
double third; // ...and the third would be doubles.
};

std::vector<whatever> data;

就您的输出而言,您将定义一个 operator<<处理:

std::ostream &operator<<(std::ostream &os, whatever const &w) { 
os << std::setw(10) << w.first
<< std::setw(5) << w.second
<< std::setw(9) << w.third;
return os;
}

关于c++ - 如何创建不同类型的多维 vector/数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16473346/

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