c++ - 不带参数调用 std::vector::reserve 是什么意思,为什么在创建空 vector 后这样做?

标签 c++ c++11 vector

<分区>

我正在关注 this tutorial on move semantics当我遇到以前从未见过的东西时:没有参数的 vector.reserve()。我去了documentation对于该方法,还没有保留(无效)签名。如果我们可以调用 reserve(void),为什么没有记录呢?此外,该调用的作用是什么?为什么我们要在实例化一个空 vector 后进行调用?

#include <iostream>

using namespace std;

vector<int> doubleValues (const vector<int>& v)
{
    vector<int> new_values;
    new_values.reserve();
    for (auto itr = v.begin(), end_itr = v.end(); itr != end_itr; ++itr )
    {
        new_values.push_back( 2 * *itr );
    }
    return new_values;
}

int main()
{
    vector<int> v;
    for ( int i = 0; i < 100; i++ )
    {
        v.push_back( i );
    }
    v = doubleValues( v );
}

最佳答案

除了未包含的 header 之外,代码无法编译,也就是说,根据 C++11 标准:http://coliru.stacked-crooked.com/a/0ba7ec853fced363

引用自 C++11 标准:

§ 23.3.6.1 Class template vector overview [vector.overview]

[...]
bool empty() const noexcept;
void reserve(size_type n);
void shrink_to_fit();
[...]

总是先测试二手代码!

关于c++ - 不带参数调用 std::vector::reserve 是什么意思,为什么在创建空 vector 后这样做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22191392/

相关文章:

c++ - Boost 分配器的 vector 大小不正确

matlab - Matlab 中一次运行中由另一个向量决定的累积求和向量分量

c++ - 操作系统原生 2D API 与 OpenGL

c++ - 尝试保存用户输入 MFC

c++ - 在 64 位 Debian 环境下编译 32 位 qt 源码

c++ - C++ 中的 B 样条曲线

c++ - 使用 NuGet 包将带有 Cuda 的 OpenCV 添加到 Visual Studio 程序中?

c++ - std::enable_if 的两个版本有什么区别

c++ - 可变参数模板和类型安全

c++ - 在显式实例化 vector<someType> 时,someType 默认构造函数用于什么?