From David Abrahams and Aleksey Gurtovoy's book "C++ Template Metaprogramming", I learned that iter_swap
(see below) would be much slower than std::swap
sometimes. Although the book has some explanation, I did not quite get it, could someone explains the reason behind it with more details.
template <typename ForwardIt1>
void iter_swap(ForwardIt1 it1, ForwardIt1 it2){
typedef typename std::iterator_traits<ForwardIt1>::value_type T;
T tmp = *it1;
*it1 = *it2;
*it2 = tmp;
}
template <typename ForwardIt1>
void swap_wrapper(ForwardIt1 it1, ForwardIt1 it2){
std::swap(*it1, *it2);
}
By applying them on std::list<std::vector<std::string>>::iterator
, I found the first is 10X slower than the second even when the size of the vector (whose elements are all small strings, length less than 10) is just 10.