循环遍历多维数组
Loop through a multidimensional array?
我将如何循环通过一个多维数组?假设我们有这样的东西:
class blah
{
public:
blah();
bool foo;
};
blah::blah()
{
foo = true;
}
blah testArray[1][2];
testArray[1][0].foo = false;
我如何循环testArray
来找出foo
中哪个是假的呢?
这个不依赖于幻数:
#include <cstddef>
for (size_t x = 0; x < sizeof(*testArray) / sizeof(**testArray); ++x)
for (size_t y = 0; y < sizeof(testArray) / sizeof(*testArray); ++y) {
if (testArray[x][y].foo == false) {
}
}
将x
放在外循环中可以获得更好的缓存
class blah
{
public:
blah();
bool foo;
};
blah::blah()
{
foo = true;
}
int testArrayFirstLength = 1;
int testArraySecondLength = 2;
blah testArray[testArrayFirstLength][testArraySecondLength];
testArray[1][0].foo = false;
for (int i = 0; i < testArrayFirstLength; i++) {
for (int j = 0; j < testArraySecondLength; j++) {
if (!testArray[i][j]) {
blah thing = testArray[i][j]
}
}
}
,好吗?还是你在找别的东西?
int x = 0;
int y = 0;
for( x = 0; x < 1; x++ ){
for( y = 0; y < 2; y++ ){
if( testArray[x][y].foo == false ){
//yeah!
}
}
}
for (std::size_t i(0); i != 1; ++i){
for (std::size_t j(0); j != 2; ++j) {
if (!testArray[i][j].foo) {
//testArray[i][j].foo is false
//Perform the required operation
}
}
}
在c++ 14中测试(使用指针,因此是安全的)
#include <iostream>
int main()
{
int array[2][2][2];
int* pointer=&array[0][0][0];
for(int i=0; i<2*2*2; i++)
{
std::cout<<*pointer<<std::endl;
pointer++;
}
}
相关文章:
- 遍历并行数组以确定C++中的最大数字
- 遍历二维数组的所有子数组
- 遍历向量与数组哪个更快?
- 是否可以遍历传递给函数的数组?
- 如果你有一个固定大小的数组,你需要遍历它!n次,使用二进制搜索如何改变时间复杂性
- 我该如何循环遍历我的数组(缓冲区——包含一个文本文件),并将其打印成30字节的块
- 数组数据以错误的方式遍历 Python/Matlab
- 如何使用 PHPCPP 传递对象数组,遍历每个对象并返回关联数组
- 如何使用指针遍历结构数组中的数组
- 程序在遍历所有值之前离开循环. 数组的
- 按顺序遍历 AVL 树,将值保存在数组中
- 数组 - 循环遍历辅助阵列
- 在C++中循环遍历二维数组时改进 O(n)
- 如何修复我的代码并使其遍历 2D 数组中的所有行?(C++)
- 如何遍历充满结构的数组
- 数组 通过指针遍历
- 在常量数组上使用指针遍历
- 如何遍历可变参数模板以填充 POD 数组
- 有条件的大平面数组遍历和令人惊讶的短循环执行时间
- 数组遍历中的BST