resize()和reserve()有什么区别?

STL*_*mer 0 c++ stl vector

#include<iostream>
using namespace std;
#include<vector>
#include "s.h"


template<class T> 
void f(vector<T> a)
{
    cout << "size  " << a.size() << endl;
    cout << "capacity  " << a.capacity() << endl << endl;
}


int main()
{
    vector<int> s(10,5);
    f(s);
    s.resize(50);
    f(s);
    s.reserve(150);
    f(s);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我认为resize()会改变大小,而reserve()会改变容量,但在我的例子中,reserve()不会改变capasity,为什么?我的第二个问题 - assign()的含义是什么?我可以用operator =()做同样的事吗?

// 10 10
// 50 50 
// 50 50
Run Code Online (Sandbox Code Playgroud)

the*_*mel 6

当您将向量传递给函数时,您正在创建向量的副本.更改定义f以通过引用传递向量,并且您看到它的行为与您期望的一样:

void f(const vector<T>& a)
Run Code Online (Sandbox Code Playgroud)

版画

size  10
capacity  10

size  50
capacity  50

size  50
capacity  150
Run Code Online (Sandbox Code Playgroud)