swap_ranges() 用来交换两个序列。这个算法需要 3 个正向迭代器作为参数:前两个参数分别是第一个序列的开始和结束迭代器,第三个参数是第二个序列的开始迭代器。
这个算法会返回一个迭代器,它指向第二个序列的最后一个被交换元素的下一个位置。
template<class ForwardIt1, class ForwardIt2>
constexpr ForwardIt2 swap_ranges(ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2)
{
while (first1 != last1) {
std::iter_swap(first1++, first2++);
}
return first2;
}
#include
#include
#include
#include
auto print = [](auto comment, auto const& seq) {
std::cout << comment;
for (const auto& e : seq) { std::cout << e << ' '; }
std::cout << '\n';
};
int main()
{
std::vector<char> vct = { 'a', 'b', 'c', 'd', 'e' };
std::list<char> lst = { '1', '2', '3', '4', '5', '6' };
print("Before swap_ranges:\n" "v: ", vct);
print("l: ", lst);
std::list<char>::iterator itr = std::swap_ranges(vct.begin(), vct.begin() + 3, lst.begin());
int val = std::distance(lst.begin(), itr);
std::cout << "distance=" << val << "\n";
print("After swap_ranges:\n" "v: ", vct);
print("l: ", lst);
}
Before swap_ranges:
v: a b c d e
l: 1 2 3 4 5 6
distance=3
After swap_ranges:
v: 1 2 3 d e
l: a b c 4 5 6