std::move(), which moves elements to another range or backwards in the same range. You specify the beginning of the destination range and the elements are moved from the beginning to the end of the source range.std::move_backward(), which moves elements to another range or forward in the same range. You specify the end of the destination range and the elements are moved from the end to the beginning of the source range.
# 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'
std::remove() with the value 2 to remove all elements with the value 2 modifies the sequence as follows:
1 3 4 5 4 3 1 2 1std::remove() and std::remove_if()std::unique()std::copy, the algorithm will copy elements:
std::copy(src.begin(), src.end(), dst.begin());
std::copy(
std::make_move_iterator(src.begin()),
std::make_move_iterator(src.end()),
std::back_inserter(dst)
);
std::for_each:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
template<typename 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";
}
void process(std::string s) // gets moved value from rvalues
{
std::cout << "- process(" << s << ")\n";
//...
}
int main()
{
std::vector<std::string> coll{"don't", "vote", "for", "liars"};
print("coll", coll);
// move away only the elements processed:
std::for_each(std::make_move_iterator(coll.begin()),
std::make_move_iterator(coll.end()),
[] (auto&& elem) {
if (elem.size() != 4) {
process(std::move(elem));
}
});
print("coll", coll);
}
# 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).