views:

254

answers:

3

Hi,

Im holding an iterator that points to an element of a vector, and I would like to compare it to the next element of the vector.

Here is what I have

Class Point{
public:
 float x,y;
}

//Somewhere in my code I do this

vector<Point> points = line.getPoints();

foo (points.begin(),points.end());

where foo is:

void foo (Vector<Point>::iterator begin,Vector<Point>::iterator end)
{
    std::Vector<Point>::iterator current = begin;

    for(;current!=end-1;++current)
    {
        std::Vector<Point>::iterator next = current + 1;

        //Compare between current and next.
    }
}

I thought that this would work, but current + 1 is not giving me the next element of the vector.

I though operator+ was the way to go, but doesnt seem so. Is there a workaround on this?

THanks

+3  A: 

current + 1 is valid for random access iterators (which include vector iterators), and it is the iterator after current (i.e., what you think it does). Check (or post!) your comparison code, you're probably doing something wrong in there.

rlbond
Indeed. The solution? 1) Asking on S.O, 2) Getting some sleep.
Tom
+1  A: 

std::vector has random-access iterators. That means they are, basically, as versatile as pointers. They provide full-blown pointer arithmetic (it+5, it+=2) and comparisons other than !=/== (i.e., <, <=, >, and >=).

Comparison between iterators in your code should certainly work, but would be nonsensical:

for(std::vector<Point>::iterator current = begin;current!=end-1;++current)
{
    std::vector<Point>::iterator next = current + 1;

    assert(current!=next); // always true
    assert(current<next); // also always true
}

So if it doesn't work for you, it's likely you do something wrong. Unfortunately, "...is not giving me the next element of the vector..." doesn't give us no clue what you are trying, so it's hard to guess what you might be doing wrong.

sbi
current shouldn't point to the last element in this loop, though a check for `begin != end` might be in order.
visitor
@visitor: Yeah, you're right. I copied the loops ending condition without even looking at it. `<sigh>`
sbi
A: 

Maybe it's just a typo, but your code is referring to Vector while the standard container is vector (lower case V).

But if that's not a typo in your question, without seeing the definition of Vector, there's no way to tell what that does.

R Samuel Klatchko