Moving Algorithms

# include<iostream>
# include<vector>
# include<string>

template<class T>
void print(const std::string& name, const T& coll)
{
   std::cout << name << " (" << coll.size() << " elems): ";
   for (const auto& elem : coll) {
      std::cout << " '" << elem << "'";
   }
   std::cout << "\n";
}

int main() {

   std::vector<std::string> v1={"love","is","all","you","need"};
   std::vector<std::string> v2;
   std::vector<std::string> v3;

   v2.resize(v1.size());
   v3.resize(v1.size()+3);

   std::move(v1.begin(),v1.end(),v2.begin());
   std::move_backward(v2.begin(),v2.begin()+3,v3.end());

   print("v1",v1);
   print("v2",v2);
   print("v3",v3);
}

Result:

v1 (5 elems):  '' '' '' '' ''
v2 (5 elems):  '' '' '' 'you' 'need'
v3 (8 elems):  '' '' '' '' '' 'love' 'is' 'all'

Removing Algorithms

Move Iterators

# Move Iterators in Constructors and Member Functions

std::list<std::string> src{"don't", "vote", "for", "liars"};

// move all elements from the list to the vector:
std::vector<std::string> vec{
   std::make_move_iterator(src.begin()),
   std::make_move_iterator(src.end())
};

By the way, what’s difference between them?

std::vector<int> v1={1,2,3};
std::vector<int> v2 = std::move(v1);
std::vector<int> v1={1,2,3};
std::vector v3{
   std::make_move_iterator(v1.begin()),
   std::make_move_iterator(v1.end())
};

The first move an entire object to another with time complexity O(1). However, in the second, each element was moved individually to another with time complexity O(N).