如何创建不同类型的多维向量/数组?
How do I create a multidimensional vector/array of different types?
我知道要创建一个多维向量,你需要这样写
std::vector< std::vector <int> > name;
std::vector<int> firstVector;
firstVector.push_back(10);
numbers.push_back(thisVector);
std::cout << numbers[0][0]
输出为10.
然而,我正在尝试创建三种不同类型的表。第一列是字符串,第二列是整型,第三列是双精度。
这个表的输出看起来像这样
One 200 5.1%
Three 10 1.4%
Nine 5000 10.8%
我不确定我是否跟上了你的解释,但是听起来你真正想要的是一个结构向量:
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;
}
我建议将数据封装到一个类中,而不是仅仅使用该类的向量。
(可能不会按原样编译)
class MyData
{
public:
std::string col1;
int col2;
double col3;
};
...
std::vector<MyData> myData;
MyData data1;
data1.col1 = "One";
data1.col2 = 10;
data1.col3 = 5.1
myData.push_back(data1);
这是更方便的工作,因为现在当你需要打印你的集合,你只迭代一组对象,你不需要担心索引或访问到一个复杂的向量或元组的向量
如果您的编译器支持c++ 11,您可以使用tuple
s的vector
:
#include <vector>
#include <tuple>
#include <string>
int main()
{
std::vector<std::tuple<std::string, int, double>> var;
var.emplace_back("One", 200, 5.1);
var.emplace_back("Three", 10, 1.4);
var.emplace_back("Nine", 5000, 10.8);
}
使用 std::get<N>
进行编译时索引
相关文章:
- 如何在向量数组中插入元素?
- 不同大小的向量数组的大小 cpp
- 很好的语法来获取对向量/数组数据的大小引用?
- 指向 c++ 中的向量数组并将其发送到函数的指针
- 初始化向量数组,其中每个向量的大小为 0
- 在这里,当我们比较 if(vc[i]==vc1[i]) 时,它是向量数组. 实际上比较的值是多少,
- 如何使用结构体的向量数组?
- C++:向量数组
- 在C++中通过引用传递向量数组
- 向量数组"Cannot access memory at address"
- 构造不同类型的C++向量数组
- 向量数组的均值和众数 - 如何对函数进行较小的改进
- C++:初始化(新)一个不同初始大小的向量数组
- 五个中三个最大参数的平均值,不使用排序算法或向量/数组
- 销毁C++中的向量数组
- 继承向量/数组/列表并更改其大小
- 如何输出属于向量数组的结构字符串
- 如何通过引用传递向量数组
- 在向量数组中获得前五个最大的结果
- 为什么"new vector<int>[5]"不创建向量数组?