Generic way to access elements of sequential sequences - c++

What is the best way to write generic code for targeting C arrays, C++ libraries, and C++ standard library?
Example: dot product
template<class Vector1, class Vector2>
constexpr auto dot_product(Vector1 const& v1, Vector2 const& v2) {
// doesn't work for Vectors that do not implement () subscripting
using return_type = decltype(v1(0) + v2(0));
return_type tmp = return_type{};
// doesn't work for e.g. std::tuple
for (std::size_t i = 0, e = size(v1); i != e; ++i) {
tmp += v1(i) * v2(i);
}
return tmp;
}
There is a problem with access the elements:
for a C array array[i], C matrix array[i][j]
for a C++ std::vector, vector[i]
for a C++ tuple, std::get<i>(tuple)
for a C++ linear algebra vector/matrix (e.g. Eigen): vector(i), matrix(i, j)
There is a problem with iteration:
run-time for loops for C arrays, std::vectors, ...
boost::fusion for e.g. std::array, std::tuple, ...
custom expression for linear algebra libraries that handle both cases under the covers (e.g. Eigen uses expression templates)
Boost.Geometry uses a get function to solve the access problem which results in convoluted code full with gets everywhere. It also uses strategies for dispatching the different iteration methods.
Are there any better alternatives?

You can work with policy based template.
template <typename T>
struct DefaultUsePolicy {
int DoSomethingWithT( T const & ) {
return 42;
}
};
template < typename T, typename UsePolicy = DefaultUsePolicy<T>>
int Generic( T& arg ) {
UsePolicy use;
return use.DoSomethingWithT(arg);
}
Then have some default implementation for common type and let the user write a policy if he have a custom type.
The Generic function will document the services need in the policies it requires.
It is similar to what is done with std::unique_ptr and std::default_deleter to provide control on the destruction of the pointer owned.

You may wrap the get function inside a class, something like:
#define Return(ret) decltype ret { return ret; }
template <typename T>
class Getter
{
private:
T& t;
public:
constexpr explicit Getter(T&t) : t(t) {}
constexpr auto operator () (std::size_t i) const
-> Return((get(t, i)))
constexpr auto operator () (std::size_t i, std::size_t j) const
-> Return((get(t, i, j)))
operator T&() const { return t; }
};
template <typename T>
Getter<T> make_getter(T&t) { return Getter<T>(t); }
And then
template<class Vector1, class Vector2>
constexpr auto dot_product(Vector1 const& v1_arg, Vector2 const& v2_arg) {
auto v1 = make_getter(v1_arg);
auto v2 = make_getter(v2_arg);
using return_type = decltype(v1(0) + v2(0));
return_type tmp = return_type{};
for (std::size_t i = 0, e = size(v1); i != e; ++i) {
tmp += v1(i) * v2(i);
}
return tmp;
}

Related

Implementing an efficient and convenient constructor for a C++ vector class template

I'm trying to implement a constructor for a C++ vector class template that is both efficient and convenient to use. The latter is, of course, somewhat subjective — I'm aiming at something like Vec2D myVec = Vec2D({1.0, 2.0}).
To start with, I'm thinking about a class template for fixed-length vectors, so no immediate use for std::vector I'd say. With template <typename T, unsigned short n>, two options to store the elements of the vector would be T mElements[n] or std::array<T, n> mElements. I would go with the latter (same storage and some added benefits compared to the former).
Now, on to the constructor (and the question) — what should be its parameter? The following options come to mind:
Using std::array<T, n> initElements would require the use of double curved brackets for initialisation as it is an aggregate, i.e. Vec2D myVec = Vec2D({{1.0, 2.0}}). Omitting the outer curly brackets might still compile, though results in a warning. Additionally, if we were to generalise this to a 2D array, e.g. for a matrix class template, it would require quadruple curved brackets (or triple when omitting the outer pair again, taking a warning for granted). Not so convenient.
Using T initElems[] would require e.g. double dElems[2] = {1.0, 2.0} followed by Vec2D myVec = Vec2D(dElems), it is not possible to directly pass {1.0, 2.0} as argument. Not so convenient.
Using std::initializer_list<T>, which would allow Vec2D myVec{1.0, 2.0}. This also nicely generalises to a 2D array. However, I don't see how one would use this as a constructor when overloading operators, say operator +.
Using std::vector<T>. This allows the use of Vec2D myVec = Vec2D({1.0, 2.0}), nicely generalises to 2D arrays, and is easy to use in overloaded operators. However, it does not seem very efficient.
The (intentionally basic) code below reflects the last option. Are there alternatives which are more efficient, without losing convenience?
template <typename T, unsigned short n>
class Vector {
public:
std::array<T, n> mElements;
// Constructor
Vector(std::vector<T> initElements) {
for (unsigned short k = 0; k < n; k++) {
mElements[k] = initElements[k];
}
}
// Overloaded operator +
Vector operator + (const Vector& rightVector) const {
std::vector<T> sumVec(n);
for (unsigned short k = 0; k < n; k++) {
sumVec[k] = mElements[k] + rightVector.mElements[k];
}
return Vector(sumVec);
}
};
With the usage
using Vec2D = Vector<double, 2>;
Vec2D myVec = Vec2D({1.0, 2.0});
You could also make use of parameter packs, which (combined with some nice polymorphism) can enable you to do stuff like this:
Vector<int, 3> v1{std::vector<int>{1, 2, 3}};
Vector<double, 3> v2 = {5., 6., 7.};
Vector<float, 3> v3 = v1 + v2;
Where Vector is defined as follows:
#include <vector>
#include <array>
#include <algorithm>
#include <cassert>
template <typename T, size_t n>
struct Vector : std::array<T, n>
{
/* Default constructor, needed as recursion endpoint */
Vector() = default;
/* Recursive constructor that takes an arbitrary number of arguments
* Dangerous: only adds the last n arguments */
template <typename... Ts>
Vector(T v, Ts... args) : Vector(args...) { addItem(v); };
/* Vector constructor that takes an arbitrary std::vector v
* Dangerous: only adds the first n items */
template <typename T2>
explicit Vector(const std::vector<T2>& v) : added{std::min(v.size(), n)}
{
assert(v.size() == n);
for (size_t i = 0; i < added; i++)
{
(*this)[i] = (T)v[i];
}
}
/* Copy constructor: takes a Vector of any type, but of the same length */
template <typename T2>
Vector(const std::array<T2, n>& v) : added{n}
{
for (size_t i = 0; i < added; i++)
{
(*this)[i] = (T)v[i];
}
}
/* Example of a polymorphic addition function */
template <typename T2>
Vector<T, n> operator+(const Vector<T2, n>& v)
{
Vector<T, n> vr{*this};
for (size_t i = 0; i < n; i++)
{
vr[i] += (T)v[i];
}
return vr;
}
private:
size_t added{0};
/* Needed for recursive constructor */
void addItem(const T& t)
{
added++;
if (added <= n) { (*this)[n - added] = t; }
else { assert(false); }
}
};
The most convienient way to make this would be to use a deduction guide, changing your given usage example:
using Vec2D = Vector<double, 2>;
Vec2D myVec = Vec2D({1.0, 2.0});
into something much simpler:
Vector<double, 2> myVec = { 1.0, 2.0 };
// or even
// Vector myVec = { 1.0, 2.0 };
Enabling a usage similar to std::array.
Arguably the easiest, and most efficient way to create a statically sized vector that allows this would be to use a non-standard C++ __attriubute__.
Templating the T __attribute__((vector_size(N))), we end up with the following:
using ushort = unsigned short;
template <typename T, ushort N>
using Vector = T __attribute__((
vector_size(sizeof(T) * N) // the number of bytes in a single `T`, multiplied by the number of elements, `N`
));
int main() {
using vector_t = Vector<double const, 2>;
vector_t x = { 1.0, 2.0 };
vector_t y = { 9.0, 3.0 };
vector_t z = x + y;
std::wcout << z[0] << ", " << z[1] << '\n'; // "10, 5\n"
}
Okay, okay, I'm joking, don't do that, let's not touch upon the world of attributes, compiler extensions, and nonportable code.
The simplest way to make it as convenient to use as the underlying std::array, would be to either, create a type deduction guide, inherit from std::array, or to not implement a constructor, the latter two allow the std::array constructor to take effect, as the class has no constructor on its own.
I think, in this case, you might be able to simply inherit from std::array, without pissing off every C++ developer on SO.
Something along the lines of:
#include <iostream>
#include <vector>
#include <array>
using u16 = unsigned short const;
template <typename T, u16 N>
struct Vector : std::array<T, N> {
Vector<T, N> operator + (Vector<T, N> & rightVector) {
decltype(auto) self = *this;
Vector<T, N> sumVec;
for ( ushort i = 0; i < N; ++i ) {
sumVec[i] = self[i] + rightVector[i];
}
return sumVec;
}
Vector operator += (Vector const& rightVector) {
decltype(auto) self = *this;
for ( ushort i = 0; i < N; ++i ) {
self[i] += rightVector[i];
}
return this;
}
Vector operator ++ () {
decltype(auto) self = *this;
for ( T& item : self ) {
++item;
}
return this;
}
Vector operator ++ (int const) {
decltype(auto) self = *this;
Vector temporary = self;
++self;
return temporary;
}
Vector operator - (Vector const& rightVector) const {
decltype(auto) self = *this;
Vector<T, N> sumVec;
for ( ushort i = 0; i < N; ++i ) {
sumVec[i] = self[i] - rightVector[i];
}
return Vector(sumVec);
}
};
int main() {
using vector_t = Vector<double, 2>;
vector_t x = { 1.0, 2.0 };
vector_t y = { 9.0, 3.0 };
vector_t z = x + y; // { 10.0. 4.0 }
std::wcout << z[0] << ", " << z[1] << '\n';
}
Although, you might want to use a few std::enable_ifs or assertions to make sure that you only create Vectors of a numerical type, as that seems to be what you want to use.
This should have the same memory usage as a std::array. It doesn't initialize any extra types, in contrast to your example that had constructed std::vectors everywhere.
Does this fit your intended usage and goals?
You could directly use the parameters to initialise the base class
Untested code.
template <typename... Args>
Vector(Args...&& args) : mEVector(std::forward<Args>(args)...) { };

constexpr vector push_back or how to constexpr all the things

There is a good talk by Jason Turner and Ben Deane from C++Now 2017 called "Constexpr all the things" which also gives a constexpr vector implementation. I was dabbling with the idea myself, for educational purposes. My constexpr vector was pure in the sense that pushing back to it would return a new vector with added element.
During the talk, I saw a push_back implementation tat looks like more or less following:
constexpr void push_back(T const& e) {
if(size_ >= Size)
throw std::range_error("can't use more than Size");
else {
storage_[size_++] = e;
}
}
They were taking the element by value and moving it but, I don't think this is the source of my problems. The thing I want to know is, how this function could be used in a constexpr context? This is not a const member function, it modifies the state. I don think it is possible to do something like
constexpr cv::vector<int> v1;
v1.push_back(42);
And if this is not possible, how could we use this thing in constexpr context and achieve the goal of the task using this vector, namely compile-time JSON parsing?
Here is my version, so that you can see both my new vector returning version and the version from the talk. (Note that performance, perfect forwarding etc. concerns are omitted)
#include <cstdint>
#include <array>
#include <type_traits>
namespace cx {
template <typename T, std::size_t Size = 10>
struct vector {
using iterator = typename std::array<T, Size>::iterator;
using const_iterator = typename std::array<T, Size>::const_iterator;
constexpr vector(std::initializer_list<T> const& l) {
for(auto& t : l) {
if(size_++ < Size)
storage_[size_] = std::move(t);
else
break;
}
}
constexpr vector(vector const& o, T const& t) {
storage_ = o.storage_;
size_ = o.size_;
storage_[size_++] = t;
}
constexpr auto begin() const { return storage_.begin(); }
constexpr auto end() const { return storage_.begin() + size_; }
constexpr auto size() const { return size_; }
constexpr void push_back(T const& e) {
if(size_ >= Size)
throw std::range_error("can't use more than Size");
else {
storage_[size_++] = e;
}
}
std::array<T, Size> storage_{};
std::size_t size_{};
};
}
template <typename T>
constexpr auto make_vector(std::initializer_list<T> const& l) {
return cx::vector<int>{l};
}
template <typename T>
constexpr auto push_back(cx::vector<T> const& o, T const& t) {
return cx::vector<int>{o, t};
}
int main() {
constexpr auto v1 = make_vector({1, 2, 3});
static_assert(v1.size() == 3);
constexpr auto v2 = push_back(v1, 4);
static_assert(v2.size() == 4);
static_assert(std::is_same_v<decltype(v1), decltype(v2)>);
// v1.push_back(4); fails on a constexpr context
}
So, this thing made me realize there is probably something deep that I don' know about constexpr. So, recapping the question; how such a constexpr vector could offer a mutating push_back like that in a constexpr context? Seems like it is not working in a constexpr context right now. If push_back in a constexpr context is not intended to begin with, how can you call it a constexpr vector and use it for compile-time JSON parsing?
Your definition of vector is correct, but you can't modify constexpr objects. They are well and truly constant. Instead, do compile-time calculations inside constexpr functions (the output of which can then be assigned to constexpr objects).
For example, we can write a function range, which produces a vector of numbers from 0 to n. It uses push_back, and we can assign the result to a constexpr vector in main.
constexpr vector<int> range(int n) {
vector<int> v{};
for(int i = 0; i < n; i++) {
v.push_back(i);
}
return v;
}
int main() {
constexpr vector<int> v = range(10);
}
Your return cx::vector<int>{o, t}; will produce a compilation error when o and t are of types cx::vector<T> and T respectively, because those are different types, while all elements of std::initializer_list<T> should be of same type (o is not expanded into a list of its elements).
If you're merely after your 'pure' implementation of push_back, then you can make do with standard arrays:
#include <array>
template <typename T, std::size_t N>
constexpr auto push_back(std::array<T, N> const& oldArr, T const& el) {
std::array<T, N+1> newArr{};
std::copy(begin(oldArr), end(oldArr), begin(newArr));
newArr[N] = el;
return newArr;
}
int main() {
constexpr auto a1 = std::to_array({1, 2, 3});
static_assert(a1.size() == 3);
constexpr auto a2 = push_back(a1, 4);
static_assert(a2.size() == 4);
// This assert will still fail though, because push_back's implementation
// above not only returns new array, but also a new type.
// For example, std::array<int, 3> is not the same type as std::array<int, 4>
//static_assert(std::is_same_v<decltype(a1), decltype(a2)>);
}

generic iterators to access elements of vectors without using Templates c++

I am creating a function which should take as input iterators to vector
for example:
vector<int> a;
foo(a.begin(),a.end())
The vector can hold any type.
Now the simple way to do this is using templates
template <typename Iterator>
void foo(Iterator first, Iterator last) {
for (Iterator it = first; it!=last; ++it) {
cout << *it;
}
}
I want to know if there is a way to achieve the same functionality without using templates. Since using Templates would force me to include these functions in Header file of a public API which I don't want to. So I wanted to know is there an alternate way to access the iterators without using Templates.
There are ways not to include the implementation in header files but they are not clean to implement (for instance you should know in advance the instantiations). Read here for more info about this issue:
Why can’t I separate the definition of my templates class from its declaration and put it inside a .cpp file?
How can I avoid linker errors with my template functions?
For instance in:
foo.h
#ifndef HI_
#define HI_
template<class Iterator>
void foo(Iterator first, Iterator last);
#endif
foo.cpp
#include "stack.h"
using namespace std;
template<class Iterator>
void foo(Iterator first, Iterator last) {
for (Iterator it = first; it != last; ++it) {
cout << *it << " ";
}
}
template
void foo( std::vector<int>::iterator first, std::vector<int>::iterator last);
template
void foo( std::vector<double>::iterator first, std::vector<double>::iterator last);
Now you can use foo function only for double and int. Other types won't link.
Hope this helps.
This is a long answer. The short answer is "type erasure"; go learn about it.
The long answer is two answers. First I cover "do you just want to be able to iterate over contiguous ints?". Then you want span. This is a really simple form of type erasure that forgets what the exact container is you are working on so long as it is contiguous and over T.
The second answer is if you actually need to deal with multiple types (not just int) and multiple kinds of containers (not just contiguous ones).
The two answers are separated by a line.
The span concept (see gsl::span) is designed for pretty much this reason. It itself is a template (over the type you are working with), but it will be a concrete instance of a template in most interfaces.
Here is a toy version of it:
template<class T>
struct span_t {
T* b = 0;
T* e = 0;
T* begin() const { return b; }
T* end() const { return e; }
span_t(span_t const&)=default;
span_t& operator=(span_t const&)=default;
span_t()=default;
span_t( T* s, T* f ):b(s),e(f) {}
span_t( T* s, std::size_t l):span_t(s, s+l){}
template<std::size_t N>
span_t( T(&arr)[N] ):span_t(arr, N) {}
std::size_t size() const { return end()-begin(); }
bool empty() const { return begin()==end(); }
T& front() const { return *begin(); }
T& back() const { return *(std::prev(end()); }
T* data() const { return begin(); }
span_t without_front( std::size_t N=1 ) const {
return {std::next( begin(), (std::min)(N, size()) ), end()};
}
span_t without_back( std::size_t N=1 ) const {
return {begin(), std::prev(end(), (std::min)(N, size()) )};
}
};
we can augment it with conversion operators
namespace details {
template<template<class...>class Z, class, class...Ts>
struct can_apply:std::false_type{};
template<class...>using void_t=void;
template<template<class...>class Z, class...Ts>
struct can_apply<Z, void_t<Z<Ts...>>, Ts...>:std::true_type{};
}
template<template<class...>class Z, class...Ts>
using can_apply = details::can_apply<Z,void,Ts...>;
template<class C>
using dot_data_r = decltype( std::declval<C>().data() );
template<class C>
using dot_size_r = decltype( std::declval<C>().size() );
template<class C>
using can_dot_data = can_apply< dot_data_r, C >;
template<class C>
using can_dot_size = can_apply< dot_size_r, C >;
can_dot_data detects via SFINAE if .data() is valid to do on an object of type C.
Now we add a constructor:
template<class T,
std::enable_if_t<
can_dot_data<T&>{}
&& can_dot_size<T&>{}
&& !std::is_same<std::decay_t<T>, span_t>{}
, int
> =0
>
span_t( T&& t ): span_t( t.data(), t.size() ) {}
which covers std::vector and std::string and std::array.
Your function now looks like:
void foo(span_t<int> s) {
for (auto&& e:s)
std::cout << s;
}
}
with use:
std::vector<int> a;
foo(a);
now, this only works for contiguous containers of a specific type.
Suppose this is not what you want. Maybe you do need to solve this for a myriad of types, and you don't want to expose everything in the header.
Then what you need to do is known as type erasure.
You need to work out what minimal set of operations you need from the provided types. Then you need to write wrappers that "type erase" these operations down to "typeless" operations.
This goes in the header, or in another helper header.
In the interface of the function, or in a header intermediate helper, you take the incoming types and do the type erasure, then pass the type-erased types into the "real" implementation.
An example of type erasure is std::function. It takes almost anything that can be invoked with a fixed signature, and turns it into a single type-erased type. Everything except how to copy, destroy and invoke an instance of the type is "forgotten" or erased.
For your case:
template <typename Iterator>
void foo(Iterator first, Iterator last) {
for (Iterator it = first; it!=last; ++it) {
cout << *it;
}
}
I see two things that need to be erased down to; iteration, and printing.
struct printable_view_t {
void const* data = 0;
void(*print_f)(std::ostream& os, void const*) = 0;
explicit operator bool()const{return data;}
printable_view_t() = default;
printable_view_t(printable_view_t const&) = default;
template<class T,
std::enable_if_t<!std::is_same<T, printable_view_t>{}, int> =0
>
printable_view_t( T const& t ):
data( std::addressof(t) ),
print_f([](std::ostream& os, void const* pv){
auto* pt = static_cast<T const*>(pv);
os << *pt;
})
{}
std::ostream& operator()(std::ostream& os)const {
print_f(os, data);
return os;
}
friend std::ostream& operator<<(std::ostream& os, printable_view_t p) {
return p(os);
}
};
printable_view_t is an example of type-erasing "I can be printed".
void bar( printable_view_t p ) {
std::cout << p;
}
void test_bar() {
bar(7);
bar(3.14);
bar(std::string("hello world"));
}
The next thing we'd have to do is type erase iteration. This is harder, because we want to type erase iteration over iterating over a printable_view_t type.
Type erasing foreach is a tad easier, and often more efficient.
template<class View>
struct foreach_view_t {
void* data = 0;
void(*func)( std::function<void(View)>, void* ) = 0;
explicit operator bool()const{return data;}
foreach_view_t() = default;
foreach_view_t(foreach_view_t const&) = default;
template<class T,
std::enable_if_t<!std::is_same<std::decay_t<T>, foreach_view_t>{}, int> =0
>
foreach_view_t( T&& t ):
data( const_cast<std::decay_t<T>*>(std::addressof(t)) ),
func([](std::function<void(View)> f, void* pv){
auto* pt = static_cast<std::remove_reference_t<T>*>(pv);
for (auto&& e : *pt)
f(decltype(e)(e));
})
{}
void operator()(std::function<void(View)> f)const{
func(f, data);
}
};
we then daisy chain these together
void foo(foreach_view_t<printable_view_t> x) {
x([](auto p){ std::cout << p; });
}
test code:
std::vector<int> a{1,2,3};
foo(a);
Now much of the header code was "hoisted" into the type erasure types instead of a function template body. But careful choice of the points of type erasure can let you keep what you need from the types precise and narrow, and the logic of how you use those operations private.
As an example, the above code doesn't care where you are printing it to; std::cout was not part of the type erasure.
Live example.
I want to know if there is a way to achieve the same functionality without using templates. [...] I wanted to know is there an alternate way to access the iterators without using Templates.
Yes, if you use C++14, but...
Since using Templates would force me to include these functions in Header file of a public API which I don't want to.
... isn't a useful way for you because it's equivalent to use templates and you have to put it in the header file.
In C++14 you can use a lambda function with auto parameters.
auto foo = [](auto first, auto last)
{ for (auto it = first ; it != last; ++it ) std::cout << *it; };
The autos aren't template (from a formal point of view) but are equivalent and you can't declare foo in the header and develop it in a cpp file.

c++ overloading operator[] for std::pair

I work a lot with pairs of values: std::pair<int, int> my_pair. Sometimes I need to perform the same operation on both my_pair.first and my_pair.second.
My code would be much smoother if I could do my_pair[j] and loop over j=0,1.
(I am avoiding using arrays because I don't want to bother with allocating memory, and I use pair extensively with other things).
Thus, I would like to define operator[] for std::pair<int, int>.
And I can't get it to work, (I'm not very good with templates and such)...
#include <utility>
#include <stdlib.h>
template <class T1> T1& std::pair<T1, T1>::operator[](const uint &indx) const
{
if (indx == 0)
return first;
else
return second;
};
int main()
{
// ....
return 0;
}
fails to compile. Other variations fail as well.
As far as I can tell, I am following the Stack Overflow operator overloading FAQ, but I guess I am missing something...
you cannot overload operator[] as a non-member
you cannot define a member function which has not been declared in the class definition
you cannot modify the class definition of std::pair
Here's a non-member implementation:
/// #return the nth element in the pair. n must be 0 or 1.
template <class T>
const T& pair_at(const std::pair<T, T>& p, unsigned int n)
{
assert(n == 0 || n == 1 && "Pair index must be 0 or 1!");
return n == 0 ? p.first: p.second;
}
/// #return the nth element in the pair. n must be 0 or 1.
template <class T>
T& pair_at(std::pair<T, T>& p, unsigned int index)
{
assert(index == 0 || index == 1 && "Pair index must be 0 or 1!");
return index == 0 ? p.first: p.second;
}
// usage:
pair<int, int> my_pair(1, 2);
for (int j=0; j < 2; ++j)
++pair_at(my_pair, j);
Note that we need two versions: one for read-only pairs and one for mutable pairs.
Don't be afraid to use non-member functions liberally. As Stroustrup himself said, there is no need to model everything with an object or augment everything through inheritance. If you do want to use classes, prefer composition to inheritance.
You can also do something like this:
/// Applies func to p.first and p.second.
template <class T, class Func>
void for_each_pair(const std::pair<T, T>& p, Func func)
{
func(p.first);
func(p.second);
}
/// Applies func to p.first and p.second.
template <class T, class Func>
void for_each_pair(std::pair<T, T>& p, Func func)
{
func(p.first);
func(p.second);
}
// usage:
pair<int, int> my_pair(1, 2);
for_each_pair(my_pair, [&](int& x){
++x;
});
That isn't too unwieldy to use if you have C++11 lambdas and is at least a bit safer since it has no potential to access out of bounds.
You cannot add functions to an existing class like this. And you certainly can't do it to things in the std namespace.
So you should define your own wrapper class:
class MyPair {
private:
std::pair<int,int> p;
public:
int &operator[](int i) { return (i == 0) ? p[0] : p[1]; }
// etc.
};
You probably should check out Boost.Fusion. You can apply algorithms to sequences(which std::pair is considered a sequence). So for example you can do for_each like this:
std::pair<int, int> my_pair;
for_each(my_pair, [] (int i)
{
cout << i;
});
You can also access the index of the element like this:
int sum = at_c<0>(my_pair) + at_c<1>(my_pair);

C++: select argmax over vector of classes w.r.t. arbitrary expression

I have trouble describing my problem so I'll give an example:
I have a class description that has a couple of variables in it, for example:
class A{
float a, b, c, d;
}
Now, I maintain a vector<A> that contains many of these classes. What I need to do very very often is to find the object inside this vector that satisfies that one of it's parameters is maximal w.r.t to the others. i.e code looks something like:
int maxi=-1;
float maxa=-1000;
for(int i=0;i<vec.size();i++){
res= vec[i].a;
if(res > maxa) {
maxa= res;
maxi=i;
}
}
return vec[maxi];
However, sometimes I need to find class with maximal a, sometimes with maximal b, sometimes the class with maximal 0.8*a + 0.2*b, sometimes I want a maximal a*VAR + b, where VAR is some variable that is assigned in front, etc. In other words, I need to evaluate an expression for every class, and take the max. I find myself copy-pasting this everywhere, and only changing the single line that defines res.
Is there some nice way to avoid this insanity in C++? What's the neatest way to handle this?
Thank you!
I know this thread is old, but i find it quite useful to implement a powerful argmax function in C++.
However, as far as i can see, all the given examples above rely on std::max_element, which does comparison between the elements (either using a functor or by calling the operator<). this can be slow, if the calculation for each element is expensive. It works well for sorting numbers and handling simple classes, but what if the functor is much more complex? Maybe calculating a heuristic value of a chess position or something else that generate a huge tree etc.
A real argmax, as the thread starter mentioned, would only calculate its arg once, then save it to be compared with the others.
EDIT: Ok i got annoyed and had too much free time, so i created one < C++11 and one C++11 version with r-value references, first the C++11 version:
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>
template<typename IteratorT, typename HeuristicFunctorT>
IteratorT argmax(IteratorT && it, const IteratorT & end, const HeuristicFunctorT & functor) {
IteratorT best(it++);
typename HeuristicFunctorT::result_type best_value(functor(*best));
for(; it != end; ++it) {
typename HeuristicFunctorT::result_type value(functor(*it));
if (value > best_value) {
best_value = value;
best = it;
}
}
return best;
}
template<typename IteratorT, typename HeuristicFunctorT>
inline IteratorT argmax(const IteratorT & begin, const IteratorT & end, const HeuristicFunctorT & functor) {
return argmax(IteratorT(begin), end, functor);
}
class IntPairFunctor : public std::unary_function< std::pair<int, int>, int > {
public:
int operator() (const std::pair<int, int> & v) const {
return v.first + v.second;
}
};
std::pair<int, int> rand_pair() {
return std::make_pair(rand(), rand());
}
int main(int argc, const char **argv) {
srand(time(NULL));
std::vector< std::pair<int, int> > ints;
std::generate_n(std::back_insert_iterator< std::vector< std::pair<int, int> > >(ints), 1000, rand_pair);
std::vector< std::pair<int, int> >::iterator m (argmax(ints.begin(), ints.end(), IntPairFunctor()));
std::cout << std::endl << "argmax: " << *m << std::endl;
}
The non C++11 version is much simpler, only the template:
template<typename IteratorT, typename HeuristicFunctorT>
IteratorT argmax(IteratorT it, const IteratorT & end, const HeuristicFunctorT & functor) {
IteratorT best(it++);
typename HeuristicFunctorT::result_type best_value(functor(*best));
for(; it != end; ++it) {
typename HeuristicFunctorT::result_type value(functor(*it));
if (value > best_value) {
best_value = value;
best = it;
}
}
return best;
}
Note that neither version requires any template arguments, the only requirement is that the heuristic implements the unary_function class
template <typename F>
struct CompareBy
{
bool operator()(const typename F::argument_type& x,
const typename F::argument_type& y)
{ return f(x) < f(y); }
CompareBy(const F& f) : f(f) {}
private:
F f;
};
template <typename T, typename U>
struct Member : std::unary_function<U, T>
{
Member(T U::*ptr) : ptr(ptr) {}
const T& operator()(const U& x) { return x.*ptr; }
private:
T U::*ptr;
};
template <typename F>
CompareBy<F> by(const F& f) { return CompareBy<F>(f); }
template <typename T, typename U>
Member<T, U> mem_ptr(T U::*ptr) { return Member<T, U>(ptr); }
You need to include <functional> for this to work. Now use, from header <algorithm>
std::max_element(v.begin(), v.end(), by(mem_ptr(&A::a)));
or
double combination(A x) { return 0.2 * x.a + 0.8 * x.b; }
and
std::max_element(v.begin(), v.end(), by(std::fun_ptr(combination)));
or even
struct combination : std::unary_function<A, double>
{
combination(double x, double y) : x(x), y(y) {}
double operator()(const A& u) { return x * u.a + y * u.b; }
private:
double x, y;
};
with
std::max_element(v.begin(), v.end(), by(combination(0.2, 0.8)));
to compare by a member or by linear combinations of a and b members. I split the comparer in two because the mem_ptr thing is damn useful and worth being reused. The return value of std::max_element is an iterator to the maximum value. You can dereference it to get the max element, or you can use std::distance(v.begin(), i) to find the corresponding index (include <iterator> first).
See http://codepad.org/XQTx0vql for the complete code.
This is what functors and STL are made for:
// A class whose objects perform custom comparisons
class my_comparator
{
public:
explicit my_comparator(float c1, float c2) : c1(c1), c2(c2) {}
// std::max_element calls this on pairs of elements
bool operator() (const A &x, const A &y) const
{
return (x.a*c1 + x.b*c2) < (y.a*c1 + y.b*c2);
}
private:
const float c1, c2;
};
// Returns the "max" element in vec
*std::max_element(vec.begin(), vec.end(), my_comparator(0.8,0.2));
Is the expression always linear? You could pass in an array of four coefficients. If you need to support arbitrary expressions, you'll need a functor, but if it's just an affine combination of the four fields then there's no need for all that complexity.
You can use the std::max_element algorithm with a custom comparator.
It's easy to write the comparator if your compiler supports lambda expressions.
If it doesn't, you can write a custom comparator functor. For the simple case of just comparing a single member, you can write a generic "member comparator" function object, which would look something like this:
template <typename MemberPointer>
struct member_comparator
{
MemberPointer p_;
member_comparator(MemberPointer p) : p_(p) { }
template <typename T>
bool operator()(const T& lhs, const T& rhs) const
{
return lhs.*p_ < rhs.*p_;
}
};
template <typename MemberPointer>
member_comparator<MemberPointer> make_member_comparator(MemberPointer p)
{
return member_comparator<MemberPointer>(p);
}
used as:
// returns an iterator to the element that has the maximum 'd' member:
std::max_element(v.begin(), v.end(), make_member_comparator(&A::d));
You could use the std::max_element STL algorithm providing a custom comparison predicate each time.
With C++0x you can even use a lambda function for it for maximum conciseness:
auto maxElement=*std::max_element(vector.begin(), vector.end(), [](const A& Left, const A& Right) {
return (0.8*Left.a + 0.2*Left.b)<(0.8*Right.a + 0.2*Right.b);
});
Sample of using max_element/min_element with custom functor
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
struct A{
float a, b, c, d;
};
struct CompareA {
bool operator()(A const & Left, A const & Right) const {
return Left.a < Right.a;
}
};
int main() {
vector<A> vec;
vec.resize(3);
vec[0].a = 1;
vec[1].a = 2;
vec[2].a = 1.5;
vector<A>::iterator it = std::max_element(vec.begin(), vec.end(), CompareA());
cout << "Largest A: " << it->a << endl;
it = std::min_element(vec.begin(), vec.end(), CompareA());
cout << "Smallest A: " << it->a << endl;
}