Use std :: swap between vectors or vector :: swap?

For two std :: vector v1, v2.
I was wondering what are the advantages of using std :: swap (v1, v2) compared to v1.swap (v2).

I applied a simple test code (I'm not sure if this is appropriate) regarding the performance point of view:

#include <iostream>
#include <vector>
#include <random>
#include <chrono>
#include <algorithm>

#define N 100000

template<typename TimeT = std::chrono::microseconds>
struct Timer
{
    template<typename F, typename ...Args>
    static typename TimeT::rep exec(F func, Args&&... args)
    {
        auto start = std::chrono::steady_clock::now();
        func(std::forward<Args>(args)...);
        auto duration = std::chrono::duration_cast<TimeT>(std::chrono::steady_clock::now() - start);
        return duration.count();
    }
};

void test_std_swap(std::vector<double>& v1, std::vector<double>& v2)
{
    for (int i = 0; i < N; i ++)
    {
        std::swap(v1,v2);
        std::swap(v2,v1);
    }
}

void test_swap_vector(std::vector<double>& v1, std::vector<double>& v2)
{
    for (int i = 0; i < N; i ++)
    {
        v1.swap(v2);
        v2.swap(v1);
    }
}

int main()
{
    std::vector<double> A(1000);
    std::generate( A.begin(), A.end(), [&]() { return std::rand(); } );
    std::vector<double> B(1000);
    std::generate( B.begin(), B.end(), [&]() { return std::rand(); } );
    std::cout << Timer<>::exec<void(std::vector<double>& v1, std::vector<double>& v2)>(test_std_swap, A, B) << std::endl;
    std::cout << Timer<>::exec<void(std::vector<double>& v1, std::vector<double>& v2)>(test_swap_vector, A, B)  << std::endl;
    std::cout << Timer<>::exec<void(std::vector<double>& v1, std::vector<double>& v2)>(test_std_swap, A, B) << std::endl;
    std::cout << Timer<>::exec<void(std::vector<double>& v1, std::vector<double>& v2)>(test_swap_vector, A, B)  << std::endl;
}

According to the findings, it seems that vector :: swap looks faster without -O0 optimization. Output (in microseconds):

20292
16246
16400
13898

And with -O3 there is no difference in revelant.

752
752
752
760
+4
source share
2 answers

You must not use std::swap()directly in any way! Instead, you should use something like this:

using std::swap;
swap(x, y);

std::vector<...>, , , std::vector<...>, , std. , std::swap() , , ADL, .

swap(x, y) std::vector<...> x y, x.swap(y). .

+7

, . , .

, std::swap(vector<T> & x, vector<T> & y), x.swap(y).

+8

Source: https://habr.com/ru/post/1569311/


All Articles