2013-05-10 82 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); 

這是方便多了,因爲與現在,當你需要打印出您的收藏你只遍歷一組對象和你不工作不需要擔心索引或訪問向量或元組的複雜向量。