std::list remove_if using state in stack - c++

I want to remove elements from a std::list with linear complexity (going through each element in the list only once). I need to do so depending on the value of a variable in the stack:
int somevalue= 5;
int count=0;
mylist.remove_if(
[](MyStructure* s)
{
if (s->somefield==somevalue)
{
count++;
return true;
}
else
return false;
});
Of course, this doesn't work - somevalue is a variable in the stack.
I've tried using template functions, only to realize (after illegal operation on bound member function expression) you can't really use them in this situation. I know I need to make a closure somehow, so I've read this question, but I can't use C++0x yet and I failed to adapt the other answer for my usecase, as I don't really understand if there's some magic to operator.
Alternatively, is there some way to remove an element from a list given the current position of an iterator (without going through the whole list again to find the element)?

In terms of the lambda expression (a c++11 feature), you can capture the somevalue by value like this: [somevalue](...) {...}

You need to capture the variable in the sample code:
int somevalue= 5;
mylist.remove_if( [somevalue](MyStructure* s){ s->somefield==somevalue });
If no C++11 could be used you need to make the functor yourself:
// For static constant check
template <int CheckValue>
struct Equal {
operator()(const MyStructure* s) { return s->somefield == CheckValue; }
};
mylist.remove_if(Equal<5>);
..or..
// For dynamic constant check as the sample code
struct Equal {
Equal(int check_value) : m_check_value(check_value) {}
operator()(const MyStructure* s) { return s->somefield == m_check_value; }
private:
int m_check_value;
};
mylist.remove_if(Equal(somevalue));

You must capture somevalue in your lamdba expression to use it:
Example (live here) :
struct MyStructure
{
int somefield;
};
int main(int argc, char** argv) {
std::list<MyStructure> my_list = { { 1 }, { 2 }, { 1 }, { 3 }, { 2 }, { 1 } };
int somevalue = 2;
my_list.remove_if( [somevalue](MyStructure s){ return s.somefield == somevalue; });
// ^^^^^^
// Capture
for(auto& s : my_list)
std::cout << s.somefield << " ";
return 0;
}

Iterate on the elements to identify which one you want to remove. Use erase to remove the identified elements and continue to iterate from the returned iterator.
Something like that:
int somevalue=5;
std::list<MyStructure*> myList;
// ...
std::list<MyStructure*>::iterator it=myList.begin();
while(it!=myList.end())
{
if ((*it)->somefield==somevalue)
{
it = myList.erase(it);
}
else
{
++it;
}
}

Related

function parameters that are writeable only by the function itself - recursion counter

So I'm trying to write a recursive function that keeps track of how often it got called. Because of its recursive nature I won't be able to define an iterator inside of it (or maybe it's possible via a pointer?), since it would be redefined whenever the function gets called. So i figured I could use a param of the function itself:
int countRecursive(int cancelCondition, int counter = 0)
{
if(cancelCondition > 0)
{
return countRecursive(--cancelCondition, ++counter);
}
else
{
return counter;
}
}
Now the problem I'm facing is, that the counter would be writeable by the caller of the function, and I want to avoid that.
Then again, it wouldn't help to declare the counter as a const, right?
Is there a way to restrict the variable's manipulation to the function itself?
Or maybe my approach is deeply flawed in the first place?
The only way I can think of solving this, is to use a kind of "wrapper-function" that keeps track of how often the recursive function got called.
An example of what I want to avoid:
//inside main()
int foo {5};
int countToZero = countRecursive(foo, 10);
//countToZero would be 15 instead of 5
The user using my function should not be able to initially set the counter (in this case to 10).
You can take you function as is, and wrap it. One way I have in mind, which completely encapsulates the wrapping is by making your function a static member of a local class. To demonstrate:
int countRecursive(int cancelCondition)
{
struct hidden {
static int countRecursive(int cancelCondition, int counter = 0) {
if(cancelCondition > 0)
{
return countRecursive(--cancelCondition, ++counter);
}
else
{
return counter;
}
}
};
return hidden::countRecursive(cancelCondition);
}
Local classes are a nifty but rarely seen feature of C++. They possess some limitations, but fortunately can have static member functions. No code from outside can ever pass hidden::countRecursive an invalid counter. It's entirely under the control of the countRecursive.
If you can use something else than a free function, I would suggest to use some kind of functor to hold the count, but in case you cant, you may try to use something like this using friendship to do the trick:
#include <memory>
class Counter;
int countRecursive(int cancelCondition, std::unique_ptr<Counter> counter = nullptr);
class Counter {
int count = 0;
private:
friend int countRecursive(int, std::unique_ptr<Counter>);
Counter() = default; // the constructor can only be call within the function
// thus nobody can provide one
};
int countRecursive(int cancelCondition, std::unique_ptr<Counter> c)
{
if (c == nullptr)
c = std::unique_ptr<Counter>(new Counter());
if(cancelCondition > 0)
{
c->count++;
return countRecursive(--cancelCondition, std::move(c));
}
else
{
return c->count;
}
}
int main() {
return countRecursive(12);
}
You can encapsulate the counter:
struct counterRecParam {
counterRecParam(int c) : cancelCondition(c),counter(0) {}
private:
int cancelCondition;
int counter;
friend int countRecursive(counterRecParam);
};
Now the caller cannot modify the counter, and you only need to modify the function slightly:
int countRecursive(counterRecParam crp)
{
if(crp.cancelCondition > 0)
{
--crp.cancelCondition;
++crp.counter;
return countRecursive(crp);
}
else
{
return crp.counter;
}
}
And the implicit conversion lets you call it with an int
counterRecursive(5);
One way to do this is to use a functor. Here's a simple example:
#include <iostream>
class counter
{
public:
unsigned operator()(unsigned m, unsigned n)
{
// increment the count on every iteration
++count;
// rest of the function
if (m == 0)
{
return n + 1;
}
if (n == 0)
{
return operator()(m - 1, 1);
}
return operator()(m - 1, operator()(m, n - 1));
}
std::size_t get_count() const
{
return count;
}
private:
// call count
std::size_t count = 0;
};
int main()
{
auto f = counter();
auto res = f(4, 0);
std::cout << "Result: " << res << "\nNumber of calls: " << f.get_count() << std::endl;
return 0;
}
Output:
Result: 13
Number of calls: 107
Since the count is stored in the object itself, the user cannot overwrite it.
Have you tried using "static" counter variable. Static variables gets initialized just once, and are best candidates to be used as counter variables.

Unpack vector into arguments to call functions that have a variable number of arguments

It's a little bit tricky trying to phrase this question.
So let's say I have a large number of functions that all have varying numbers of arguments - some have none, some have one, some have a few or many more. I receive the parameters for these functions in a vector. Normally, I can just call them like this:
#include <vector>
int my_functionA(std::string a) { /*...*/ return 1; }
int my_functionB(std::string a, std::string b) { /*...*/ return 2; }
void some_useful_function(std::vector<std::string> vec, int choice) {
if (choice == 1) {
// Error checking would happen here
int val = my_functionA(vec[0]);
// Do something with val
// ...
}
else if (choice == 2) {
// Error checking would happen here
int val = my_functionB(vec[0], vec[1]);
// Do something with val
// ...
}
}
Error checking would be making sure there are the correct number of arguments, etc. But this gets very tedious if I have a large number of functions, and the error checks and what I do with the return value are mostly the same (ie checking that the vector size matches the number of arguments). I end up repeating very similar ~15 lines of code 100 times, and if I ever decide I want to change or add something to that 15 line 'sequence', I'd have to redo it a hundred times.
It would make more sense if I could make a map from a choice to a data structure that has the function pointer and other information I'll need, and then the my_useful_function would be more like:
struct funcPointer {
funcPointer(void * f, int n) : fnc(f), numOfArgs(n) {};
void * fnc;
int numOfArgs;
};
std::map<int, funcPointer> = {
{1, funcPointer(my_functionA, 1)},
{2, funcPointer(my_functionB, 2)}};
void some_useful_function(std::vector<std::string> vec, int choice) {
if (map.count(choice) > 0) {
// Do stuff if map[choice].numOfArgs doesn't match vec size
int val = map[choice].fnc(vectorSomehowConvertedToArguments);
// Do stuff with the return value
}
}
This answer with the 'index trick' got me really close, but since it requires a constant for the unpack_caller, I'm not sure how to mesh that into my map / data struct.
First, here's funcPointer which returns a lambda doing the std::vector-to-arguments juggling before calling a given function, generated based on the function's arity:
template <class F, std::size_t... ParamsIdx>
auto funcPointer(F f, std::index_sequence<ParamsIdx...>) {
return [f](std::vector<std::string> const &args) {
assert(args.size() == sizeof...(ParamsIdx));
return f(args[ParamsIdx]...);
};
}
template <class... Params>
auto funcPointer(int (*f)(Params...)) {
return funcPointer(f, std::index_sequence_for<Params...>{});
}
These lambdas can then be stored together in a std::map<int, std::function<int(std::vector<std::string> const &)>>:
std::map<int, std::function<int(std::vector<std::string> const &)>> map = {
{1, funcPointer(my_functionA)},
{2, funcPointer(my_functionB)}
};
Finally, the call is straightforward:
void some_useful_function(std::vector<std::string> vec, int choice) {
if (map.count(choice) > 0) {
int val = map[choice](vec);
// Do stuff with the return value
std::cout << "Call succeeded, got " << val << '\n';
}
}
See it live on Wandbox

Elegant Way To Generate Composite Permutations in C++

I have a class Test which contains two vectors of a Letter class, a user defined type for which the less-than operator (<) has been implemented. How can I best generate all possible permutations of Test?
class Test
{
vector<Letter> letter_box_a;
vector<Letter> letter_box_b;
}
So if letter_box_a contains the letters A and B and letter_box_b contains C and D the valid permutations of Test would be (AB)(CD), (BA)(CD), (AB)(DC) and (BA)(DC).
Although I am able to brute force it, I was trying to write a better (more elegant/efficient) function which would internally call std::next_permutation on the underlying containers allowing me to do
Test test;
while (test.set_next_permutation())
{
// Do the stuff
}
but it appears to be a bit trickier than I first anticipated. I don't necessarily need an STL solution but would like an elegant solution.
I would think you could do something like
bool Test::set_next_permutation() {
auto &a = letter_box_a, &b = letter_box_b; // entirely to shorten the next line
return std::next_permutation(a.start(), a.end()) || std::next_permutation(b.start(), b.end());
}
(Of course, a while loop will skip the initial permutation in any case. You want a do...while loop instead.)
If you want to use std::next_permutation, you need a nested loop for each vector you are permuting:
std::string s0 = "ab";
std::string s1 = "cd";
do
{
do
{
cout << s0 << "" << s1 << endl;
} while (std::next_permutation(s0.begin(), s0.end()));
} while (std::next_permutation(s1.begin(), s1.end()));
Output:
abcd
bacd
abdc
badc
And, in the class:
class Foo
{
public:
Foo(std::string_view arg_a, std::string_view arg_b)
: a(arg_a)
, b(arg_b)
, last(false)
{ }
void reset_permutations()
{
last = false;
}
bool next_permutation(std::string& r)
{
if (last)
return false;
if (not std::next_permutation(a.begin(), a.end()))
if (not std::next_permutation(b.begin(), b.end()))
last = true;
r = a + b;
return true;
}
private:
std::string a, b;
bool last;
};
int main(int argc, const char *argv[])
{
Foo foo("ab", "cd");
string s;
while (foo.next_permutation(s))
cout << s << endl;
return 0;
}

C++ Function to find the min+max value element in a vector

I just started learning C++ so I am very new to this.
I have a vector vector<int> pricelist{30,10,16,25,13};that's stored in a main class.
I want to implement a function lowestNHighestPrices() to return a Prices object that gives me the index value of the highest and lowest values in the vector (i.e. 0 and 1 respectively).
class Prices {
protected:
int lowestPrice;
int highestPrice;
public:
Prices(const int lowestPriceIn, const int highestPriceIn)
: lowestPrice(lowestPriceIn), highestPrice(highestPriceIn) {
}
int getlowestPrice() const {
return lowestPrice;
}
int gethighestPrice() const {
return highestPrice;
}
};
the method will be called by this line of code Prices prices = lowestNHighestPrices(prices);
I am not entirely sure of the syntax, is there a keyword of some sort I can use with the getter methods so that I can obtain the highest and lowest values from the vector? Such that getLowestPrice() == 0 and getHighestPrice() == 1?
As suggested in comments, you can use std::min_element and std::max_element. The following code (with an update of the Prices class for the empty list) makes one list iteration.
class Prices {
protected:
int lowestPrice;
int highestPrice;
bool isValid;
public:
Prices() : lowestPrice(), highestPrice(), isValid(false) {}
Prices(const int lowestPriceIn, const int highestPriceIn)
: lowestPrice(lowestPriceIn), highestPrice(highestPriceIn) {}
void updateWith(int val)
{ if (!isValid) {
lowestPrice = highestPrice = val;
isValid = true;
}
else if (val < lowestPrice)
lowestPrice = val;
else if (val > highestPrice)
highestPrice = val;
}
};
Prices lowestNHighestPrices(const vector<int>& pricelist) {
Prices result;
for (auto val : pricelist)
result.updateWith(val);
return result;
}
If you have C++11 available (and you should), just use std::minmax_element:
Prices lowestNHighestPrices(const vector<int>& pricelist)
{
assert( !pricelist.empty() ); // just in case
auto res = std::minmax_element(
pricelist.cbegin(),
pricelist.cend()
);
return Prices( *res.first, *res.second );
}
Return a std::pair<int, int>.
std::pair<int, int> lowestNHighestPrices() const
{
return {lowestPrice, highestPrice};
}
your class already has a public interface/methods to your high and low price values. returning another structure from it or using a pass by reference parameter is although a possible solution but looks pointless in this situation. and use of std::pair, another class/structure, should be preferred where more generic code is intended, such as containers, due to its abstract naming to access member variables.

Lazy transform in C++

I have the following Python snippet that I would like to reproduce using C++:
from itertools import count, imap
source = count(1)
pipe1 = imap(lambda x: 2 * x, source)
pipe2 = imap(lambda x: x + 1, pipe1)
sink = imap(lambda x: 3 * x, pipe2)
for i in sink:
print i
I've heard of Boost Phoenix, but I couldn't find an example of a lazy transform behaving in the same way as Python's imap.
Edit: to clarify my question, the idea is not only to apply functions in sequence using a for, but rather to be able to use algorithms like std::transform on infinite generators. The way the functions are composed (in a more functional language like dialect) is also important, as the next step is function composition.
Update: thanks bradgonesurfing, David Brown, and Xeo for the amazing answers! I chose Xeo's because it's the most concise and it gets me right where I wanted to be, but David's was very important into getting the concepts through. Also, bradgonesurfing's tipped Boost::Range :).
Employing Boost.Range:
int main(){
auto map = boost::adaptors::transformed; // shorten the name
auto sink = generate(1) | map([](int x){ return 2*x; })
| map([](int x){ return x+1; })
| map([](int x){ return 3*x; });
for(auto i : sink)
std::cout << i << "\n";
}
Live example including the generate function.
I think the most idiomatic way to do this in C++ is with iterators. Here is a basic iterator class that takes an iterator and applies a function to its result:
template<class Iterator, class Function>
class LazyIterMap
{
private:
Iterator i;
Function f;
public:
LazyIterMap(Iterator i, Function f) : i(i), f(f) {}
decltype(f(*i)) operator* () { return f(*i); }
void operator++ () { ++i; }
};
template<class Iterator, class Function>
LazyIterMap<Iterator, Function> makeLazyIterMap(Iterator i, Function f)
{
return LazyIterMap<Iterator, Function>(i, f);
}
This is just a basic example and is still incomplete as it has no way to check if you've reached the end of the iterable sequence.
Here's a recreation of your example python code (also defining a simple infinite counter class).
#include <iostream>
class Counter
{
public:
Counter (int start) : value(start) {}
int operator* () { return value; }
void operator++ () { ++value; }
private:
int value;
};
int main(int argc, char const *argv[])
{
Counter source(0);
auto pipe1 = makeLazyIterMap(source, [](int n) { return 2 * n; });
auto pipe2 = makeLazyIterMap(pipe1, [](int n) { return n + 1; });
auto sink = makeLazyIterMap(pipe2, [](int n) { return 3 * n; });
for (int i = 0; i < 10; ++i, ++sink)
{
std::cout << *sink << std::endl;
}
}
Apart from the class definitions (which are just reproducing what the python library functions do), the code is about as long as the python version.
I think the boost::rangex library is what you are looking for. It should work nicely with the new c++lambda syntax.
int pipe1(int val) {
return 2*val;
}
int pipe2(int val) {
return val+1;
}
int sink(int val) {
return val*3;
}
for(int i=0; i < SOME_MAX; ++i)
{
cout << sink(pipe2(pipe1(i))) << endl;
}
I know, it's not quite what you were expecting, but it certainly evaluates at the time you want it to, although not with an iterator iterface. A very related article is this:
Component programming in D
Edit 6/Nov/12:
An alternative, still sticking to bare C++, is to use function pointers and construct your own piping for the above functions (vector of function pointers from SO q: How can I store function pointer in vector?):
typedef std::vector<int (*)(int)> funcVec;
int runPipe(funcVec funcs, int sinkVal) {
int running = sinkVal;
for(funcVec::iterator it = funcs.begin(); it != funcs.end(); ++it) {
running = (*(*it))(running); // not sure of the braces and asterisks here
}
return running;
}
This is intended to run through all the functions in a vector of such and return the resulting value. Then you can:
funcVec funcs;
funcs.pushback(&pipe1);
funcs.pushback(&pipe2);
funcs.pushback(&sink);
for(int i=0; i < SOME_MAX; ++i)
{
cout << runPipe(funcs, i) << endl;
}
Of course you could also construct a wrapper for that via a struct (I would use a closure if C++ did them...):
struct pipeWork {
funcVec funcs;
int run(int i);
};
int pipeWork::run(int i) {
//... guts as runPipe, or keep it separate and call:
return runPipe(funcs, i);
}
// later...
pipeWork kitchen;
kitchen.funcs = someFuncs;
int (*foo) = &kitchen.run();
cout << foo(5) << endl;
Or something like that. Caveat: No idea what this will do if the pointers are passed between threads.
Extra caveat: If you want to do this with varying function interfaces, you will end up having to have a load of void *(void *)(void *) functions so that they can take whatever and emit whatever, or lots of templating to fix the kind of pipe you have. I suppose ideally you'd construct different kinds of pipe for different interfaces between functions, so that a | b | c works even when they are passing different types between them. But I'm going to guess that that's largely what the Boost stuff is doing.
Depending on the simplicity of the functions :
#define pipe1(x) 2*x
#define pipe2(x) pipe1(x)+1
#define sink(x) pipe2(x)*3
int j = 1
while( ++j > 0 )
{
std::cout << sink(j) << std::endl;
}