C++ 嵌套迭代器访问

C++ 嵌套迭代器访问,c++,C++,我有一个关于迭代器的问题。问题是:“我如何访问(如果是嵌套迭代器)行中的元素,即更高或更低的元素。下面是我的意思示例: for( auto i = graphMatrix.begin();i != graphMatrix.end();i++ ) { for( auto j = i->begin();j != i->end();j++ ) { if( *j == 'O' ) { // here we must anal

我有一个关于迭代器的问题。问题是:“我如何访问(如果是嵌套迭代器)行中的元素,即更高或更低的元素。下面是我的意思示例:

for( auto i = graphMatrix.begin();i != graphMatrix.end();i++ )
{
    for( auto j = i->begin();j != i->end();j++ )
    {
        if( *j == 'O' )
        {
          // here we must analyze an element which is a row higher or lower
        }
    }
}
下一件事是我想做的(但这是矢量):

for(int i=graphMatrix.size();i

我知道vector具有快速的大小函数,但要概括代码,在我看来,最好使用迭代器(正如我的导师所说)。那么我如何使用迭代器和vector做同样的事情呢?

因为迭代器是非数字的,它们不适合这个问题

您可以使用
std::distance
std::advance
编写复杂、混乱且可能代价高昂的代码,在迭代器上执行“指针算术”……或者您可以坚持使用数字循环计数器方法,这正是我所要做的。尤其是当您使用具有恒定时间的
vector
时(让我们面对现实,立即)访问任意位置的任意元素


如果你想知道为什么,在这种情况下,迭代器突然不是你所学的迭代的“更好”机制:这是因为一个人必须为工作使用正确的工具,没有任何技术是所有工作的正确工具。

要从迭代器中获得向量的位置,使用
std::distance

for( auto i = graphMatrix.begin();i != graphMatrix.end();i++ )
{
    for( auto j = i->begin();j != i->end();j++ )
    {
        int x = std::distance(graphMatrix.begin(),i);
        int y = std::distance(i->begin(),j);

        graphMatrix[x][y] = 'x';


    }
}

您可以将所需的值存储在一个临时变量中。但读取/调试将是一件令人头痛的事情,因此使用索引的方法可能是最好的(我怀疑在这种情况下迭代器会快得多)。“最好使用迭代器。”“…用于迭代。你在做迭代以外的事情…然后使用数字索引?这有什么意义?:-)@Lightness Races in Orbit在本例中没有意义,但据我所知,这不是问题,在这种情况下可能需要使用std::distance,
for( auto i = graphMatrix.begin();i != graphMatrix.end();i++ )
{
    for( auto j = i->begin();j != i->end();j++ )
    {
        int x = std::distance(graphMatrix.begin(),i);
        int y = std::distance(i->begin(),j);

        graphMatrix[x][y] = 'x';


    }
}