0
#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;
}

I think resize() changes size, and reserve() changes capacity, but in my example reserve() don't change capasity, why? And my second question-what is the meaning assign()? can i do the same with operator=()?

// 10 10
// 50 50 
// 50 50
Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
STL programmer
  • 141
  • 2
  • 10

4 Answers4

6

You are creating a copy of your vector when you pass it into the function. Change the definition of f to pass the vector by reference, and you see that it behaves as you expect:

void f(const vector<T>& a)

prints

size  10
capacity  10

size  50
capacity  50

size  50
capacity  150
themel
  • 8,825
  • 2
  • 32
  • 31
4

Copying a vector copies its contents. And the capacity is not considered part of a vector's contents. Since your f function copies its parameter, you're not passing the actual vector; you're passing a copy. A copy whose capacity is set to an implementation-defined value.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
3

The call to reserve(...) may in fact be working, but you just don't know it. When you call your function

void f(vector<T> a)

you are copying your original vector into the new vector a; at that point I suspect that the library creates a vector with some minimum capacity. If you try changing the signature of your function to

void f(vector<T> const& a)

you may see the results you are expecting, as the function will then be operating on the original vector object instead of a copy.

aldo
  • 2,927
  • 21
  • 36
1

reserve() always increases capacity while resize() can do anything including destroying your data and its dangerous in some way. calling reserve() for smaller capacity than the actual size may not cause any problem nor a change while calling resize() with a value smaller than the size simply crops your data or resizing with a value higher than the actual size increases vector size itself ofcourse

fatihk
  • 7,789
  • 1
  • 26
  • 48