迭代器的动态大小检查?

时间:2014-03-03 05:40:46

标签: c++ iterator

vector<int> solution;
vector<int>::iterator col;
vector<int>::iterator row;
vector<int>::iterator sum;


...

for (row = vec.begin(); row != vec.end(); ++row)
{
    sum = solution.begin();

    for (col = row->begin(); col != row->end(); ++col)
    {
        if(sum == (solution.end())) //value for solution.end() doesn't change, while vector keeps growing
        {
            solution.push_back(*col);
        }

        *sum = (*sum + *col); //leads to segfault

        ++sum;
    }
}

我希望有一个条件允许我检查增长的向量,但是如何在c ++中实现迭代器,因为它不允许我这样做。那我该怎么用?

2 个答案:

答案 0 :(得分:1)

push_back有可能使所有迭代器无效到向量中;这解释了为什么在下一行代码中取消引用*sum时会出现段错误。

您可以通过从sum获取差异并将其添加到begin()之后的新begin()来重新计算push_back(),也可以使用索引而不是迭代器。

size_t offset = sum - solution.begin();
solution.push_back(*col);
sum = solution.begin() + offset;

答案 1 :(得分:0)

if(sum == (solution.end())) //value for solution.end() doesn't change, while vector keeps growing
{
    solution.push_back(*col);
}

else if(sum!=solution.end()) //<---- add this condition
    *sum = (*sum + *col);

*sum = (*sum + *col);即使总和达到最终结果分段错误,这个条件仍在执行。