Tuesday, December 19, 2017

C++98: std::swap_ranges()

std::swap_ranges() swaps elements of two ranges. Here is an example:

#define _SCL_SECURE_NO_WARNINGS 1 // Turn off Microsoft Error/Warning

#include <algorithm>
#include <iostream>
#include <iterator>

int main()
{
  //             Index: 0  1  2  3  4  5  6  7
  int   sequence1[8] = {1, 3, 3, 3, 1, 1, 1, 1};
  int   sequence2[8] = {1, 1, 1, 1, 4, 4, 4, 1};
  int * iter_beg1    = &sequence1[1]           ; // Point to    first 3.
  int * iter_end1    = &sequence1[4]           ; // Point after last  3.
  int * iter_beg2    = &sequence2[4]           ; // Point to    first 4.
  int * iter_end2    = NULL                    ;

  iter_end2 = std::swap_ranges(iter_beg1, // Points after original first 4.
                               iter_end1,
                               iter_beg2);
  std::copy(&sequence1[0]                             ,
            &sequence1[8]                             ,
            std::ostream_iterator(std::cout, " "));
  std::cout << ": ";
  std::copy(&sequence2[0]                             ,
            &sequence2[8]                             ,
            std::ostream_iterator(std::cout, " "));

  std::cout << std::endl;
  return 0;
}
// Output: 1 4 4 4 1 1 1 1 : 1 1 1 1 3 3 3 1
Reference: Josuttis, Nicolai M., The C++ Standard Library: A Tutorial and Reference. New York: Addison-Wesley, 1999, pp. 370-1.

No comments:

Post a Comment