简体   繁体   English

识别2D向量C ++中的位置

[英]Identifying position in a 2D vector C++

I'm really struggling with vectors. 我真的很努力地使用向量。 Although I could do this in an array, I need to be able to pass my grid into a function without constant rows and columns. 尽管我可以在数组中执行此操作,但是我需要能够将网格传递给没有常量行和列的函数。

    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)
    }
}

Thank you! 谢谢!

You can use the functions out of <iterator> to find adjacent items 您可以使用<iterator>的功能查找相邻项

#include <iterator>

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

Similarly 同样

auto prev_cell = std::prev(col);
auto next_cell = std::next(col);

Just be careful with your loop start and end values so that you do not go out of bounds, ie make sure std::prev does not go before begin() and make sure std::next doesn't advance you to end() . 请小心循环起始和结束值,以免超出界限,即确保std::prev不会在begin()之前出现,并确保std::next不会使您前进到end()

std::vector supports indexing so you don't have to use iterators. std :: vector支持索引编制,因此您不必使用迭代器。 You can do something like this: 您可以执行以下操作:

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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM