0

我正在尝试用字符填充 C++ 中的 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;
}
4

2 回答 2

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;
}
于 2017-12-04T18:15:03.067 回答
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;
    }

于 2019-10-23T18:21:27.530 回答