如何创建不同类型的多维矢量/数组?

时间:2013-05-10 00:30:28

标签: c++

我知道要创建一个多维向量,你需要像这样写

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%

3 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:2)

如果您的编译器支持C ++ 11,则可以vector使用tuple

#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 :(得分: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);

使用起来更加方便,因为现在当你需要打印出你的集合时,你只是迭代一组对象而你不需要担心索引或访问向量或元组的复杂向量

相关问题