I am trying to find template functions that do:
template <typename T>
T add(T lhs, T rhs) {
return lhs + rhs;
}
(for add, subtract, multiply, and divide).
I remember there being a standard set of functions for this-- do you remember what they are?
In the header <functional>, you'll find things like std::plus, std::minus, std::multiplies, and std::divides.
They're not functions, either. They're actually functors.
You need functors such as std::plus from the <functional> header. See Arithmetic operations here.
These are functors, not functions, so you need an instance to do anything useful:
#include <functional>
#include <iostream>
int main() {
std::multiplies<int> m;
std::cout << m(5,3) << "\n";
}
This seems like overkill in the above sample, but they are pretty useful with standard library algorithms. For example, find the product of elements in a vector:
std::vector<int> v{1,2,3,4,5,6};
int prod = std::accumulate(v.begin(), v.end(), 1, std::multiplies<int>());
Related
I was wondering if it is possible to apply boost's automatic differentiation library:
#include <boost/math/differentiation/autodiff.hpp>
to functions which return std::complex<double> values?
For instance, consider the multivariate complex valued function:
#include <complex>
std::complex<double> complex_function(double a, double c){
// Assuming a < 0
return exp(sqrt(std::complex(a, 0.0))) + sin(c);
}
How can I take the derivative wrt to a or c using Boost's autodiff? Is that even possible?
is [it] possible to apply boost's automatic differentiation library to functions which return std::complex<double> values?
Not at the present time.
A version that did might look something like this:
// THIS DOES NOT COMPILE - FOR DISCUSSION ONLY
#include <boost/math/differentiation/autodiff.hpp>
#include <iostream>
#include <complex>
namespace ad = boost::math::differentiation;
template <typename T0, typename T1>
auto complex_function(T0 a, T1 c){
// Assuming a < 0
return exp(sqrt(complex(a, 0.0))) + sin(c); // DOES NOT COMPILE
}
int main() {
auto const a = ad::make_fvar<double, 2>(-3);
auto const c = 0.0;
auto const answer = complex_function(a, c);
return 0;
}
This requires complex to be defined specific to autodiff::fvar template types, similar to how other mathematical functions (exp, sqrt, etc.) have overloads in the autodiff library, and are called via ADL.
As #user14717 pointed out in the comments, it is a special case of vector-valued autodiff since the return value isn't a single truncated Taylor polynomial, but rather a tuple of them.
I was curious about why this piece of code doesn't work:
#include "stdafx.h"
#include <iostream>
#include <tuple>
#include <string>
#include <vector>
#include <algorithm>
typedef std::tuple<int, std::string> intString;
bool operator<(intString& lhs, intString& rhs){
return std::tie(std::get<1>(lhs), std::get<0>(lhs)) < std::tie(std::get<1>(rhs), std::get<0>(rhs));
}
void printIntStrings(std::vector<intString>& v){
for (intString& i : v){
std::cout << std::get<0>(i) << " is " << std::get<1>(i) << std::endl;
}
}
int main(int argc, char* argv[])
{
std::vector<intString> v;
v.push_back(std::make_tuple(5, "five"));
v.push_back(std::make_tuple(2, "two"));
v.push_back(std::make_tuple(9, "nine"));
printIntStrings(v);
std::sort(v.begin(), v.end());
printIntStrings(v);
return 0;
}
As far as I can understand, I simply create a vector of intStrings and my operator should sort by the second element in the tuple first thus the output should be (last 3 lines anyway)
5 five
9 nine
2 two
However running it on my machine I get
2 two
5 five
9 nine
which implies that the sort is using the default less than operator, ignoring the one I specified. Note, adding const before the parameters didn't seem to affect anything.
I found three ways to "fix" this.
Fix #1
surround bool operator< ... in namespace std like so:
namespace std{
bool operator<(intString& lhs, intString& rhs){
return std::tie(std::get<1>(lhs), std::get<0>(lhs)) < std::tie(std::get<1>(rhs), std::get<0>(rhs));
}
}
However I was told we should never add things to the std namespace since that behavior is undefined, so this fix seems the worst.
Fix #2
Add in something custom to the tuple like so:
enum class TRASH{DOESNTMATTER};
typedef std::tuple<int, std::string, TRASH> intString;
bool operator<(intString& lhs, intString& rhs){
return std::tie(std::get<1>(lhs), std::get<0>(lhs)) < std::tie(std::get<1>(rhs), std::get<0>(rhs));
}
(and obviously add in TRASH::DOESNTMATTER as the third make_tuple argument)
However, this seemed like a lot of work for something this simple. Also, it seems wasteful since the enum is not meaningfully used.
Fix #3
Use the predicate sort like so:
std::sort(v.begin(), v.end(), operator<);
This seemed to be the most elegant solution. However, I don't see why I have to explicitly tell the compiler to use my defined operator<.
So I want to know:
1) why this happens? Shouldn't c++ find my implementation and use that?
2) which "fix" is the best? if none of the ones I found, what would you recommend?
Any ideas? Thanks for reading!
Your operator< overload is not visible at the point where < is used (which is in the body of std::sort and/or any helper functions called by it, somewhere in <algorithm>).
If it is to be used, it must be picked up by argument-dependent lookup; but there's nothing in std::tuple<int, std::string> that has the global namespace as an associated namespace, so ADL doesn't help you, either, and the standard one is used.
Pass it as a comparator, preferably using a lambda or function object (which inlines better than function pointers), is the simplest fix. I'd also recommend renaming it; having a operator< overload with completely different semantics than the standard one, which may or may not be used by the expression a < b depending on where that expression is, is not a good idea.
you already fix it by your self
the problem is your operator< function doesn't override the default tuple::operator<, they are in different namespace
so, both your Fix#1 and Fix#3 are good solution
Fix#1 put them into the same namespace make it override correct,I think is the best way
From time to time I am feeling the need for a certain kind of iterator (for which I can't make up a good name except the one prefixed to the title of this question).
Suppose we have a function (or function object) that maps an integer to type T. That is, we have a definition of a mathematical sequence, but we don't actually have it stored in memory. I want to make an iterator out of it. The iterator class would look something like this:
template <class F, class T>
class sequence_iterator : public std::iterator<...>
{
int i;
F f;
public:
sequence_iterator (F f, int i = 0):f(f), i(i){}
//operators ==, ++, +, -, etc. will compare, increment, etc. the value of i.
T operator*() const
{
return f(i);
}
};
template <class T, class F>
sequence_iterator<F, T> make_sequence_iterator(F f, int i)
{
return sequence_iterator<F, T>(f, i);
}
Maybe I am being naive, but I personally feel that this iterator would be very useful. For example, suppose I have a function that checks whether a number is prime or not. And I want to count the number of primes in the interval [a,b]. I'd do this;
int identity(int i)
{
return i;
}
count_if(make_sequence_iterator<int>(identity, a), make_sequence_iterator<int>(identity, b), isPrime);
Since I have discovered something that would be useful (at least IMHO) I am definitely positive that it exists in boost or the standard library. I just can't find it. So, is there anything like this in boost?. In the very unlikely event that there actually isn't, then I am going to write one - and in this case I'd like to know your opinion whether or not should I make the iterator_category random_access_iterator_tag. My concern is that this isn't a real RAI, because operator* doesn't return a reference.
Thanks in advance for any help.
boost::counting_iterator and boost::transform_iterator should do the trick:
template <typename I, typename F>
boost::transform_iterator<
F,
boost::counting_iterator<I>>
make_sequence_iterator(I i, F f)
{
return boost::make_transform_iterator(
boost::counting_iterator<I>(i), f);
}
Usage:
std::copy(make_sequence_iterator(0, f), make_sequence_iterator(n, f), out);
I would call this an integer mapping iterator, since it maps a function over a subsequence of the integers. And no, I've never encountered this in Boost or in the STL. I'm not sure why that is, since your idea is very similar to the concept of stream iterators, which also generate elements by calling functions.
Whether you want random access iteration is up to you. I'd try building a forward or bidirectional iterator first, since (e.g.) repeated binary searches over a sequence of integers may be faster if they're generated and stored in one go.
Does the boost::transform_iterator fills your needs? there are several useful iterator adaptors in boost, the doc is here.
I think boost::counting_iterator is what you are looking for, or atleast comes the closest. Is there something you are looking for it doesn't provide? One could do, for example:
std::count_if(boost::counting_iterator<int>(0),
boost::counting_iterator<int>(10),
is_prime); // or whatever ...
In short, it is an iterator over a lazy sequence of consecutive values.
Boost.Utility contains a generator iterator adaptor. An example from the documentation:
#include <iostream>
#include <boost/generator_iterator.hpp>
class my_generator
{
public:
typedef int result_type;
my_generator() : state(0) { }
int operator()() { return ++state; }
private:
int state;
};
int main()
{
my_generator gen;
boost::generator_iterator_generator<my_generator>::type it =
boost::make_generator_iterator(gen);
for (int i = 0; i < 10; ++i, ++it)
std::cout << *it << std::endl;
}
Suppose i want something simple like the following:
I have an core-algorithm, which randomly selects one of the specialized algorithms (specialized at compile-time) and process this algorithm. These specialized algorithms are implemented trough functors.
The question is now: how to implement a container, which is build at compile-time, where the core-algorithm can first check the size of this container ("i got 4 algorithms -> need to randomly select algorithm 0-3") and can then execute the functor in this container ("randomly chosen 2 -> process the third functor in container").
How would one implement it as simple as possible? I suppose it is possible.
Is there any connection to the curiously recurring template idiom? (wiki link)
Is there a simple way with the use of Boost::Fusion? (official doc)
Edit: All the algorithms will be used in the core-algorithm. The use pattern (random-numbers) is a runtime-decision (so i don't need compile-time-rands). The algorithm just has to know the container of functors and the size of this container for safe access.
If you want your core-algorithm to execute a specialized algorithm, there should be some kind of contract between the core-algorithm and the specialized algorithm.
If you define this contract as an interface, your container is simply a container containing pointers to these interfaces, e.g.:
class IAlgorithm
{
public:
virtual double operator()(double d) = 0;
};
typedef std::vector<IAlgorithm *> Algorithms;
Calling a random algorithm is then simply taking the size of the vector, taking a random value between zero and the size of the list (0..size-1), taking the entry at that position and calling the interface.
Alternatively, you can also use the new C++0x std::function construction, like this:
#include <functional>
typedef std::function<double(double)> Algorithm;
typedef std::vector<Algorithm> Algorithms;
Taking an algorithm is similar, you should be able to call an algorithm like this:
Algorithms myAlgorithms;
...
double myresult = myAlgorithms[2](mydouble);
This approach has the advantage that you can also use lambda's.
EDIT: This is an example that uses lambda's. It compiles and works as expected with Visual Studio 2010 (just tested this myself):
#include <iostream>
#include <vector>
#include <functional>
typedef std::function<double(double)> Algorithm;
typedef std::vector<Algorithm> Algorithms;
int main()
{
Algorithms algorithms;
algorithms.push_back([](double d)->double{return d+d;});
algorithms.push_back([](double d)->double{return d*d;});
std::cout << algorithms[0](5) << std::endl;
std::cout << algorithms[1](5) << std::endl;
}
I'm not a specialist but I think that indeed boost::fusion and/or boost::mpl are the tools you're looking for.
Your class would take an mpl container as parameter, being the list of algorithms functor types, and then would work with it at compile time.
I think an interesting subproblem is how to generate random numbers at compile-time.
Perhaps something like this :)
//compiletime_rand.h
#ifndef COMPILETIME_RAND_GENERATOR_H
#define COMPILETIME_RAND_GENERATOR_H
template <unsigned N, unsigned Seed, unsigned Modulo>
struct rand_c_impl
{
static const unsigned value_impl = (1664525 * rand_c_impl<N - 1, Seed, Modulo>::value + 1013904223) % (1ull << 32);
static const unsigned value = value_impl % Modulo;
};
template <unsigned Seed, unsigned Modulo>
struct rand_c_impl<0, Seed, Modulo>
{
static const unsigned value_impl = Seed;
static const unsigned value = value_impl;
};
#endif
//next_c_rand.h
#include BOOST_PP_UPDATE_COUNTER()
rand_c_impl<BOOST_PP_COUNTER, 0, MAX_C_RAND>::value
//main.cpp
#include <boost/preprocessor/slot/counter.hpp>
#include "compiletime_rand.h"
#include <iostream>
#define MAX_C_RAND 16
template <unsigned N>
void output_compiletime_value()
{
std::cout << N << '\n';
}
int main()
{
output_compiletime_value<
#include "next_c_rand.h"
>();
output_compiletime_value<
#include "next_c_rand.h"
>();
}
Output: 15 2
I'm writing a class which will be used to perform some calculations on a set of values, with scaling based on a per-value weight. The values and weights are supplied to the class' constructor. The class will be part of an internal library, and so I want to put as few restrictions as possible on the clients data structures - some clients will use vectors of structs or std::pairs, another separate OpenCV matrixes. During development I've taken start/end iterators and relied on the pair mechanism (val = it->first, weight = it->second).
How could this be done better, without too much hassle for the programmer on the other end? Generally, what is considered best practise when having this sort of multi-dimensional input?
Iterators are fine. However, relying on the types having public members called first and second is a pretty big restriction.
In C++0x, access to std::pair members will be unified with the access patterns of std::tuple, via a get function. This would allow you to overload and specialize the get function for arbitrary types:
#include <iostream>
#include <utility>
template <class T>
void print(const T& data)
{
using std::get;
std::cout << get<0>(data) << ' ' << get<1>(data) << '\n';
}
struct Coord
{
int x, y;
};
template <unsigned>
int get(const Coord&);
template <>
int get<0>(const Coord& c) { return c.x; }
template <>
int get<1>(const Coord& c) { return c.y; }
int main()
{
print(std::make_pair(1, 2));
Coord coord = {4, 5};
print(coord);
}
In case your standard library doesn't have get for pair, then boost's tuple library seems to have it.
That situation is pretty much what templates are in the language for.