Flattening iterator

I don’t know of any implementation in a major library, but it looked like an interesting problem so I wrote a basic implementation. I’ve only tested it with the test case I present here, so I don’t recommend using it without further testing. The problem is a bit trickier than it looks because some of … Read more

Sorting std::map using value

Even though correct answers have already been posted, I thought I’d add a demo of how you can do this cleanly: template<typename A, typename B> std::pair<B,A> flip_pair(const std::pair<A,B> &p) { return std::pair<B,A>(p.second, p.first); } template<typename A, typename B> std::multimap<B,A> flip_map(const std::map<A,B> &src) { std::multimap<B,A> dst; std::transform(src.begin(), src.end(), std::inserter(dst, dst.begin()), flip_pair<A,B>); return dst; } int main(void) … Read more

printf with std::string?

It’s compiling because printf isn’t type safe, since it uses variable arguments in the C sense1. printf has no option for std::string, only a C-style string. Using something else in place of what it expects definitely won’t give you the results you want. It’s actually undefined behaviour, so anything at all could happen. The easiest … Read more

Sorting zipped (locked) containers in C++ using boost or the STL

Here’s a working example based on the range-v3 Library that has been proposed for Standardization #include <range/v3/all.hpp> #include <iostream> using namespace ranges; int main() { std::vector<int> a1{15, 7, 3, 5}; std::vector<int> a2{ 1, 2, 6, 21}; sort(view::zip(a1, a2), std::less<>{}, &std::pair<int, int>::first); std::cout << view::all(a1) << ‘\n’; std::cout << view::all(a2) << ‘\n’; } Live Example (requires … Read more

How to create an std::function from a move-capturing lambda expression?

template<class F> function(F f); template <class F, class A> function(allocator_arg_t, const A& a, F f); Requires: F shall be CopyConstructible. f shall be Callable for argument types ArgTypes and return type R. The copy constructor and destructor of A shall not throw exceptions. ยง20.9.11.2.1 [func.wrap.func.con] Note that operator = is defined in terms of this … Read more