You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何遍历行数与列数未知的2D vector并访问其中int值?

Hey there! Let's figure out how to access values in a 2D vector<int> when you don't know the number of rows and columns ahead of time. I’ll break down the most reliable approaches—chances are these align with what you’ve already tried, but let’s clarify the details to make sure you’re covered.

Accessing Elements in a 2D vector<int> with Unknown Rows/Columns

First, remember that a 2D vector in C++ is just a vector<vector<int>>—each element is a separate vector<int> representing a row. Even if you don’t know the exact dimensions upfront, there are simple ways to work with its elements.

Approach 1: Nested Range-Based For Loops (Simplest Traversal)

If you just need to iterate through every element, range-based for loops are perfect—they handle variable row lengths automatically, no need to calculate dimensions first:

#include <vector>
#include <iostream>

int main() {
    // Example 2D vector with uneven row lengths
    std::vector<std::vector<int>> my_2d_vec = {{1,2,3}, {4,5}, {6,7,8,9}};

    // Loop through each row
    for (const auto& row : my_2d_vec) {
        // Loop through each value in the current row
        for (int val : row) {
            std::cout << val << " ";
        }
        std::cout << "\n";
    }
    return 0;
}

This will print each row’s elements neatly, even if rows have different numbers of columns.

Approach 2: Use size() to Get Dimensions and Index Directly

If you need to access specific positions (like element at row i, column j) or want more control over traversal, you can get the row count with my_2d_vec.size(), then get each row’s column count with my_2d_vec[i].size():

#include <vector>
#include <iostream>

int main() {
    std::vector<std::vector<int>> my_2d_vec = {{1,2,3}, {4,5}, {6,7,8,9}};

    // Total number of rows
    int total_rows = my_2d_vec.size();
    for (int i = 0; i < total_rows; ++i) {
        // Number of columns in the current row
        int row_cols = my_2d_vec[i].size();
        for (int j = 0; j < row_cols; ++j) {
            std::cout << "Element (" << i << "," << j << "): " << my_2d_vec[i][j] << "\n";
        }
    }
    return 0;
}

Critical Note: Avoid Out-of-Bounds Errors

If your 2D vector might have empty rows (a vector<int> with no elements), always check if the row is empty before accessing its elements to prevent crashes:

if (!my_2d_vec[i].empty()) {
    // Safe to access elements in this row now
}

Common Pitfalls You Might Have Hit

If your previous attempts ran into issues, it’s likely one of these:

  • Assuming all rows have the same number of columns, leading to out-of-bounds errors when accessing shorter rows
  • Forgetting to check if a row is empty before trying to access its elements, triggering undefined behavior

Sticking to the methods above will keep your code safe and functional, no matter what the dimensions of your 2D vector are.

内容的提问来源于stack exchange,提问作者Klaus Kientzle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:31:08