【问题标题】:How to convert 2D array into Vector如何将二维数组转换为向量
【发布时间】:2017-07-17 00:03:29
【问题描述】:
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];
}

我的代码运行良好,但我想将二维数组转换为向量。而通过数组读取文件的大小是固定的,所以vector是解决这个问题的一个很好的解决方案。

【问题讨论】:

  • 我的代码运行良好,但我想将二维数组转换为向量。 -- 如果是这个问题,那么您不需要提供有关票证的详细信息输赢。只需编写一个简单的主程序,它接受一个二维数组并创建一个向量向量。
  • 因为我的大部分代码都使用数组,所以我试图将它们转换为向量,但似乎效果不佳。我以前从未使用过矢量,所以对我来说只是新的。

标签: c++ arrays for-loop vector fstream


【解决方案1】:

根据您的文件结构,您可以将行读入临时向量,然后将其插入向量向量中:

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

这假设您的二维数组是 N * 2。

【讨论】:

    猜你喜欢
    • 2021-01-31
    • 1970-01-01
    • 2016-02-02
    • 2019-07-30
    • 1970-01-01
    • 1970-01-01
    • 2019-07-21
    • 2011-07-05
    相关资源
    最近更新 更多