Wednesday, October 26, 2016

STL iterator [03]: Iterator auxiliary function --

std::make_move_iterator


[References]
1. "std::make_move_iterator, from naipc.uchicago.edu.."
2. "std::move_iterator, from en.cppreference.com"

Defined in header <iterator>
template< class Iterator >
std::move_iterator<Iterator> make_move_iterator( const Iterator& i );
(since C++11)
(until C++14)
template< class Iterator >
std::move_iterator<Iterator> make_move_iterator( Iterator i );
(since C++14)
(until C++17)
template< class Iterator >
constexpr std::move_iterator<Iterator> make_move_iterator( Iterator i );
(since C++17)
make_move_iterator is a convenience function template that 
  • constructs a std::move_iterator for the given iterator i 
  • with the type deduced from the type of the argument.

Parameters

i-input iterator to be converted to move iterator

Return value

std::move_iterator which can be used to move from the elements accessed through i

Possible implementation

template< class Iterator >
std::move_iterator<Container> make_move_iterator( const Iterator& i )
{
    return std::move_iterator<Iterator>(i);
}

Example

#include <iostream>
#include <list>
#include <vector>
#include <string>
#include <iterator>
int main()
{
    std::list<std::string> s{"one", "two", "three"};
 
    std::vector<std::string> v1(s.begin(), s.end()); // copy
 
    std::vector<std::string> v2(std::make_move_iterator(s.begin()),
                                std::make_move_iterator(s.end())); // move
 
    std::cout << "v1 now holds: ";
    for(auto str : v1)
            std::cout << "\"" << str << "\" ";
    std::cout << "\nv2 now holds: ";
    for(auto str : v2)
            std::cout << "\"" << str << "\" ";
    std::cout << "\noriginal list now holds: ";
    for(auto str : s)
            std::cout << "\"" << str << "\" ";
    std::cout << '\n';
}
Output:
v1 now holds: "one" "two" "three"
v2 now holds: "one" "two" "three"
original list now holds: "" "" ""
...


std::move_iterator

Defined in header <iterator>
template< class Iterator >
class move_iterator; (since C++11)

std::move_iterator is an iterator adaptor which behaves exactly like the underlying iterator (which must be at least an InputIterator), except that dereferencing converts the value returned by the underlying iterator into an rvalue. If this iterator is used as an input iterator, the effect is that the values are moved from, rather than copied from.
...

No comments:

Post a Comment