Algorithm-修改序列操作(一)

Algorithm-Modifying sequence operations

std::copy

template <class InputIterator, class OutputIterator>
OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result);

功能:

​ 将[first,last)的元素复制到result开始的地方,两个范围不应该重复,可以是同一个容器,也可以是不同的容器。

返回值:

​ 返回指向目标范围末尾的iterator,在该范围内复制了元素。

该模板函数的行为等价于:

template<class InputIterator, class OutputIterator>
  OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result)
{
  while (first!=last) {
    *result = *first;
    ++result; ++first;
  }
  return result;
}

测试代码:

void test_copy()
{
    std::array<string, 3>foo{ "I", "love", "you" };
    std::array<string, 3>Jack;
    std::copy(foo.begin(), foo.end(), Jack.begin());
    if (!Jack.empty())
        std::for_each(Jack.begin(), Jack.end(), [](string val) {cout << val << " "; });
    cout << endl;
}

std::copy_n

template <class InputIterator, class Size, class OutputIterator>
  OutputIterator copy_n (InputIterator first, Size n, OutputIterator result);

功能:

​ 从范围first开始的n个元素复制到范围result开始的地方。如果n是一个负数,则该函数什么也不做。

返回值:

​ 如果成功,该函数返回一个指向目标范围末尾的iterator,该iterator指向复制的最后一个元素的下一个位置。

  • 最好不要让两个范围有所重叠,否则可能会出现一些具有未定义但有效的值。

该模板函数的行为等价于:

template<class InputIterator, class Size, class OutputIterator>
  OutputIterator copy_n (InputIterator first, Size n, OutputIterator result)
{
  while (n>0) {
      //逐个复制
    *result = *first;
    ++result; ++first;
    --n;
  }
  return result;
}

测试代码:

void test_copy_n()
{
    std::array<char, 11>foo{ 'h','e','l','l','o',' '};
    std::array<char, 5>jack{ 'w','o','r','l','d' };
    std::copy_n(jack.begin(), 5, foo.begin() + 6);
    std::for_each(foo.begin(), foo.end(), [](char val) {cout << val; });
    cout << endl;
}

std::copy_if

template <class InputIterator, class OutputIterator, class UnaryPredicate>	//一元谓词
  OutputIterator copy_if (InputIterator first, InputIterator last, OutputIterator result, UnaryPredicate pred);

功能:

​ 将[first,last)中满足条件pred的所有元素copy到以result开始的范围里。

返回值:

​ 指向结果序列中最后一个元素后的元素的iterator。

该模板函数的行为等价于:

template <class InputIterator, class OutputIterator, class UnaryPredicate>
  OutputIterator copy_if (InputIterator first, InputIterator last,
                          OutputIterator result, UnaryPredicate pred)
{
  while (first!=last) {
    if (pred(*first)) {	//满足条件时,copy
      *result = *first;
      ++result;
    }
    ++first;	//不满足条件则只对迭代器first后移
  }
  return result;
}

测试代码:

void test_copy_if()
{
    std::array<int, 8>number{ 1,2,3,4,5,6,7,8 };
    std::array<int, 8>even;
    auto it = std::copy_if(number.begin(), number.end(), even.begin(), [](int val) {return (val % 2) == 0; });
    std::for_each(even.begin(), it, [](int val) {cout << val << " "; });
    cout << endl;
}

std::copy_backward

template <class BidirectionalIterator1, class BidirectionalIterator2>
  BidirectionalIterator2 copy_backward (BidirectionalIterator1 first, BidirectionalIterator1 last, BidirectionalIterator2 result);

功能:

​ 将[first,last)范围内从末尾开始的元素复制到以result结束的范围内。即从后往前复制。复制到的result也是从末尾装入。最终两个容器中元素的顺序是一致的。

返回值:

​ 指向目标序列中己复制元素的第一个元素的iterator。

该模板函数的行为等价于:

template<class BidirectionalIterator1, class BidirectionalIterator2>	//要求传入的iterator是双向的
  BidirectionalIterator2 copy_backward ( BidirectionalIterator1 first,
                                         BidirectionalIterator1 last,
                                         BidirectionalIterator2 result )	//容器的末尾iterator
{
    //从后往前copy
  while (last!=first) *(--result) = *(--last);
  return result;
}

测试代码:

void test_copy_backward()
{
    std::array<int, 5>foo{ 1,2,3,4,5 };
    std::array<int, 5>jack{ 0 };
    auto it = std::copy_backward(foo.begin(), foo.end(), jack.end());
    std::for_each(foo.begin(), foo.end(), [](int val) {cout << val << " "; });
    cout << endl;
    std::for_each(jack.begin(), jack.end(), [](int val) {cout << val << " "; });
    cout << endl;
}

std::move

template <class InputIterator, class OutputIterator>
  OutputIterator move (InputIterator first, InputIterator last, OutputIterator result);

功能:

​ 将[first,last)范围内的元素移动到以result开始的范围内。数组[first,last)中元素的值被传递给result所指向的元素。调用之后,[first,last)范围内的元素将保持未指定但有效的状态。

返回值:

​ 指向目标范围末尾的iterator,该范围内的元素己经被移动。

该模板函数的行为等价于:

template<class InputIterator, class OutputIterator>
  OutputIterator move (InputIterator first, InputIterator last, OutputIterator result)
{
  while (first!=last) {
    *result = std::move(*first);
    ++result; ++first;
  }
  return result;
}

测试代码:

void test_move()
{
    std::array<int, 5>foo{ 1,2,3,4,5 };
    std::array<int, 5>jack;
    auto it = std::move(foo.begin(), foo.end(), jack.begin());
    if (it == (jack.begin() + foo.size()))
        cout << "foo移动成功\n";
    cout << foo.size() << endl;	//5
    std::for_each(foo.begin(), foo.end(), [](int val) {cout << val << " "; });	//foo仍是有效状态,虽然未指定
    cout << endl;
    std::for_each(jack.begin(), it, [](int val) {cout << val << " "; });
    cout << endl;

}
  • 注意的是这个函数应该同#include 中提供的std::move区别开来。

    std::move并不能移动任何东西,它唯一的功能是将一个左值强制转化为右值引用,继而可以通过右值引用使用该值,以用于移动语义。从实现上讲,std::move基本等同于一个类型转换:static_cast<T&&>(lvalue);

  • std::move是将对象的状态或者所有权从一个对象转移到另一个对象,只是转移,没有内存的搬迁或者内存拷贝所以可以提高利用效率,改善性能.。

std::move_backward

template <class BidirectionalIterator1, class BidirectionalIterator2>
  BidirectionalIterator2 move_backward (BidirectionalIterator1 first,BidirectionalIterator1 last, BidirectionalIterator2 result);

功能:

​ 将从末尾开始的[first,last)范围内的元素移动到以结果结束的范围内。函数首先将*(last-1)移动到*(result-1)中,然后向后移动这些元素之前的元素,直到到达第一个(包括它)。

返回值:

​ 指向目标序列中已移动元素的第一个元素的迭代器。

该模板函数的行为等价于:

template<class BidirectionalIterator1, class BidirectionalIterator2>
  BidirectionalIterator2 move_backward ( BidirectionalIterator1 first,
                                         BidirectionalIterator1 last,
                                         BidirectionalIterator2 result )
{
  while (last!=first) *(--result) = std::move(*(--last));
  return result;
}

测试代码:

void test_move_backward()
{
    std::string elems[10] = { "air","water","fire","earth" };

    // insert new element at the beginning:
    std::move_backward(elems, elems + 4, elems + 5);
    elems[0] = "ether";

    cout << "elems contains:";
    for (int i = 0; i < 10; ++i)
        cout << " [" << elems[i] << "]";
    cout << '\n';
}

std::swap

// moved from <algorithm> to <utility> in C++11
//non-array	
template <class T> void swap (T& a, T& b)
  noexcept (is_nothrow_move_constructible<T>::value && is_nothrow_move_assignable<T>::value);
//array 
template <class T, size_t N> void swap(T (&a)[N], T (&b)[N])
  noexcept (noexcept(swap(*a,*b)));
template <class T> void swap (T& a, T& b);	//c++98

c++11版本类型T应该是可移动构造或可移动赋值的。

c+++98T应该是可拷贝构造和可转让的

功能:

​ 交换a与b的值。

  • 这个函数涉及到一个拷贝构造函数和两个赋值操作,对于交换存储大量数据的类内容不建议使用这个方法。
  • 对于大数据类型可以提供此函数的重载版本,以优化其性能。值得注意的是所有标准容器都以这样的方式特化它,即只交换少数内部指针,而不是交换它们的全部内容,使它们在常量时间内操作。

返回值:

​ 无返回值。

该模板函数的行为等价于:

  • c++98版

    template <class T> void swap ( T& a, T& b )
    {
      T c(a); a=b; b=c;
    }
    
  • c++11版

    //non-array
    template <class T> void swap (T& a, T& b)
    {
      T c(std::move(a)); a=std::move(b); b=std::move(c);
    }
    //array
    template <class T, size_t N> void swap (T (&a)[N], T (&b)[N])
    {
      for (size_t i = 0; i<N; ++i) swap (a[i],b[i]);
    }
    

    测试代码:

    void test_swap()
    {
        //array
        std::array<int, 5>foo{ 10,10,10,10,10 };
        std::array<int, 5>jack{ 20,20,20,20,20 };
        std::swap(foo, jack);
        cout << "foo中第二个元素是:" <<  foo[1] << "and jack中第二个元素是:" << jack[1] << endl;	//foo[1]=20 jack[1]=10
        //non-array
        int x = 5;
        int y = 20;
        std::swap(x, y);
        cout << "x=" << x << " and y=" << y << endl; // x = 20 y = 5
    }
    

std::swap_ranges

template <class ForwardIterator1, class ForwardIterator2>	//前向iterator
  ForwardIterator2 swap_ranges (ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2);

功能:

​ 将[first1,last1)范围内的每个元素的值与该范围内从first2开始的元素的值交换。

  • 这个函数内部是调用std::swap来交换的。

返回值:

​ 返回第二个序列中交换的最后一个元素的iterator。

该模板函数的行为等价于:

template<class ForwardIterator1, class ForwardIterator2>
  ForwardIterator2 swap_ranges (ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2)
{
  while (first1!=last1) {
    swap (*first1, *first2);
    ++first1; ++first2;
  }
  return first2;
}

测试代码:

void test_swap_ranges()
{
    std::array<int, 9>foo{ 1,2,3,4,5,6,7,8,9 };
    std::swap_ranges(foo.begin(), foo.begin() + 4, foo.begin() + 5);
    std::for_each(foo.begin(), foo.end(), [](int val) {cout << val << " "; });
    cout << endl;
}

std::iter_swap

template <class ForwardIterator1, class ForwardIterator2>
  void iter_swap (ForwardIterator1 a, ForwardIterator2 b);

功能:

​ 交换a和b指向的元素。

该模板函数的行为等价于:

template <class ForwardIterator1, class ForwardIterator2>	//接收前向iterator
  void iter_swap (ForwardIterator1 a, ForwardIterator2 b)
{
  swap (*a, *b);
}

测试代码:

void test_iter_swap()
{
    //数组倒置
    std::array<int, 9>foo{ 1,2,3,4,5,6,7,8,9 };
    auto first = foo.begin();
    auto last = foo.end() - 1;
    for (; first != (foo.begin() + 4) && last != (foo.begin() + 4); ++first, --last)
        std::iter_swap(first, last);
    std::for_each(foo.begin(), foo.end(), [](int val) {cout << val << " "; });
    cout << endl;
}

std::transform

//unary operation	
template <class InputIterator, class OutputIterator, class UnaryOperation>
  OutputIterator transform (InputIterator first1, InputIterator last1, OutputIterator result, UnaryOperation op);
//binary operation	
template <class InputIterator1, class InputIterator2,
          class OutputIterator, class BinaryOperation>
  OutputIterator transform (InputIterator1 first1, InputIterator1 last1,  InputIterator2 first2, OutputIterator result,  BinaryOperation binary_op);

功能:

​ 这是一个变换函数。

  • 一元操作

    ​ 对[first1,last1)中的每个元素应用op,并将每个操作返回的值存储在从result开始的范围内。

  • 二元操作
    使用[first1,last1)中的每个元素作为第一个参数调用binary_op,并将以first2开头的各个参数作为第二个参数传入。每次调用返回的值存储在从result开始的范围中。

op和binary_op都不应该直接修改作为参数传递的元素:如果为result指定了相同的范围,算法会间接修改这些元素(使用返回值)。

返回值:

​ 返回指向结果序列中最后一个元素后的元素的iterator。

该模板函数的行为等价于:

template <class InputIterator, class OutputIterator, class UnaryOperator>
  OutputIterator transform (InputIterator first1, InputIterator last1,   OutputIterator result, UnaryOperator op)
{
  while (first1 != last1) {
    *result = op(*first1);  // or: *result=binary_op(*first1,*first2++);
    ++result; ++first1;
  }
  return result;
}

测试代码:

void test_transform()
{
    std::vector<int>foo;
    std::vector<int>bar;

    for (int i = 1; i < 6; ++i)
        foo.push_back(i * 10);
    //设置相同size
    bar.resize(foo.size());
    //op 一元谓词
    std::transform(foo.begin(), foo.end(), bar.begin(), [](int val) {return ++val; });
    //binary_op 二元谓词
    std::transform(foo.begin(), foo.end(), bar.begin(), foo.begin(), std::plus<int>());
    std::cout << "foo contains:";
    for (std::vector<int>::iterator it = foo.begin(); it != foo.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';
}

std::replace

template <class ForwardIterator, class T>
  void replace (ForwardIterator first, ForwardIterator last,  const T& old_value, const T& new_value);

功能:

​ 将new_value赋值给范围[first,last]中值等于old_value的所有元素。

该模板函数的行为等价于:

template <class ForwardIterator, class T>
  void replace (ForwardIterator first, ForwardIterator last,
                const T& old_value, const T& new_value)
{
  while (first!=last) {
    if (*first == old_value) *first=new_value;
    ++first;
  }
}

测试代码:

void test_replace()
{
    std::array<int, 5>foo{ 11,1,1,1,2 };
    std::replace(foo.begin(), foo.end(), 1, 5);
    std::for_each(foo.begin(), foo.end(), [](int val) {cout << val << " "; });
    cout << endl;
}

std::replace_if

template <class ForwardIterator, class UnaryPredicate, class T>
  void replace_if (ForwardIterator first, ForwardIterator last,  UnaryPredicate pred, const T& new_value );

功能:

​ 将[first,last)中所有满足条件pred的元素值全替换为new_value。

该模板函数的行为等价于:

template < class ForwardIterator, class UnaryPredicate, class T >
  void replace_if (ForwardIterator first, ForwardIterator last,  UnaryPredicate pred, const T& new_value)
{
  while (first!=last) {
    if (pred(*first)) *first=new_value;
    ++first;
  }
}

测试代码:

void test_replace_if()
{
    std::vector<int> myvector;

    // set some values:
    for (int i = 1; i < 10; i++) myvector.push_back(i);               // 1 2 3 4 5 6 7 8 9

    std::replace_if(myvector.begin(), myvector.end(), [](int val) {return ((val % 2) == 1); }, 0); // 0 2 0 4 0 6 0 8 0

    std::cout << "myvector contains:";
    for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值