如何遍历行数与列数未知的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.
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

