【STL】reverse函数用法


reverse函数的功能是反转排序一个容器中指定元素的内容。

函数参数:reverse(first,last),其中firstlast分别指向被反转序列中初始及末尾位置的双向迭代器(Bidirectional iterators)。这个范围即 [first,last) ,包括 first 到 last 间的所有元素,包括 first 指向的元素,但不包括 last 指向的元素。

无返回值

示例:

#include <iostream>
#include <list>
 
namespace ClassFoo{
void ListReverseExample1() {
    std::list<int> foo;
 
    for (int i=1; i<10; ++i) foo.push_back(i);
 
    foo.reverse();
 
    std::cout << "foo contains:";
    for (std::list<int>::iterator it=foo.begin();
        it!=foo.end(); ++it)
        std::cout << ' ' << *it;
 
    std::cout << '
';
}
}
int main ()
{
    ClassFoo::ListReverseExample1();
    return 0;
}

输出  

foo contains:9 8 7 6 5 4 3 2 1

复杂度

O(n),n 为 last - first.。

数据争用相关

范围 [first,last) 中的所有元素都被修改过。

异常安全性相关

如果元素交换(Swap)或操作某个迭代器抛异常,该函数才会抛异常。

原文地址:https://www.cnblogs.com/Patrick-L/p/6745235.html