2013-05-10 87 views
0

我知道,创建你需要把它写这样如何创建不同类型的多维向量/数组?

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% 

回答

2

我不知道我跟着你的解释,但它听起来你真正想要的是结构的载体:

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; 
} 
2

如果你的编译器支持C++ 11,可以使用tuplevector一个S:

#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>的编译时间索引。

2

我会建议将数据封装到一个类中,而不是使用该类的向量将其封装到jsut中。

(可能不会编译原样)

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); 

这是方便多了,因为与现在,当你需要打印出您的收藏你只遍历一组对象和你不工作不需要担心索引或访问向量或元组的复杂向量。