c++11总结25——reverse_copy

1. 功能

将src[begin,end)内的元素复制到"以dst起始的目标区间",并在复制过程中将元素倒序插入。

2. 源码分析

将原容器中的元素反序插入目的容器。

template 
_CONSTEXPR20 _OutIt reverse_copy(_BidIt _First, _BidIt _Last, _OutIt _Dest) {
    // copy reversing elements in [_First, _Last)
    _Adl_verify_range(_First, _Last);
    const auto _UFirst = _Get_unwrapped(_First);
    auto _ULast        = _Get_unwrapped(_Last);
    auto _UDest        = _Get_unwrapped_n(_Dest, _Idl_distance<_BidIt>(_UFirst, _ULast));

    ...

    for (; _UFirst != _ULast; ++_UDest) {   // 核心处理部分: 将_BidIt的元素反序插入至_Dest
        *_UDest = *--_ULast;
    }

    _Seek_wrapped(_Dest, _UDest);
    return _Dest;
}

3. 示例

#include 
#include 
#include 

using namespace std;

int main()
{
	std::vector v({ 1,2,3,4 });
	for (const auto& value : v) {
		cout << value << " ";
	}
	cout << endl;

	std::vector dst(4);  // 指定vector的容量
	cout << "dst.size(): " << dst.size() << endl;
	cout << "dst.capacity(): " << dst.capacity() << endl;

	cout << endl;
	std::reverse(std::begin(v), std::end(v));  // 容器元素反转
	cout << "reverse begin" << endl;
	for (const auto& value : v) {
		cout << value << " ";
	}
	cout << endl;
	cout << "reverse end" << endl;
	cout << endl;

	// 将v中元素逆序放入dst dst必须有大于等于v的空间来进行存储
	std::reverse_copy(std::begin(v), std::end(v), std::begin(dst));
	cout << "reverse_copy begin" << endl;
	for (const auto& value : dst) {
		cout << value << " ";
	}
	cout << endl;
	cout << "reverse_copy end" << endl;
	cout << endl;

	system("pause");
	return 0;
}

打印结果:

c++11总结25——reverse_copy_第1张图片

你可能感兴趣的:(c++11/17,c++11,c++)