• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Alessandro

C++: problem erasing vector items

17 posts in this topic

The following code works perfectly when I need to find and remove items in a vector:

[source]
for (int i=0; i<NSIZE; i++)
{
myVec.erase(std::remove_if(myVec.begin(), myVec.end(), myPred(i)), myVec.end());
}

// predicate
struct myPred {
findValue(int i) : id(i) { }
bool operator()(const myVec::myVecLib &obj) {
return obj.ID==id;
}
int id;
};
[/source]

However, I'd like to remove the items that don't match. I thought I could do it easily modifying the predicate function like this (showing only the line I changed):

[source]
...
return obj.ID!=id;
...
[/source]

But in this case the function will actually remove all the items. What am I doing wrong?
Thanks!

Sorry for the code not showing properly, I don't know why but the source=cpp messes things up. Edited by Alessandro
0

Share this post


Link to post
Share on other sites
Are you doing this in the same loop? First you remove everything that doesn't match 0, which leaves only things that match 0. Then you remove everything that doesn't match 1, which means that you get rid of all the 0s that you left in the first pass.
0

Share this post


Link to post
Share on other sites
Do you really want to call the removal in the loop? Just think about it... if you call "remove this element if its not equal X" for different X the will obviously be no elements left since they would have to be equal to all the different X.
0

Share this post


Link to post
Share on other sites
[quote name='SiCrane' timestamp='1345652792' post='4972257']
Are you doing this in the same loop? First you remove everything that doesn't match 0, which leaves only things that match 0. Then you remove everything that doesn't match 1, which means that you get rid of all the 0s that you left in the first pass.
[/quote]

That's right, I did something stupid. But then what commands can be used that allow to iterate a vector and, at each loop, find a no-match condition and erase it?
I tried using an iterator with the same result...
0

Share this post


Link to post
Share on other sites
I have no idea what you mean by "find a no-match condition". What exactly do you want to remove from your vector? What exactly do you want left in the vector?
0

Share this post


Link to post
Share on other sites
Sorry for explaining poorly what I intended to do.

Say I have two vector, like:

std::vector<int> someValues;
std::vector<int> someValuesToCheck;

I'd like to remove all the values in someValuesToCheck that are not in someValues.

So that if:

someValues={1,2,5,6,7}
someValuesToCheck={1,3,5,7,8,11}

the resulting someValuesToCheck should have: {1,5,7}

Please tell me if it's not clear. Thanks.
0

Share this post


Link to post
Share on other sites
It sounds relatively straightforward, in pseudo code: erase(remove_if(someValuesToCheck, not( ismember(someValues)))).

What part is causing you trouble?
1

Share this post


Link to post
Share on other sites
std::set_intersection can do that.
[code]
std::vector<int> results;
std::set_intersection(someValues.begin(), someValues.end(), someValuesToCheck.begin(), someValuesToCheck.end(), std::back_inserter(results));

someValuesToCheck = result;
[/code] Edited by Brother Bob
2

Share this post


Link to post
Share on other sites
try something like this, havent t
[CODE]

std::vector<int> somevalues;
std::vector<int> somevaluesTocheck;
bool status = false;


for(int i = 0 ; i < (int)somevaluesTocheck.size() ; i++){

status = false;

for(int j = 0; j < (int)somevalues.size(); j++){

if(somevaluesTocheck[i] == somevalues[j]){

status = true;

}

}


if(!status){
somevaluesTocheck.erase(somevaluesTocheck.begin() + i);
}
}
[/CODE]
-1

Share this post


Link to post
Share on other sites
[quote name='Brother Bob' timestamp='1345740634' post='4972644']
std::set_intersection can do that.
[code]
std::vector<int> results;
std::set_intersection(someValues.begin(), someValues.end(), someValuesToCheck.begin(), someValuesToCheck.end(), std::back_inserter(results));

someValuesToCheck = result;
[/code]
[/quote]

That would be very useful. Unfortunately can't use it because I'm using different type of sets (someValues is a int, someValuesToCheck is a structure) and from what I've read in the documentation the back_inserter expects to compare two equal type of sets.
Thanks anyway, this will come useful in other occasions...
0

Share this post


Link to post
Share on other sites
[quote name='rip-off' timestamp='1345740494' post='4972643']
It sounds relatively straightforward, in pseudo code: erase(remove_if(someValuesToCheck, not( ismember(someValues)))).

What part is causing you trouble?
[/quote]

Thanks, I'm going to try this...
0

Share this post


Link to post
Share on other sites
[CODE]someValues.erase( std::remove_if( someValues.begin(), someValues.end(),
[&]( int val )
{
return (std::find( someValuesToCheck.begin(), someValuesToCheck.end(), val ) == someValuesToCheck.end() );
} ),
someValues.end() );[/CODE]

or

[CODE]
struct myPred
{
myPred(const std::vector<int>& toCheck )
:someValuesToCheck(toCheck)
{}
bool operator()(int val)
{
return (std::find( someValuesToCheck.begin(), someValuesToCheck.end(), val ) == someValuesToCheck.end() );
}
const std::vector<int>& someValuesToCheck;
};
someValues.erase( std::remove_if( someValues.begin(), someValues.end(), myPred(someValuesToCheck) ), someValues.end() );
[/CODE]

(Just realized I got someValues and someValuesToCheck backwards, but you should get the idea) Edited by krippy2k8
1

Share this post


Link to post
Share on other sites
[quote name='rip-off' timestamp='1345671036' post='4972387']
What are you actually trying to remove? As the others have said, if you want to erase all but a given ID, then use the following:
[code]
int id = /* determine id */;
myVec.erase(std::remove_if(myVec.begin(), myVec.end(), myInversePred(id)), myVec.end());
[/code]

You can also use the std::not1 predicate to invert an existing predicate:
[code]
#include <functional>

int id = /* determine id */;
myVec.erase(std::remove_if(myVec.begin(), myVec.end(), std::not1(myPred(id))), myVec.end());
[/code]
[/quote]

I'm trying to use the std::not1 as suggested but I've troubles coding the predicate.

Here is the code:

[source]std::vector<myStruct::myStructLib> myVector;

for (int f=0; f<tempValues.size(); f++)
{
int faceID=tempValues.at(f);
myVector.erase(std::remove_if(myVector.begin(), myVector.end(), std::not1(myPredicate(faceID))), myVector.end());
}

// predicate
struct myPredicate : std::unary_function<int,bool>{
bool operator()(const myStruct::myStructLib &obj) {
return obj.faceID==id;
}
int id;
};[/source]

When I compile I get several errors:
error: no type named 'argument_type' in 'struct myPredicate'
error: no match for call to '(std::unary_negate<myPredicate>) (myStruct::myStructLib&)' Edited by Alessandro
0

Share this post


Link to post
Share on other sites
[quote name='Alessandro' timestamp='1345757490' post='4972755']
[quote name='Brother Bob' timestamp='1345740634' post='4972644']
std::set_intersection can do that.
[code]
std::vector<int> results;
std::set_intersection(someValues.begin(), someValues.end(), someValuesToCheck.begin(), someValuesToCheck.end(), std::back_inserter(results));

someValuesToCheck = result;
[/code]
[/quote]

That would be very useful. Unfortunately can't use it because I'm using different type of sets (someValues is a int, someValuesToCheck is a structure) and from what I've read in the documentation the back_inserter expects to compare two equal type of sets.
Thanks anyway, this will come useful in other occasions...
[/quote]
The function allows the two sets to be of different types, as long as each of the two types are less than comparable with itself, and that the type of the first set is less than comparable with the type of the second set (alternatively you provide a predicate to less than compare an element of the first set with an element of the second set). I should have realized that from your first post that the types were different, sorry, so I didn't mention more about that.

That is, if the first set is of type T1, and the second set is of type T2, then you need the following operators:[list=1]
[*]bool operator<(T1, T1)
[*]bool operator<(T2, T2)
[*]bool operator<(T1, T2), or a predicate bool pred(T1, T2)
[/list]
Operator 1 or 2 is the built in int operator (depending on which one is the integer of course), and the other one you have to define as a sorting criteria for your structure. Operator 3 can either be an operator or a predicate you pass a parameter to the set intersect function.

edit: And I should add now that since you probably shouldn't define an arbitrary operator < for your class for 1 or 2 above, and since that you cannot provide that operator as an explicit predicate, you probably shouldn't go this route. It requires an operator that may not be obvious and unambiguous, so you should not define it. Edited by Brother Bob
0

Share this post


Link to post
Share on other sites
@Brother Bob

std::set_intersection requires sorted ranges, which the OP hasn't definitively stated (though the example data is sorted, that could be human convenience).

@Alessandro
The following compiles for me:
[code]
#include <vector>
#include <functional>
#include <algorithm>

struct Example {
int id;
};

struct myPredicate : std::unary_function<Example, bool> {

myPredicate(int id) : id(id) {
}

bool operator()(const Example &obj) const {
return obj.id == id;
}

private:
int id;
};

void foo(std::vector<Example> &examples, const std::vector<int> &identifiers) {
for (unsigned i = 0 ; i < identifiers.size(); ++i) {
int id = identifiers[i];
examples.erase(std::remove_if(examples.begin(), examples.end(), std::not1(myPredicate(id))), examples.end());
}
}
[/code]
Your code was incorrectly using std::unary_function (the first type parameter must match the parameter type of the operator().

Note that there are two simple ways of implementing this (naive) algorithm, essentially swapping the inner and outer loops. These have different performance characteristics, depending on the relative sizes of the two containers. You want the inner loop to be the smaller one, if you can predict this in advance (i.e. if there are always less identifiers than objects, then the identifiers should be the inner loop).

If this is a performance sensitive application and you are frequently attempting to look up an item by ID, you may also want to consider storing the data in a more search friendly manner, e.g. a binary tree or hash map based on identifier. You could also sort the list of identifiers, this way you can quickly binary search for a given element.

If both ranges are sorted, then you can use some of the more advanced C++ algorithms to help you, as Brother Bob is suggesting. You would need, of course, to balance the cost of lookups against the iteration cost (if you frequently visit the entire collection) and the insert/removal cost (depending on frequency of insertion/removal, and in particular if you need random access insertion).
1

Share this post


Link to post
Share on other sites
[code]
for (int f=0; f<tempValues.size(); f++)
{
int faceID=tempValues.at(f);
myVector.erase(std::remove_if(myVector.begin(), myVector.end(), std::not1(myPredicate(faceID))), myVector.end());
}

// predicate
struct myPredicate : std::unary_function<int,bool>{
bool operator()(const myStruct::myStructLib &obj) {
return obj.faceID==id;
}
int id;
};
[/code]

I don't get it. Unless tempValues is empty or contains only one element, you can just as well call myVector.clear() and be done with it. As soon as this for-loop has executed the second time, your vector will always be empty.

At this point it's not a matter of syntax, it's a matter of the whole approach being simply wrong. The only place where a loop should iterate over all tempValues is inside your predicate (and even there I'd prefer find).

[code]
struct IDcontainedIn
{
IDcontainedIn(const Container& c) : container(c) {}

const Container& container;

bool operator()(ObjectType obj)
{
return find(container.begin(), container.end(), obj.id) != container.end();
}
};


myVector.erase(std::remove_if(myVector.begin(), myVector.end(), std::not1(containedIn(tempValues))), myVector.end());
[/code]
0

Share this post


Link to post
Share on other sites
[quote name='Trienco' timestamp='1345784507' post='4972888']
I don't get it. Unless tempValues is empty or contains only one element, you can just as well call myVector.clear() and be done with it. As soon as this for-loop has executed the second time, your vector will always be empty.

At this point it's not a matter of syntax, it's a matter of the whole approach being simply wrong. The only place where a loop should iterate over all tempValues is inside your predicate (and even there I'd prefer find).
[/quote]

That's right, exactly what's happening.

The solution I used is the one suggested by krippy2k8, which uses std::find into the predicate:

[code]
struct myPred
{
myPred(const std::vector<int>& toCheck )
:someValuesToCheck(toCheck)
{}
bool operator()(int val)
{
return (std::find( someValuesToCheck.begin(), someValuesToCheck.end(), val ) == someValuesToCheck.end() );
}
const std::vector<int>& someValuesToCheck;
};
someValues.erase( std::remove_if( someValues.begin(), someValues.end(), myPred(someValuesToCheck) ), someValues.end() );
[/code]

Nonetheless, it was very interesting to read rip-off, Brother Bob and all other folks suggestions. I'm very new to vectors and very confused about those. Hopefully I learned something new today. Edited by Alessandro
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0