c++数组小结

按行遍历二维数组元素

const int size = 8;
const int a[size] = {1, 2, 3, 4, 5, 6, 7, 8};
const int a_raw = 2;
const int a_col = 4;

for (int i = 0; i < size; ++i) {
    std::cout << a[i] << " ";
}
std::cout << std::endl;

// 二维数组按行遍历
for (int i = 0; i < a_raw; ++i) {              // i表示数组的行索引
    for (int k = 0; k < a_col; ++k) {          // k表示数组的列索引
        std::cout << a[i * a_col + k] << " ";
    }
    std::cout << std::endl;
}
std::cout << std::endl;

按列遍历二维数组元素

const int size = 8;
const int a[size] = {1, 2, 3, 4, 5, 6, 7, 8};
const int a_raw = 2;
const int a_col = 4;

for (int i = 0; i < size; ++i) {
    std::cout << a[i] << " ";
}
std::cout << std::endl;

// 二维数组按列遍历
for(int j = 0; j < a_col; ++j) {  // j是数组的列索引
    for (int k = 0; k < a_raw; ++k) { // k是数组的行索引
        std::cout << a[k * a_col + j] << " ";
    }
    std::cout << std::endl;
}
std::cout << std::endl;

posted @ 2021-12-18 16:43  烟花不太冷  阅读(25)  评论(0编辑  收藏  举报