If I have a range and I want to transform adjacent pairs is there a boost
range adaptor to do this?
for example
std::vector<int> a;
a.push_back(1);
a.push_back(2);
a.push_back(3);
auto b = a
| boost::range::transformed([](int x, int y){return x+y;});
and the output would be
3, 5
EDIT
I have made an attempt at a range adaptor
// Base class for holders
template< class T >
struct holder
{
T val;
holder( T t ) : val(t)
{ }
};
// Transform Adjacent
template <typename BinaryFunction> struct transformed_adjacent_holder
: holder
{
transformed_adjacent_holder(BinaryFunction fn) : holder<BinaryFunction>(fn)
};
template <typename BinaryFunction> transform_adjacent
(BinaryFunction fn)
{ return transformed_adjacent_holder<BinaryFunction>(fn); }
template< class InputRng, typename BinFunc>
inline auto Foo(const InputRng& r, const transformed_adjacent_holder<BinFunc> & f)
-> boost::any_range
< std::result_of(BinFunc)
, boost::forward_traversal_tag
, int
, std::ptrdiff_t
>
{
typedef boost::range_value<InputRng>::type T;
T previous;
auto unary = [&](T const & t) {auto tmp = f.val(previous, t); previous = t; return tmp; };
return r | transformed(unary);
}
However I don't know how to deduce the return type of the | operator. If I can do this then the adaptor is almost solved.
You can maintain a dummy variable
int prev=0;
auto b = a | transformed([&prev](int x){int what = x+prev;prev=x;return what;});
No. But you can use the range algorithm:
Live On Wandbox
#include <boost/range/algorithm.hpp>
#include <boost/range/adaptors.hpp>
#include <vector>
#include <iostream>
using namespace boost::adaptors;
int main() {
std::vector<int> a { 1,2,3 };
auto n = a.size();
if (n > 0) {
auto out = std::ostream_iterator<int>(std::cout, "\n");
boost::transform(a, a | sliced(1, n), out, [](int x, int y) { return x + y; });
}
}
This uses the binary transform on a and a slice of itself.
Prints
3
5
Related
I'm working on big codes for which performance matters. And one of the things I read is that raw loops should be avoided and replaced by for_each, range-based for loops, or STL algorithms etc etc. The problem is that in all (most) examples, everything looks adapted for the problem, i.e. for_each is shown with the cout routine *eye roll*.
In my case, the index inside the loop matters (unless you show me otherwise). For example, I want to create tables like this:
std::vector<double> vect1 (nmax), vect2 (nmax);
for (size_t i{0}; i < nmax; ++i) {
vect1[i] = f(i); // f is a routine defined somewhere else
vect2[i] = f(i)+2.0;
}
What I could use is the generate function with a lambda function and it would be something like this:
std::vector<double> vect1 (nmax), vect2 (nmax);
size_t count{0};
generate(vect1.begin(), vect1.end(), [&]() {return f(count++);});
count=0;
generate(vect2.begin(), vect2.end(), [&]() {return f(count++) + 2.0;});
But I’m not a big fan of that, because:
count exists until the end of the routine.
We see that with another function, I have to put back count to zero and generate another vector again. I have to track down all the count variables etc. With the for loop, I could just put it in the same loop.
With the for loop, the correspondence is seen easily. i is on the left and the right. With generate, I feel like it’s counting with a different variable on the left and the right, which means potential mistake.
I can only do count++, not ++count, which means copy of variables.
Of course, this is a simple example. But I would like to know if the generate() version is still better for this kind of things (code/performance/readability wise). Or maybe there’s a better way of doing it, and I’m open to all suggestions and comments.
Thanks!
I wrote an index range that lets me:
std::vector<double> vect1 (nmax), vect2 (nmax);
for (auto i : index_upto(nmax))
vect1[i] = f(i); // f is a routine defined somewhere else
vect2[i] = f(i)+2.0;
}
which eliminates the manual fenceposting but leaves the code otherwise unchanged.
This isn't all that hard. Write a pseudo-iterator that stores a T and returns a copy on unary *. It should support == and ++ (passing both into the stored T).
template<class T>
struct index_it {
T t;
index_it& operator++() { ++t; return *this; }
index_it operator++(int) { auto r = *this; ++*this; return r; }
friend bool operator==( index_it const& lhs, index_it const& rhs ) {
return lhs.t == rhs.t;
}
friend bool operator!=( index_it const& lhs, index_it const& rhs ) {
return lhs.t != rhs.t;
}
T operator*()const& { return t; }
T operator*()&& { return std::move(t); }
};
Next, write a range:
template<class It>
struct range {
It b, e;
It begin() const { return b; }
It end() const { return e; }
};
then compose the two.
template<class T>
using index_range = range<index_it<T>>;
template<class T>
index_range<T> make_index_range( T s, T f ) {
return {{std::move(s)}, {std::move(f)}};
}
index_range<std::size_t> index_upto( std::size_t n ) {
return make_index_range( std::size_t(0), n );
}
note that index_it is not an iterator, but works much like one. You could probably finish it and make it an input iterator; beyond that you run into problems as iterators expect backing containers.
Using a stateful lambda is not a good idea. You may be better off writing your own generate function that takes a function object receiving an iterator:
template<class ForwardIt, class Generator>
void generate_iter(ForwardIt first, ForwardIt last, Generator g) {
while (first != last) {
*first = g(first);
++first;
}
}
You can use it as follows:
generate_iter(vect1.begin(), vect1.end(), [&](const std::vector<double>::iterator& iter) {
auto count = std::distance(vect1.begin(), iter);
return f(count);
});
Demo.
We could use a mutable lambda...
#include <vector>
#include <algorithm>
double f(int x) { return x*2; }
int main()
{
constexpr int nmax = 100;
std::vector<double> vect1 (nmax), vect2 (nmax);
std::generate(vect1.begin(),
vect1.end(),
[count = int(0)]() mutable { return f(count++); });
std::generate(vect2.begin(),
vect2.end(),
[count = int(0)]() mutable { return f(count++) + 2.0; });
}
Another option (uses c++17 for template argument deduction):
template<class F>
struct counted_function
{
constexpr counted_function(F f, int start = 0, int step = 1)
: f(f)
, counter(start)
, step(step) {}
decltype(auto) operator()() {
return f(counter++);
}
F f;
int counter;
int step;
};
used as:
std::generate(vect2.begin(),
vect2.end(),
counted_function([](auto x) { return f(x) + 2.0; }));
And finally, just for fun, could write this:
generate(vect2).invoking(f).with(every<int>::from(0).to(nmax - 1));
...if we had written something like this...
#include <vector>
#include <algorithm>
#include <iterator>
double f(int x) { return x*2; }
template<class T> struct value_iter
{
using value_type = T;
using difference_type = T;
using reference = T&;
using pointer = T*;
using iterator_category = std::forward_iterator_tag;
friend bool operator==(value_iter l, value_iter r)
{
return l.current == r.current;
}
friend bool operator!=(value_iter l, value_iter r)
{
return !(l == r);
}
T const& operator*() const& { return current; }
value_iter& operator++() { ++current; return *this; }
T current;
};
template<class T> struct every
{
struct from_thing
{
T from;
struct to_thing
{
auto begin() const { return value_iter<T> { from };}
auto end() const { return value_iter<T> { to+1 };}
T from, to;
};
auto to(T x) { return to_thing { from, x }; }
};
static constexpr auto from(T start)
{
return from_thing { start };
}
};
template<class F>
struct counted_function
{
constexpr counted_function(F f, int start = 0, int step = 1)
: f(f)
, counter(start)
, step(step) {}
decltype(auto) operator()() {
return f(counter++);
}
F f;
int counter;
int step;
};
template <class Container> struct generate
{
generate(Container& c) : c(c) {}
template<class F>
struct invoking_thing
{
template<class Thing>
auto with(Thing thing)
{
using std::begin;
using std::end;
std::copy(begin(thing), end(thing), begin(c));
return c;
}
F f;
Container& c;
};
template<class F>
auto invoking(F f) { return invoking_thing<F>{f, c}; }
Container& c;
};
int main()
{
constexpr int nmax = 100;
std::vector<double> vect2 (nmax);
generate(vect2).invoking(f).with(every<int>::from(0).to(nmax - 1));
}
With range-v3, it would be something like:
auto vect1 = ranges::view::ints(0, nmax) | ranges::view::transform(f);
auto vect2 = ranges::view::ints(0, nmax) | ranges::view::transform(f2);
// or auto vect2 = vect1 | ranges::view::transform([](double d){ return d + 2.; });
Demo
There is a generic class Vector which extends std::array, and a generic class Expression which defines the possible expressions of the Vectors.
For example:
Vector A({1,2,3});
Vector B({2,2,2});
and the expressions:
A + B;
A * B;
A - B;
A / B;
Now I need this expression A ** B which returns a double as the scalar-production of two vectors A and B, the result must be: 2+4+6=12. The problem is the implementation of operator**!!!
How can i write this operator** ?
My Idea is to overload the dereference operator* of Vector which returns a pointer and then overload the struct-Mul oder multiply operator* ... couldn't solve this error:
"no suitable conversion function from "Expression, Mul, Vector *>" to "double" exists"
template<typename Left, typename Op, typename Right> class Expression {
const Left& m_left;
const Right& m_right;
public:
typedef typename Left::value_type value_type;
// Standard constructor
Expression(const Left& l, const Right& r) : m_left{ l }, m_right{ r } {}
size_t size() const {
return m_left.size();
}
value_type operator[](int i) const {
return Op::apply(m_left[i], m_right[i]);
}
};
struct Mul {
template<typename T> static T apply(T l, T r) {
return l * r;
}
};
template<typename Left, typename Right>
Expression<Left, Mul, Right> operator*(const Left& l, const Right& r) {
return Expression<Left, Mul, Right>(l, r);
}
.......................
// Class Vector extends std::array
template<class T, size_t S> class Vector : public array<T, S> {
public:
// Standard constructor
Vector<T, S>(array<T, S>&& a) : array<T, S>(a) {}
// Initializerlist constructor
Vector(const initializer_list<T>& data) {
size_t s = __min(data.size(), S);
auto it = data.begin();
for (size_t i = 0; i < s; i++)
this->at(i) = *it++;
}
};
.....................................
int main {
Vector<double, 5> A({ 2, 3, 4, 5, 6 });
Vector<double, 5> B({ 3, 3, 3, 3, 3 });
Vector<double, 5> C;
C = A * B; // is a Vector: [6, 9, 12, 15, 18] and it works.
double d = A**B; // but this one does not work, the error message is: "no suitable conversion function from "Expression<Vector<double, 5U>, Mul, Vector<double, 5U> *>" to "double" exists"
cout << d << endl; // must give me: 60
}
A solution I was able to come up with that is very quick and easy to follow is:
class X
{
class B
{
};
B n;
public:
B operator* ()
{
return this->n;
}
double operator * (B rhs)
{
cout<<"Here"<<endl;
return 0;
}
};
int main()
{
X a;
X b;
a ** b;
}
This allows you store the data in the B class and then use it for your needs.
A little bit of type abuse gives you want you want:
#include <vector>
#include <type_traits>
#include <cassert>
#include <iostream>
struct special_vector;
struct star
{
star(special_vector& v) : vec(std::addressof(v)) {}
special_vector* vec;
};
struct special_vector : std::vector<double>
{
using std::vector<double>::vector;
auto operator*() -> star { return star(*this);}
};
auto operator*(special_vector const& l, star const& r) -> double
{
assert(l.size() == r.vec->size());
double result = 0.0;
auto fl = l.cbegin(), fr = r.vec->cbegin(), ll = l.cend();
while (fl != ll)
{
result += (*fl++ * *fr++);
}
return result;
}
int main()
{
auto v1 = special_vector{ 1, 2, 3 };
auto v2 = special_vector{ 1, 2, 3 };
auto ans = v1 ** v2;
std::cout << ans << std::endl;
}
expected output:
14
http://coliru.stacked-crooked.com/a/f831c7594421f37d
I’m writing filter and map algorithms using boost::range library:
template <class Range> struct Converter
{
Converter(const Range& p_range) : m_range(p_range) {}
template<class OutContainer> operator OutContainer() const
{
return {m_range.begin(), m_range.end()};
}
private:
Range m_range;
};
template<class Range> Converter<Range> convert(const Range& p_range) { return {p_range}; }
template<class Range, class Fun> auto map(Range&& p_range, Fun&& p_fun)
{
return convert(p_range | boost::adaptors::transformed(p_fun));
}
template<class Range, class Pred> auto filter(Range&& p_range, Pred&& p_pred)
{
return convert(p_range | boost::adaptors::filtered(p_pred));
}
Right now I can use them like this:
std::vector<int> l_in = {1, 2, 3, 4, 5};
std::vector<int> l_tmp_out = filter(l_in, [](int p){ return p < 4; });
std::vector<int> l_out = map(l_tmp_out, [](int p){ return p + 5; });
I would also like to write code this way:
map(filter(l_in, [](int p){ return p < 4; }), [](int p){ return p + 5; });
Unfortunately my Converter class does not compose with boost::range algorithms so this example does not compile. I'm looking for a proper way to change that.
UPDATE
I followed #sehe link and it turned out that all I had to do was to add this four lines to Converter class:
using iterator = typename Range::iterator;
using const_iterator = typename Range::const_iterator;
auto begin() const { return m_range.begin(); }
auto end() const { return m_range.end(); }
Here's my take on things:
Live On Coliru
#include <boost/range.hpp>
#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm.hpp>
#include <iostream>
#include <vector>
namespace MyRange {
template <typename R> struct Proxy {
Proxy(R&& r) : _r(std::move(r)) {}
Proxy(R const& r) : _r(r) {}
template <typename OutContainer> operator OutContainer() const {
return boost::copy_range<OutContainer>(_r);
}
using iterator = typename boost::range_mutable_iterator<R>::type;
using const_iterator = typename boost::range_const_iterator<R>::type;
auto begin() const { return range_begin(_r); }
auto end() const { return range_end(_r); }
auto begin() { return range_begin(_r); }
auto end() { return range_end(_r); }
private:
R _r;
};
template <typename R> auto make_proxy(R&& r) { return Proxy<R>(std::forward<R>(r)); }
template <typename Range, typename Fun> auto map(Range&& p_range, Fun&& p_fun) {
return make_proxy(std::forward<Range>(p_range) | boost::adaptors::transformed(std::forward<Fun>(p_fun)));
}
template <typename Range, typename Pred> auto filter(Range&& p_range, Pred&& p_pred) {
return make_proxy(std::forward<Range>(p_range) | boost::adaptors::filtered(std::forward<Pred>(p_pred)));
}
}
int main() {
using namespace MyRange;
{
std::vector<int> l_in = {1, 2, 3, 4, 5};
std::vector<int> l_tmp_out = filter(l_in, [](int p){ return p < 4; });
std::vector<int> l_out = map(l_tmp_out, [](int p){ return p + 5; });
boost::copy(l_out, std::ostream_iterator<int>(std::cout << "\nfirst:\t", "; "));
}
{
boost::copy(
map(
filter(
std::vector<int> { 1,2,3,4,5 },
[](int p){ return p < 4; }),
[](int p){ return p + 5; }),
std::ostream_iterator<int>(std::cout << "\nsecond:\t", "; "));
}
}
Prints
first: 6; 7; 8;
second: 6; 7; 8;
NOTES
it uses std::forward<> more accurately
it uses const/non-const iterators
it uses Boost Range traits (range_mutable_iterator<> etc.) instead of hardcoding assuming nested typedefs. This allows things to work with other ranges (e.g. std::array<> or even int (&)[]).
the user-defined converson operator uses boost::copy_range<> for similar reasons
I wanted to replace the loop with an algorithm in the following code
int numbers[] = { ... };
vector<int> output;
for( int* it = numbers+from; it != numbers+to ; ++it )
{
int square = func( *it );
if( predicate(square) )
{
output.push_back(square);
}
}
The program is meant to transform the values and copy them to a destination if a condition occurs.
I could not use std::copy_if because that would not apply a transformation.
I could not use std::transform because that lacks a predicate
It is not even a good idea to write a transform_copy_if() , because of the intermediate copy of the transformed variable.
It looks like my only hope is to create a conditional_back_insert_iterator. Then I could have a pretty decent call like:
int numbers[] = { ... };
vector<int> output;
std::transform(numbers+from, numbers+to,
conditional_back_inserter(predicate, output),
func);
Is this solution the best way to treat such cases ? I couldn't even google for conditional inserters, so I am worried I'm on the wrong path.
I could also imagine that I could implement an alternative solution such as
std::copy_if( transform_iterator<func>(numbers+from),
transform_iterator<func>(numbers+to),
back_inserter(output) );
(which reminds me of an example of *filter_iterators* in boost)
but that does not offer readability.
I think creating your own iterator is the way to go:
#include <iostream>
#include <vector>
#include <iterator>
#include <functional>
template<class T>
class conditional_back_insert_iterator
: public std::back_insert_iterator<std::vector<T>>
{
private:
using Base = std::back_insert_iterator<std::vector<T>>;
using Container = std::vector<T>;
using value_type = typename Container::value_type;
public:
template<class F>
conditional_back_insert_iterator(Container& other, F&& pred)
: Base(other), c(other), predicate(std::forward<F>(pred))
{ }
conditional_back_insert_iterator<T>& operator*()
{ return *this; }
conditional_back_insert_iterator<T>&
operator=(const value_type& val) const
{
if (predicate(val))
c.push_back(val);
return *this;
}
conditional_back_insert_iterator<T>&
operator=(value_type&& val) const
{
if (predicate(val))
c.push_back(std::move(val));
return *this;
}
private:
Container& c;
std::function<bool (const value_type&)> predicate;
};
template<
class Container,
class F,
class value_type = typename Container::value_type
>
conditional_back_insert_iterator<value_type>
conditional_back_inserter(Container& c, F&& predicate)
{
return conditional_back_insert_iterator<value_type>(c, std::forward<F>(predicate));
}
int main()
{
std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9};
std::vector<int> to;
auto is_even = [] (int x) { return (x % 2) == 0; };
std::copy(v.begin(), v.end(), conditional_back_inserter(to, is_even));
}
Here's my attempt.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
template <class Container, class Pred>
class conditional_insert_iterator
: public std::iterator< std::output_iterator_tag, void, void, void, void >
{
public:
explicit conditional_insert_iterator(Container& c, Pred p) : container(&c), pred(p) {}
conditional_insert_iterator& operator=(typename Container::const_reference value) {
if (pred(value))
container->push_back(value);
return *this;
}
conditional_insert_iterator& operator*() {return *this;}
conditional_insert_iterator& operator++() {return *this;}
conditional_insert_iterator& operator++(int) {return *this;}
private:
Container* container;
Pred pred;
};
template< class Container, class Pred>
conditional_insert_iterator<Container, Pred> conditional_inserter( Container& c, Pred pred )
{
return conditional_insert_iterator<Container, Pred>(c, pred);
}
using namespace std;
int main()
{
vector<int> in = { 1, 2, 3, 4, 5, 6 };
vector<int> out;
transform(in.begin(), in.end(),
conditional_inserter(out, [](int i) { return i%2 == 0;}),
[](int i) { return i + 2;});
for (auto i : out)
cout << i << "\n";
return 0;
}
What's the best way for setting an std::vector<int> to a range, e.g. all numbers between 3 and 16?
You could use std::iota if you have C++11 support or are using the STL:
std::vector<int> v(14);
std::iota(v.begin(), v.end(), 3);
or implement your own if not.
If you can use boost, then a nice option is boost::irange:
std::vector<int> v;
boost::push_back(v, boost::irange(3, 17));
std::vector<int> myVec;
for( int i = 3; i <= 16; i++ )
myVec.push_back( i );
See e.g. this question
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
template<class OutputIterator, class Size, class Assignable>
void iota_n(OutputIterator first, Size n, Assignable value)
{
std::generate_n(first, n, [&value]() {
return value++;
});
}
int main()
{
std::vector<int> v; // no default init
v.reserve(14); // allocate 14 ints
iota_n(std::back_inserter(v), 14, 3); // fill them with 3...16
std::for_each(v.begin(), v.end(), [](int const& elem) {
std::cout << elem << "\n";
});
return 0;
}
Output on Ideone
std::iota - is useful, but it requires iterator, before creation vector, .... so I take own solution.
#include <iostream>
#include <vector>
template<int ... > struct seq{ typedef seq type;};
template< typename I, typename J> struct add;
template< int...I, int ...J>
struct add< seq<I...>, seq<J...> > : seq<I..., (J+sizeof...(I)) ... >{};
template< int N>
struct make_seq : add< typename make_seq<N/2>::type,
typename make_seq<N-N/2>::type > {};
template<> struct make_seq<0>{ typedef seq<> type; };
template<> struct make_seq<1>{ typedef seq<0> type; };
template<int start, int step , int ... I>
std::initializer_list<int> range_impl(seq<I... > )
{
return { (start + I*step) ...};
}
template<int start, int finish, int step = 1>
std::initializer_list<int> range()
{
return range_impl<start, step>(typename make_seq< 1+ (finish - start )/step >::type {} );
}
int main()
{
std::vector<int> vrange { range<3, 16>( )} ;
for(auto x : vrange)std::cout << x << ' ';
}
Output:
3 4 5 6 7 8 9 10 11 12 13 14 15 16
Try to use std::generate. It can generate values for a container based on a formula
std::vector<int> v(size);
std::generate(v.begin(),v.end(),[n=0]()mutable{return n++;});