How to remove an object from std::vector? - vector

ALL,
Consider following code:
class CPlayer
{
public:
CPlayer(bool new) { m_new = new; };
bool IsNewPlayer() { return m_new; }
private:
bool m_new;
};
int main()
{
std::vector<CPlayer> players_pool;
players_pool.push_back( false );
players_pool.push_back( false );
players_pool.push_back( true );
players_pool.push_back( false );
}
Now what I'm looking for is to remove the players which has m_new as true.
Is it possible to do something like this:
players_pool.erase( std::remove( players_pool.begin(), players_pool.end(), players_pool.at().IsNewPlayer() ), players_pool.end() );
Now everywhere the examples given are for simple integers and not for the class objects.
Is there an easy way to perform such an operation?
And I need it to work in MSVC 2010 and XCode 4 with 10.6 SDK.
Note: The code given is a simplified version of the actual code I'm working on. Class CPlayer has a lot more fields than I put here but they are not relevant to this post.
Thank you.
P.S.: I found this but my question here is if it will work on OSX. My remover looks like this:
struct Remover : public std::binary_function<CPlayer,void,bool>
{
public:
bool operator()(const CPlayer &player) const
{
return player.IsNewPlayer();
}
};

Yes, it is possible. The standard library provides std::remove, which removes objects which are equal to some specified value (using the == operator), and it has std::remove_if, which, instead of a value, takes a function which is called on the object, and if it returns true, it indicates that the object should be removed. So simply write a function which defines the condition you want, and use that:
players_pool.erase( std::remove_if(
players_pool.begin(),
players_pool.end(),
[](const CPlayer& p){ return p.IsNewPlayer(); }),
players_pool.end() );
Note, I used a lambda for the function passed to remove_if. If your compiler doesn't support that yet, you can simply define the function separately, either as a function (with the signature bool func(const CPlayer&);, or a function object with an bool operator()(const CPlayer&)

Simply use std::remove_if and a lambda function as predicate:
players.erase( std::remove_if( players.begin() ,
players.end() ,
[](const Player& player) { return player.IsNewPlayer(); }
) );
Lambdas are supported by VC10 (VS2010 C++ compiler).
In XCode you are using Clang? It supports lambda expressions too.
On the other hand, if your compiler not supports C++11 lambdas, your functor is the correct way.

Related

In functional programming, is "saving the state" of an algorithm at the recursive function argument cheating?

for instance, lets suppose we had to write an algorithm to get the max value of an array of integers, could we still call the code functional if we make the recursive function return various information that simulates an assignment to a global object? an exemple:
function getMax(array, props={}) {
const {index = 0, actualMax = array[0]}= props ///initial props
const arrayNotEnded = array[index + 1] !== undefined
if (arrayNotEnded) {
const maxOf= (a, b) => a > b ? a : b
const newMax = maxOf(actualMax, array[index+1])
const nextIndex = index+1
return getMax(array, {index:nextIndex, actualMax:newMax} )
}else return actualMax
}
a funny thing about that is, in Haskell, we cannot have optional arguments, so this logic would not be something cool to work with, since we would have to pass the initial props every time we would need to call this function.
Yes, you could consider it cheating, but this is a well-known technique in functional programming, the accumulator argument [1][2][3]. Remember: code doesn't become functional by not having state, functional programming is all about making state explicit. There's no better way of doing that than by making it a parameter of your function.
Your code has some other problems, though. Most prominently, the state should be internal to your function, only being passed to a helper function (that might be locally declared or separate) but not as part of your function's public interface. This also prevents confusing your helper function by passing invalid state (e.g. out-of-bound indices). And yes, also the optional parameter smells - not because you think this is not possible in Haskell (it is, using Maybe), but because it can be forgotten or passed mistakenly. Instead, the helper function should have a required state parameter, and getMax should have none.
Last but not least, you should avoid out-of-bounds indexed access on arrays - check the length to know where the end is, don't compare to undefined. This includes unconditionally accessing array[0] - that makes it very easy to overlook that your function can return undefined. Make this error condition explicit as well.
Here's how I'd write it:
function getMax(array) {
if (!array.length)
throw new Error("array must be non-empty");
else
return maxFrom(1, array[0]);
function maxFrom(index, max) {
if (index < array.length)
return maxFrom(index+1, array[index] > max ? array[index] : max);
else
return actualMax
}
}
Even better than throwing exceptions would be if you'd had an algebraic data type at hand that you could return to represent the error-or-result.

How to specify a list of generics of unknown/arbitrary size

Note: I started a discussion on Github about this subject.
I have a zip function, for now it is typed for iterables of the same type T. I would like to have this typed for arbitrary mixed input type but still conserving the matching output type, for example, if the input type [Iterable<T>, Iterable<U>] I want the output type to be Iterable<[T, U]>. Is it possible to have this for arbitrary input size? I basically want to say, if you have this list of type as input you'll have them as output.
Here is the current version of my zip:
export function *zip<T>(...iterables:Array<Iterable<T>>): Iterable<Array<T>> {
const iterators = iterables.map(iterable => iter(iterable));
while(true){
const items = iterators.map(iterator => iterator.next());
if (items.some(item => item.done)){
return;
}
yield ((items.map(item => { return item.value }): Array<any>): Array<T>);
}
}
export function *iter<T>(iterable:Iterable<T>): Iterator<T> {
yield* iterable;
}
Current best solution by AndrewSouthpaw:
declare function zip<A, B>(Iterable<A>, Iterable<B>): Iterable<[A, B]>;
declare function zip<A, B, C>(Iterable<A>, Iterable<B>, Iterable<C>): Iterable<[A, B, C]>;
declare function zip<A, B, C, D>(Iterable<A>, Iterable<B>, Iterable<C>, Iterable<D>): Iterable<[A, B, C, D]>;
export function *zip<T>(...iterables:Array<Iterable<T>>): Iterable<Array<T>> {
const iterators = iterables.map(iterable => iter(iterable));
while(true){
const items = iterators.map(iterator => iterator.next());
if (items.some(item => item.done)){
return;
}
yield ((items.map(item => { return item.value }): Array<any>): Array<T>);
}
}
It works as expected when called with 4, 3 or 2 iterables, when called with 5 or more arguments flow will simply say that zip can only be called with 4 or less arguments. Of course we could add as many function signature as we like to get it to work for 5, 6 or any number N of arguments, but that would require to declare N distinct signatures (which is a bit ugly). On the other hand this strategy does not allow to have an unbounded number of arguments (like the spread operator does). I'm still looking for that.
This raised a more general question, is there any language in which this exists?
I really have the feeling that this can be done in theory (not necessarily in flow), on the other hand I can't recall of a statically typed language in which I've done/seen that (I would also be interested in seeing this kind of type checking in any language).
To be a bit more specific, my feeling is that if you have a type checking system in which (by definition) all types are statically known (any variable has a known type x) then function f: Array<Iterable<x>> -> Iterable<Array<x>> is always called on a known type x. Therefore we should be able to statically decide what type f will return given x (whether x is a single generic type or a list of generic types).
The same goes for the function itself, if you have a type x as input, then you only need to check that your function preserve type x.
Maybe this needs to be defined recursively in some languages, that would also be interesting to see.
We've only been able to accomplish this through overriding the function signature declaration. This might help:
declare function zip<A, B>(Iterable<A>, Iterable<B>): Iterable<[A, B]>
declare function zip<A, B, C>(Iterable<A>, Iterable<B>, Iterable<C>): Iterable<[A, B, C]>
declare function zip<A, B, C, D>(Iterable<A>, Iterable<B>, Iterable<C>, Iterable<D>): Iterable<[A, B, C, D]>
export function zip(a, b, c, d) {
/* ... */
}
Here is the working solution. All credit goes to jbrown215 from Flow team, he found the idea of using $ReadOnlyArray<mixed> here:
export function *zip<T: $ReadOnlyArray<mixed>>(...iterables:Array<Iterable<T>>): Iterable<Array<T>> {
const iterators = iterables.map(iterable => iter(iterable));
while(true){
const items = iterators.map(iterator => iterator.next());
if (items.some(item => item.done)){
return;
}
yield ((items.map(item => { return item.value }): Array<any>): Array<T>);
}
}
export function *iter<T>(iterable:Iterable<T>): Iterator<T> {
yield* iterable;
}

D: Strange behaviour from std.container.BinaryHeap with custom function for comparison

I've written the following code for a heap of Node*s, which are found in module node:
import std.exception, std.container;
public import node;
alias NodeArray = Array!(const (Node)*);
alias NodeHeap = BinaryHeap!(NodeArray, cmp_node_ptr);
auto make_heap() {
return new NodeHeap(NodeArray(cast(const(Node)*)[]));
}
void insert(NodeHeap* heap, in Node* u) {
enforce(heap && u);
heap.insert(u);
}
pure bool cmp_node_ptr(in Node* a, in Node* b) {
enforce(a && b);
return (a.val > b.val);
}
I then tried running the following unit tests on it, where make_leaf returns a Node* initialized with the argument given:
unittest {
auto u = make_leaf(10);
auto heap = make_heap();
insert(heap, u); //bad things happen here
assert(heap.front == u);
auto v = make_leaf(20);
insert(heap, v);
assert(heap.front == u); //assures heap property
}
The tests make it to the line I comment-marked, and then throw an enforcement error on the line enforce(a && b) in cmp_node_ptr. I'm totally lost as to why this is happening.
you are doing wrong thing in this operator:
NodeArray(cast(const(Node)*)[])
you obviously want to create empty NodeArray, but what you really got is NodeArray with one null item. NodeArray constructor takes list of values for new array as arguments, and you passing one "empty array" (which is essentially null), thus creating NodeArray with one null element.
the correct way is just:
NodeArray()
i.e.:
auto make_heap() {
return new NodeHeap();
}
make this change and everything will be fine.
p.s. it seems that D notation for multiple arguments of type U (U[] values...) made you think that constructor accepts another array as initialiser.
p.p.s. sorry, fixed make_heap() code: accidentally forgot to write "NodeArray()" in it. and edited it again, as empty NodeArray() call is not necessary there. double fault!

How to export Rcpp Class method with default arguments

I have a c++ class myClass which has a method foo(int x=0) and it has a parameter x with default value = 0. The c++ class could be exported to R by
RCPP_MODULE(my_module) {
class_< myClass >( "myClass" )
.constructor()
.method( "foo", &myClass::foo )
;
}
However, in R, I am not able to call myClass$foo without specifying the value of x.
I have to specify the value of x regardless the default value.
So my question is how to export Rcpp class method with default arguments. I tried to search it over the internet. The closest thing that I found was
using namespace Rcpp;
double norm( double x, double y ) { return sqrt( x*x + y*y );
}
RCPP_MODULE(mod_formals2) {
function("norm", &norm,
}
But it doesn't work in my case.
I had the same problem recently. After looking at the source file of rcpp handling the classes (~/R/x86_64-pc-linux-gnu-library/3.2/Rcpp/include/Rcpp/module/class.h in my setup) I don't think that it is currently possible.
The best workaround I came up with was to create a wrapper in R to handle the default arguments.
Here is a full example demonstrating how to do it. I defined a simple function that accepts 3 arguments and outputs their sum. The second and third arguments are optional and set by default to 10 and 100.
mwe.cpp
#include <Rcpp.h>
class MWE {
public:
int sum_them(int mandatory_arg,
int optional_arg1,
int optional_arg2)
{
return (mandatory_arg+optional_arg1+optional_arg2);
}
};
RCPP_MODULE(mod_mwe) {
Rcpp::class_<MWE>( "MWE" )
.constructor()
.method("sum_them", &MWE::sum_them)
;
}
mwe.R
require('Rcpp')
# source the C++ code
sourceCpp('mwe.cpp')
# create an instance of the class:
my_mwe = new(MWE)
# assign a wrapper with default arguments to the instance:
assign('sum_them_wrapper',
function(mandatory_arg,
optional_arg1=10,
optional_arg2=100) {
return(my_mwe$sum_them(mandatory_arg, optional_arg1, optional_arg2))
},
envir = my_mwe
)
This outputs the expected result:
> my_mwe$sum_them_wrapper(3, optional_arg2=500)
[1] 513

In boost::python how to wrap an overrideable function which takes a container of pointers to C++ objects and returns a pointer to one of them?

I'm wrapping a C++ framework with boost::python and I need to make a C++ method overrideable in python. This is a hook method, which is needed by the framework and has a default implementation in C++, which iterates through a list (passed as parameter) and performs a choice. The problems arise because the choice is stated by returning a pointer to the chosen element (an iterator, in fact), but I can't find a way to return a C++ pointer as a result of a python function. Can anyone help?
Thanks
This is most certainly doable, but you don't really have enough details. What you really need to do is create a c++ function that calls your python function, proceses the python result and returns a c++ result. To paraphrase (let's assume I have a boost object called func that points to some python function that parses a string and returns an int):
using boost::python;
A* test(const std::string &foo) {
object module = import("mymodule");
object func = module.attr("myfunc");
// alternatively, you could set the function by passing it as an argument
// to a c++ function that you have wrapped
object result = func(foo);
int val = extract<int>(result);
return new A(val); // Assumes that you've wrapped A.
}
// file: https://github.com/layzerar/box2d-py/blob/master/python/world.cpp
struct b2ContactFilter_W: b2ContactFilter, wrapper<b2ContactFilter>
{
bool ShouldCollide(b2Fixture* fixtureA, b2Fixture* fixtureB)
{
override func = this->get_override("ShouldCollide");
if (func)
{
return func(ref(fixtureA), ref(fixtureB)); //ref is boost::ref
}
return b2ContactFilter::ShouldCollide(fixtureA, fixtureB);
}
bool ShouldCollideDefault(b2Fixture* fixtureA, b2Fixture* fixtureB)
{
return b2ContactFilter::ShouldCollide(fixtureA, fixtureB);
}
};
class_<b2ContactFilter_W, boost::noncopyable>("b2ContactFilter")
.def("ShouldCollide", &b2ContactFilter::ShouldCollide, &b2ContactFilter_W::ShouldCollideDefault)
;
Is this what you need ?

Resources