CppDS.com

C++ 98 11 14 17 20 手册

std::vector<T,Allocator>::swap

来自cppreference.com
< cpp‎ | container‎ | vector

void swap( vector& other );
(C++17 前)
void swap( vector& other ) noexcept(/* see below */);
(C++17 起)
(C++20 前)
constexpr void swap( vector& other ) noexcept(/* see below */);
(C++20 起)

将内容与 other 的交换。不在单个元素上调用任何移动、复制或交换操作。

所有迭代器和引用保持合法。尾后迭代器被非法化。


std::allocator_traits<allocator_type>::propagate_on_container_swap::value 为 true ,则用非成员 swap 的非限定调用交换分配器。否则,不交换它们(且若 get_allocator() != other.get_allocator() ,则行为未定义)。

(C++11 起)

参数

other - 要与之交换内容的容器

返回值

(无)

异常

(无)

(C++17 前)
noexcept 规定:  
noexcept(std::allocator_traits<Allocator>::propagate_on_container_swap::value
|| std::allocator_traits<Allocator>::is_always_equal::value)
(C++17 起)

复杂度

常数。

示例

#include <iostream>
#include <vector>
 
template<class Os, class Co> Os& operator<<(Os& os, const Co& co) {
    os << "{";
    for (auto const& i : co) { os << ' ' << i; }
    return os << " } ";
}
 
int main()
{
    std::vector<int> a1{1, 2, 3}, a2{4, 5};
 
    auto it1 = std::next(a1.begin());
    auto it2 = std::next(a2.begin());
 
    int& ref1 = a1.front();
    int& ref2 = a2.front();
 
    std::cout << a1 << a2 << *it1 << ' ' << *it2 << ' ' << ref1 << ' ' << ref2 << '\n';
    a1.swap(a2);
    std::cout << a1 << a2 << *it1 << ' ' << *it2 << ' ' << ref1 << ' ' << ref2 << '\n';
 
    // 注意交换后迭代器与引用保持与其原来的元素关联,例如指向 'a1' 中值为 2 的元素的 it1 仍指向同一元素,
    // 尽管此元素被移动到 'a2' 中。
}

输出:

{ 1 2 3 } { 4 5 } 2 5 1 4
{ 4 5 } { 1 2 3 } 2 5 1 4

参阅

特化 std::swap 算法
(函数模板)
关闭