将2d数组转换为矢量

时间:2014-03-26 01:19:44

标签: c++ arrays vector

如何将二维数组转换为向量?这就是我到目前为止所拥有的。它编译,但它只输出"嘿"然后矢量下标超出范围错误。

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    string arr[2][3] = { { "hey", "what", "up" }, { "how", "you", "doin" } };
    vector<vector<string>> vec;

    for (int i = 0; i < 3; i++){        //creating row
        vec.push_back(vector<string>());
    }

    for (int n = 0; n < 3; n++){        //creating columns for the rows
        for (int m = 0; m < 2; m++){    
            vec[m].push_back("");
        }
    }
    for (int m = 0; m < 2; m++){        //storing and printing data
        for (int n = 0; n < 3; n++){
        //  vec[n].push_back(arr[m][n]);
            vec[m][n] = arr[m][n];
            cout << vec[n][m];
        }
    }
    cout << "\n";
}

2 个答案:

答案 0 :(得分:3)

实际上你可以用一行来做到这一点:

// Define and initialize a vector with 2D array
vector<vector<string>> vec = {vector<string>(begin(arr[0]), end(arr[0])),
                              vector<string>(begin(arr[1]), end(arr[1]))};

cout << arr[1][2] << endl;  // cout: "doin"
cout << vec[1][2] << endl;  // cout: "doin"

// print all elements
for (auto row : vec)
    for (auto elem : row)
        cout << elem << " "; // cout: hey what up how you doin

答案 1 :(得分:2)

您在cout中列有错误的行。这一行:

cout << vec[n][m];

应该是:

cout << vec[m][n];

将来,您可以考虑使用vector的方法at。此代码将抛出一个更容易调试的异常。

cout << vec.at(n).at(m);