跳到主要内容

std::vector swap() 方法

// Non const version only
constexpr void swap( vector& other ) noexcept(/* see below */);

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

失效

尾后迭代器失效。

所有其他迭代器和引用保持有效。

如果 std::allocator_traits<allocator_type>::propagate_on_container_swap::valuetrue,则使用对非成员 swap 的非限定调用来交换分配器。否则,它们不被交换(如果 get_allocator() != other.get_allocator(),则行为未定义).

参数

  • other - 要交换内容的容器

返回值

(无)

异常

noexcept(std::allocator_traits<Allocator>::propagate_on_container_swap::value 
|| std::allocator_traits<Allocator>::is_always_equal::value)

复杂度

常数 - O(1)

示例

Main.cpp
#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';

// Note that after swap the iterators and references stay associated with their
// original elements, e.g. it1 that pointed to an element in 'a1' with value 2
// still points to the same element, though this element was moved into 'a2'.
}
输出
{ 1 2 3 } { 4 5 } 2 5 1 4
{ 4 5 } { 1 2 3 } 2 5 1 4
本文源自此 CppReference 页面。它可能为了改进或编辑偏好而被修改。点击“编辑此页面”查看本文档的所有更改。
悬停查看原始许可证。

std::vector swap() 方法

// Non const version only
constexpr void swap( vector& other ) noexcept(/* see below */);

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

失效

尾后迭代器失效。

所有其他迭代器和引用保持有效。

如果 std::allocator_traits<allocator_type>::propagate_on_container_swap::valuetrue,则使用对非成员 swap 的非限定调用来交换分配器。否则,它们不被交换(如果 get_allocator() != other.get_allocator(),则行为未定义).

参数

  • other - 要交换内容的容器

返回值

(无)

异常

noexcept(std::allocator_traits<Allocator>::propagate_on_container_swap::value 
|| std::allocator_traits<Allocator>::is_always_equal::value)

复杂度

常数 - O(1)

示例

Main.cpp
#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';

// Note that after swap the iterators and references stay associated with their
// original elements, e.g. it1 that pointed to an element in 'a1' with value 2
// still points to the same element, though this element was moved into 'a2'.
}
输出
{ 1 2 3 } { 4 5 } 2 5 1 4
{ 4 5 } { 1 2 3 } 2 5 1 4
本文源自此 CppReference 页面。它可能为了改进或编辑偏好而被修改。点击“编辑此页面”查看本文档的所有更改。
悬停查看原始许可证。