泛型算法(十二)之交换算法

1、iter_swap(ForwardIterator1 a, ForwardIterator2 b):交换两个迭代器所指的元素对象

    std::vector<int> c;
    //向c中添加元素
    for (int i = 0; i < 10; i++)
    {
        c.push_back(i);
    }
    //交换c中首尾元素
    std::iter_swap(c.begin(), c.end() - 1);

    for (auto var : c)
    {
        std::cout << var<<",";
    }
    //打印结果:9,1,2,3,4,5,6,7,8,0,

2、swap_ranges(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2):交换两个序列中对应的元素

    std::vector<int> c1;
    std::vector<int> c2;
    //向c1,c2中添加元素
    for (int i = 0; i < 10; i++)
    {
        c1.push_back(i);
        c2.push_back(i * 100);
    }
    //交换c1,c2中对应元素
    std::swap_ranges(c1.begin(), c1.end(), c2.begin());
    //输出c1
    for (auto var : c1)
    {
        std::cout << var<<",";
    }
    //打印结果:0,100,200,300,400,500,600,700,800,900,

3、swap(T& a, T& b):交换两个对象。优先使用移动语义

class Test
{
public:
    Test(int x)
    {
        a = x;
    }

    void print()
    {
        std::cout << a << ",";
    }

private:
    int a;
};
int _tmain(int argc, _TCHAR* argv[])
{

    Test test1(1);
    Test test2(2);

    std::swap(test1, test2);

    test1.print();    //打印结果:2
    test2.print();    //打印结果:1
}

4、swap(T (&a)[N], T (&b)[N]):交换两个对象数组

class Test
{
public:
    Test(){ a = 0; }

    Test(int x)
    {
        a = x;
    }

    void print()
    {
        std::cout << a << ",";
    }

private:
    int a;
};
int _tmain(int argc, _TCHAR* argv[])
{
    Test a[32];
    Test b[32];

    Test test1(1);
    a[0] = test1;

    Test test2(2);
    b[0] = test2;

    std::swap(a, b);

    a[0].print();    //打印结果:2
    b[0].print();    //打印结果:1
}

 

posted on 2016-01-19 16:42  dongtshj  阅读(579)  评论(0编辑  收藏  举报