Home » C++ STL

Difference between size and capacity of a vector in C++ STL

C++ STL | size vs capacity of a vector: Here, we are going to learn about the difference between size and capacity of a vector.
Submitted by IncludeHelp, on May 17, 2019

1) C++ STL vector size

The vector size is the total number of elements of a vector and it always the same for all compilers. To get the size of a vector, vector::size() function is used.

Read more: C++ STL vector::size() function

2) C++ STL vector capacity

Capacity is the memory space occupied by a vector; elements of a vector are stored as an array in the memory. Thus, the capacity is the amount of space which is currently using by the vector (or internal array). It will also equal to greater than the size of the vector. It may differ on the different compiler. To get the capacity of a vector, vector::capacity() function is used.

Read more: C++ STL vector::capacity() function

C++ STL program to demonstrate difference between vector size and capacity

//C++ STL program to demonstrate difference between 
//vector size and capacity 
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    //vector declaration
    vector<int> v1{ 10, 20, 30, 40, 50 };
    vector<int> v2{ 100, 200, 300, 400 };

    //size, capacity and elements of vector v1
    cout << "size of v1: " << v1.size() << endl;
    cout << "capacity of v1: " << v1.capacity() << endl;
    cout << "v1: ";
    for (int x : v1)
        cout << x << " ";
    cout << endl;

    //size, capacity and elements of vector v2
    cout << "size of v2: " << v2.size() << endl;
    cout << "capacity of v2: " << v2.capacity() << endl;
    cout << "v2: ";
    for (int x : v2)
        cout << x << " ";
    cout << endl;

    return 0;
}

Output

size of v1: 5
capacity of v1: 5
v1: 10 20 30 40 50
size of v2: 4
capacity of v2: 4
v2: 100 200 300 400





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.