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

I'd like to have a condition that allows me to check for growing vectors, but how the iterator is implemented in c++ as it doesn't allow me to do that. What should I use then?

user2967016
  • 133
  • 8
  • 1
    `vector.size()` isn't sufficient? – cf stands with Monica Mar 03 '14 at 05:41
  • maybe, but I don't think you can use it with sum. sum = solution.begin + n, while size is an integer between 0 and n. so are you suggesting me to use another variable x and increment it after ++sum and use vector.size()? – user2967016 Mar 03 '14 at 05:42
  • Your question isn't sufficiently clear. "a condition that allows me to check for growing vectors" sounds as if you're trying to solve a race. You probably want to use mutual exclusion to solve that problem. Also, can you add the type declarations for `sum`, `solution`, `col`, et al? – Brian Cain Mar 03 '14 at 05:46
  • hmmm didn't work, still getting segfault... yeah, i'll add it. – user2967016 Mar 03 '14 at 05:51
  • See also http://stackoverflow.com/a/6438087/489590 – Brian Cain Mar 03 '14 at 05:53

2 Answers2

1

The push_back has the potential of invalidating all iterators into the vector; this explains why you're getting a segfault when you dereference *sum in the next line of code.

You can either recalculate sum by taking a difference from begin() and adding it to the new begin() after the push_back(), or you can use indices instead of iterators.

size_t offset = sum - solution.begin();
solution.push_back(*col);
sum = solution.begin() + offset;
Mark Ransom
  • 271,357
  • 39
  • 345
  • 578
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); this condition was executing even when sum reached to end result segmentation fault.

HadeS
  • 1,922
  • 16
  • 34