制作2d矢量和列表的不同方法

问题描述 投票:0回答:1

所以我有这个片段

vector<int> *adj;
adj = new vector<int>[n];

这是另一种常见的方式

vector<vector<int> adj(n);

以前使用指针的方式可以用来制作2d数组吗?它会像后者一样工作吗?

此外,如果以前的方式使用,如果它可以用于制作2d向量。

我也可以使用以前的方式制作2d列表吗?

对于那些想知道以前的方法的人来说,错误的制作列表的方式是极客们的极客http://www.geeksforgeeks.org/topological-sorting/

c++ list vector stl
1个回答
0
投票

有可能的方法来创建多维向量,但我使用这种方法,利用struct,

这是2X2表的示例

#include<iostream>
#include<vector>

struct table
{
    std::vector<int> column;
};

int main()
{
    std::vector<table> myvec;
    // values of the column for row1
    table t1;
    t1.column = {1,2};
    // Push the first row
    myvec.push_back(t1);
    // values of the column for row2
    table t2;
    t2.column = { 3, 4};
    // push the second row
    myvec.push_back(t2);
    // now let us see whether we've got a 2x2 table
    for(auto row : myvec)
    {
        auto values = row.column; 
        for(auto value : values) std::cout<< value << " ";
        std::cout<<"\n";
    }
    // Now we will try to get a particular value from the column index of a particular row
    table row = myvec[1]; // 2nd row
    std::cout<<"The value present at 2nd row and 1st column is: "<<row.column[0] <<"\n";
}

这给了我,

1 2 
3 4 
The value present at 2nd row and 1st column is: 3

您可以轻松地将其更改为不同的尺寸。

注意:如果有人纠正我的错误,我已将这个答案发给我。谢谢

© www.soinside.com 2019 - 2024. All rights reserved.