Jan 2, 2012 at 7:51pm Jan 2, 2012 at 7:51pm UTC
I'm comparing all elements in a std::list for object collision, my problem arises when I try to do this:
std::list<Asteroid>::iterator otherObject = currentObject + 1
currentObject is also an iterator.
This comes up with an error saying that there is no match for the + operator.
What can I do to get around this?
Jan 2, 2012 at 7:59pm Jan 2, 2012 at 7:59pm UTC
List iterators are not random access iterators.
You can use std::next(), as in
std::list<Asteroid>::iterator otherObject = std::next(currentObject);
or, if you have an older compiler, increment
1 2
std::list<Asteroid>::iterator otherObject = currentObject;
++otherObject;
But is there a reason you're using a list rather than, say, a vector? Do you actually use list::splice()?
Last edited on Jan 2, 2012 at 8:00pm Jan 2, 2012 at 8:00pm UTC
Jan 2, 2012 at 8:16pm Jan 2, 2012 at 8:16pm UTC
I need to use a list because at one point there is a list of objects that need to be deleted from the list, and the iterators need to be undisturbed.
Also, can you point me to a reference page for std::next ()?
Jan 2, 2012 at 8:53pm Jan 2, 2012 at 8:53pm UTC
Problem:
when I use std::next, an error comes up saying that it is not a member of std.
I did #include <iterator>
Jan 2, 2012 at 9:00pm Jan 2, 2012 at 9:00pm UTC
Did you use it with correct parameters?
Jan 2, 2012 at 9:04pm Jan 2, 2012 at 9:04pm UTC
std::next() is C++11, the language formerly known as C++0x, not regular C++
From
http://stackoverflow.com/questions/3673684/peek-the-next-element-in-stl-container
C++0x adds a handy utility function, std::next, that copies an iterator, advances it, and returns the advanced iterator. You can easily write your own std::next implementation:
1 2 3 4 5 6 7 8 9
#include <iterator>
template <typename ForwardIt>
ForwardIt next(ForwardIt it,
typename std::iterator_traits<ForwardIt>::difference_type n = 1)
{
std::advance(it, n);
return it;
}
Andy
PS I think people should flag C++11 specific code up until it's in wide(-ish) spread usage!
Last edited on Jan 2, 2012 at 9:08pm Jan 2, 2012 at 9:08pm UTC
Jan 2, 2012 at 9:22pm Jan 2, 2012 at 9:22pm UTC
ah yes, I've been meaning to upgrade to that for the auto feature.
I have g++ through mingw, how can I upgrade?
Jan 2, 2012 at 9:58pm Jan 2, 2012 at 9:58pm UTC
I'm mainly a VC++ user, but I have heard that with Gnu (g++ is gnu?) you just have to enable C++11 with a compiler flag. If you're up to date enough, I guess (GCC 4.3 and later).
http://gcc.gnu.org/projects/cxx0x.html
--std=c++0x
Last edited on Jan 2, 2012 at 9:59pm Jan 2, 2012 at 9:59pm UTC
Jan 3, 2012 at 12:38am Jan 3, 2012 at 12:38am UTC
Get a compiler that understands C++ 11 :)