Open In App

std::move_iterator in C++ 11

std::move_iterator was introduced in C++11, with the ability to convert regular iterators into move iterators. Instead of copying, the std::move_iterator allows the STL to move the objects it manipulates. The move iterator wraps the other iterator. This is particularly helpful while working with huge information designs or items that can be moved yet not duplicated effectively.

Syntax

To create a move iterator from the existing container’s iterator, we use the make_move_iterator() function as shown:



move_iterator <container<T>::iterator> itr = make_move_iterator( container<T>:::iterator );

Here,

Example 1: Moving All Elements From the Source to the Destination

BEFORE:



Source Vector = {1, 2, 3, 4, 5}

Destination Vector = {}

AFTER:

Source Vector = {}

Destination Vector = {1, 2, 3, 4, 5}

Example 2: Moving Elements From the Middle of the Source Vector

BEFORE:

Source Vector = {1, 2, 3, 4, 5}

Destination Vector = {}

AFTER:

Source Vector = {1, 2}

Destination Vector = {3, 4, 5}

C++ Program to Implement std::move_iterator

Let’s explore a basic example to understand how std::move_iterator works:




// C++ Program to implement move_iterator
#include <bits/stdc++.h>
  
using namespace std;
  
int main()
{
    // source vector
    vector<string> v1 = { "Hi", "Geeks", "for", "Geeks" };
  
    // destination vector
    vector<string> v2;
  
    cout << "Before move iterator\n";
    cout << "Source: ";
    for (auto s : v1) {
        cout << s << ' ';
    }
    cout << endl;
  
    cout << "Destination: ";
    for (auto s : v2) {
        cout << s << ' ';
    }
    cout << endl;
  
    // using std::copy to copy elements from one vector to
    // another
    copy(make_move_iterator(begin(v1)),
         make_move_iterator(end(v1)), back_inserter(v2));
  
    cout << "\nAfter move iterator\n";
    cout << "Source: ";
    for (auto s : v1) {
        cout << s << ' ';
    }
    cout << endl;
  
    cout << "Destination: ";
    for (auto s : v2) {
        cout << s << ' ';
    }
    cout << endl;
    return 0;
}

Output
Before move iterator
Source: Hi Geeks for Geeks 
Destination: 

After move iterator
Source:     
Destination: Hi Geeks for Geeks 

In this code:

When to Use std::move_iterator?

You should consider using std::move_iterator in the following scenarios:

  1. Optimizing Memory Usage: When you need to transfer elements from one container to another while minimizing memory overhead.
  2. Performance Enhancement: When you want to improve performance by avoiding unnecessary copying of elements.
  3. Containers with Move Semantics: When you’re working with containers, like std::vector, that support move semantics.C++ Program to Use std::move_iterator.

Article Tags :