用C ++填充2D向量

时间:2017-12-04 18:10:59

标签: c++ vector 2d-vector

我正在尝试使用字符填充C ++中的2D向量,但是当我运行此代码时,它以一行字符(*..)结束。

如何像这样填充2D矢量: *.* .**

#include <iostream>
#include <vector>

int main()
{
    std::vector<std::vector<char> > vec2D;
    std::vector<char> rowV;

    unsigned int row=2;
    unsigned int col=3;

    char c;
    unsigned int temp=0;

    while(temp!=col)
    {
        while(rowV.size()!=row)
        {
            std::cin>>c;
            rowV.push_back(c);
        }
        vec2D.push_back(rowV);
        ++temp;
    }

    return 0;
}

2 个答案:

答案 0 :(得分:1)

每次插入后都应清除rowV,否则它将被填满,不会添加其他字符。此外,row应由col交换,反之亦然,否则您将获得3x2(而不是2x3)的2D矢量。

while(temp!=row)
{
    while(rowV.size()!=col)
    {
        std::cin>>c;
        rowV.push_back(c);
    }
    vec2D.push_back(rowV);
    rowV.clear(); // clear after inserting
    ++temp;
}

答案 1 :(得分:0)

了解[用空的1D向量推回2DVector]是什么样子。 请参见下面的示例。

    #include <algorithm>
    #include <cmath>
    #include <iostream>
    #include <vector>

    using namespace std;

    //-v-----A FUNCTION TO PRINT 2D VECTORS
    template<typename T> //We don't know what type the elements are yet, so we use a template
    void printVec2D(vector<vector<T>> a) // a is the name of our input 2Dvector of type (T)
    {
        for (int i = 0; i < a.size(); i++) {// a.size() will equal the number of rows (i suppose rows/columns can depend on how you look at it)
            for (int j = 0; j < a[i].size(); j++) {// a[i].size() is the size of the i'th row (which equals the number of columns, foro a square array)
                std::cout << a[i][j] << "\t";
            }
            std::cout << "\n";
        }
        return;
    }
    //-^--------

    int main()
    {
        int X = 3; int Y = 3;
        int VectorAsArray[3][3] = {{1,2,3},
                                   {14,15,16},
                                   {107,108,109}};

        vector<vector<int>> T;

        for (int i = 0; i < X; i++)
        {
            T.push_back({});// We insert a blank row until there are X rows
            for (int j = 0; j < Y; j++)
            {
                T[i].push_back(VectorAsArray[i][j]); //Within the j'th row, we insert the element corresponding to the i'th column
            }
        }

        printVec2D(T);

        //system("pause"); //<- I know that this command works on Windows, but unsure otherwise( it is just a way to pause the program)

        return 0;
    }