2017-07-17 62 views
0
For example: [ticket.txt] 
(Number) (Amount) 
    09   10 
    13   15 
    25   21 

這是我的代碼:如何二維數組轉換成矢量

#include <iostream> 
#include <fstream> 

using namespace std; 
int main() 
{ 
    int rowNumber = 0; 
    ifstream inFile, inFile2; 
    string line; 
    inFile.open("Ticket.txt"); //open File 
    inFile2.open("Ticket.txt"); 
    if (inFile.fail()) // If file cannot open, the code will end 
    { 
     cout << "Fail to open the file" << endl; 
     return 1; 
    } 

    while (getline(inFile2, line)) // get whole lines and two valid numbers(numbers and amounts) 
     ++rowNumber; 
    cout << "Number of lines in text file: " << rowNumber << "\n"; 


    int myArray[rowNumber][2]; //declare 2d array 
     for(int i = 0; i < rowNumber; i++) 
      for(int j = 0; j < 2; j++) 
       inFile >> myArray[i][j]; 
} 

我的代碼運行良好,但我想一個二維數組轉換爲載體。雖然通過數組讀取文件的大小是固定的,但是矢量是解決此問題的一個很好的解決方案。

+0

*我的代碼是運行良好,但是我想將2d數組轉換爲向量。* - 如果這是個問題,那麼您無需提供有關票券獲勝和損失的詳細信息。只需編寫一個簡單的主程序,該程序需要一個二維數組並創建一個向量向量。 – PaulMcKenzie

+0

因爲我的大部分代碼都是使用數組,所以我試圖將它們轉換爲向量,但它似乎效果不佳。我以前從未使用過載體,所以它對我來說只是新的。 –

回答

0

鑑於文件結構可以讀取線到一個臨時載體中,然後將其插入到載體中的向量:

#include <iostream> 
#include <fstream> 
#include <vector> 
int main(){ 
    std::ifstream myfile("Tickets.txt"); 
    std::vector<int> temprow(2); 
    std::vector<std::vector<int>> matrix{}; 
    int rowcount = 0; 
    while (myfile >> temprow[0] >> temprow[1]){ 
     matrix.push_back(temprow); 
     rowcount++; 
    } 
    for (int i = 0; i < rowcount; i++){ 
     for (int j = 0; j < 2; j++){ 
      std::cout << matrix[i][j] << ' '; 
     } 
     std::cout << std::endl; 
    } 
} 

這假設你的2D陣列是N * 2