Originally posted by: Kyteland
If you have your data vector set up properly it should be simple to generate your output.
The first thing you need is a function that takes two values and returns a speed. You can do the rest either by treating your vector as an array or by using iterators. Heres some example code.
Just so you have some more info on the iterator stuff, vectors really only give you two iterators, begin() and rbegin() which point to the first and last element respectively.
They also give you end() which points to the element just past the end of the vector, and rend() which points to the element just before begining of the vector.
Since you want to access two adjacent elements at a time you need iterators to data[0] and data[1]. data[0] is the same as data.begin(). data[1] is the same as data.begin()++, which is why the first argument of the for loop increments the second value.
In iterators you cant check relative position, you can only check equality. That's why your end condition checks that your iterator isn't equal to data.end().
Not quite true. You can check relative position for iteraterators on vector objects, but not on list objects. For example:
vector<double> vx;
vector<double>::iterator vitr;
list<double> lx;
list<double> litr;
(assume we've added some data to both containers)
//This is legal
for(vitr = vx.begin(); vitr
< vx.end(); vitr++)
//So is this
vitr = vx.begin() + 5;
//This is not legal
for(litr = lx.begin(); litr
< lx.end(); litr++)
//Neitrher is this
litr = lx.begin() + 5;
It's ussually better to stay away from this stuff though, as it might be convenient at some point to switch the underlying container type down the line somewhere. For example, switching from a vector based queue to a list based queue.
Also, notice that I always did ++iterator and never iterator++. My STL book explains it like this.
Note that the preincrement operator (prefix ++) is used here. This is because it might have better performance than the postincerement operator. The latter involves a temporary object because it must return the old position of the iterator. For this reason, it generally is best to prefer ++pos over pos++.
It that didn't make any sense just remember to use the ++iterator style whenever your increment is a self contained statement, ie you don't assign it to anything.
Interesting - I've never heard that before.
Back to the OP - iterators are similar to pointers for fundamental types. But for vectors, you can also use subscripts similarly to native arrays. So, using Kyteland's code as the base, you could do this: