C++ 识别二维向量C+中的位置+;

C++ 识别二维向量C+中的位置+;,c++,vector,C++,Vector,我真的在和向量作斗争。虽然我可以在数组中执行此操作,但我需要能够将网格传递到一个没有常量行和列的函数中 for (row = matrix.begin(); row != matrix.end(); ++row) { for (col = row->begin(); col != row->end(); ++col) { //I need to do stuff like if (matrix[row-1][col+1] == blah)

我真的在和向量作斗争。虽然我可以在数组中执行此操作,但我需要能够将网格传递到一个没有常量行和列的函数中

    for (row = matrix.begin(); row != matrix.end(); ++row)
{
    for (col = row->begin(); col != row->end(); ++col)
    {
        //I need to do stuff like if (matrix[row-1][col+1] == blah)
    }
}

谢谢大家!

您可以使用
中的函数查找相邻项目

#include <iterator>

auto prev_row = std::prev(row);
auto next_row = std::next(row);

只需小心循环的开始和结束值,以免超出范围,即确保
std::prev
不在
begin()
之前,并且确保
std::next
不会将您提前到
end()
std::vector支持索引,因此您不必使用迭代器。您可以这样做:

std::vector<std::vector<int>> matrix; 
std::vector<int> row;
row.push_back(1);
row.push_back(2);
matrix.push_back(row);
for (int row = 0; row < matrix.size(); ++row) {
    for (int col = 0; col < matrix[row].size(); ++col) {
        std::cout << matrix[row][col] << std::endl;
    }
}
std::向量矩阵;
std::向量行;
行。向后推(1);
世界其他地区。推回(2);
矩阵。推回(世界其他地区);
对于(int row=0;rowstd::vector<std::vector<int>> matrix; 
std::vector<int> row;
row.push_back(1);
row.push_back(2);
matrix.push_back(row);
for (int row = 0; row < matrix.size(); ++row) {
    for (int col = 0; col < matrix[row].size(); ++col) {
        std::cout << matrix[row][col] << std::endl;
    }
}