c++ - vector 是否存在行主要形式?

标签 c++ pointers multidimensional-array vector std

很明显,二维数组的行主要形式是存储的单个数组,不同的行按顺序对齐。

要遍历二维数组的任何元素,我总是可以这样做:

int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};

for(int i=0;i<3*3;i++){

cout<<*(*a+i)<<" "; //row major form concept where i<m*n;

}

给出:

1 2 3 4 5 6 7 8 9

它对我完全有效,但每当我使用 vector 执行此操作时,它都会抛出错误:

vector<vector<int> > v={{1,2,3},{4,5,6},{7,8,9}};

int m=v.size();
int n=v[0].size();
for(int i=0;i<m*n;i++){

cout<<*(*v+i)<<" ";

}

它给出:

no match for ‘operator*’ (operand type is ‘std::vector<std::vector<int> >)

我希望 vector 确实遵循作为数组的行主要形式概念。如果是,那么在 vector 的情况下行专业的替代方案是什么?

最佳答案

你走错路了。自 std::vector在自由存储上动态分配内存,没有行优先或列优先这样的东西。

二维数组的内存 int foo[][]{ { 1, 2, 3 }, { 4, 5, 6 } }&foo[0] 开始:

1, 2, 3, 4, 5, 6

可视化:

+------+
| foo  |
+------+ 
|  1   |
|  2   |
|  3   |
|  4   |
|  5   |
|  6   |
+------+ 

std::vector<std::vector<int>> foo{ { 1, 2, 3 }, { 4, 5, 6 } } 的内存:

某处(与 &foo 无关):

1, 2, 3

其他地方:

4, 5, 6

可视化:

                                                             +------+
                                                        +--> | int  |
+-------------------------+                             |    +------|
| foo                     |                             |    |  1   |
+-------------------------+       +------------------+  |    |  2   |
| std::vector<int> *data -|-----> | std::vector<int> |  |    |  3   |           
+-------------------------+       +------------------+  |    +------+      
                                  | int* data[0]-----|--+
                                  | int* data[1]-----|--+    +------+
                                  +------------------+  +--> | int  |
                                                             +------+
                                                             |  4   |
                                                             |  5   |
                                                             |  6   |
                                                             +------+

遍历你的std::vectorstd::vector小号:

for (auto const &v_item : v) {
    for (auto const &i : v_item) {
        std::cout << i << ' ';
    }
}
std::cout.put('\n');

关于c++ - vector 是否存在行主要形式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52738900/

相关文章:

c++ - 在 C++ 中使用枚举编程 iota 相似性

c++ - 为什么 cin 在使用 getline 后没有获取缓冲区数据?

c++ - 类型的 constexpr 检查

c++ - 为什么我不能输出迷宫的路径?谁能告诉我?拜托

c++ - 关于将指向数组的指针作为函数参数的困惑

c - 从 C 函数返回 char 指针

c - 为包装在 C 中的结构中的二维指针数组分配内存

java - 查找数组中最大的平均结果集

java - 查找二维数组每行中的最小值

php - 使用多维数组中的第二个键获取值