I have to find if there are doubles in my list<SnakeParts>
and set alive to false if there are doubles
I tried with the unique()
function of the list
and added an operator==()
to my class. now when I execute the unique function I doesn't filter out the doubles. and after some debugging I found out that the ==
comparator only get's exececuted as many times as there are objects in my list I used the following code:
list<SnakePart> uniquelist = m_snakeParts;
uniquelist.unique();
if (m_snakeParts.size() != uniquelist.size()){
alive = false;
}
operator:
bool SnakePart::operator==(const SnakePart& snakePart) const{
return (x == snakePart.x && y == snakePart.y );
}
but that doesn't work. so what am I doing wrong, or is there another way I could do this?
std::list::unique
works only with consecutive duplicates. Say, if we have a {1, 2, 2, 1}
, after calling unique
we got {1, 2, 1}
. You could use sort
function before( N * log(N) + N
complexity) , or use std::map
to count every element in list(linear, + N memory(in worst case)).
Notice that an element is only removed from the list container if it compares equal to the element immediately preceding it. Thus, this function is especially useful for sorted lists.
So you'll have to either sort your list beforehand, or use an std::set (sets by nature can't contain duplicate objects).
If using a std::list
is not a requirement then I would suggest using std::set
which won't allow you to insert
an element that's already in the set. Moreover, the insert
method will let you know if the element you are trying to insert is already in the set or not via its return value.
If using a std::list
is a requirement, then I would suggest you to use std::unique
algorithm to weed out the duplicates. Please have a look at the example in there.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.