EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

C++ reserve()

Home » Software Development » Software Development Tutorials » C ++ Programming Tutorial » C++ reserve()

C++ reserve()

Introduction to C++ reserve()

The C ++ reserve() function helps us in reserving a vector capacity. This capacity must be enough so that it can contain n number of elements. This function can help us in increasing the capacity of any given vector which has a value greater than or equal to the new capacity which we will specify in the reserve function. The reserve function will just reserve the space for the vectors but will not increase its size. If the size, you are reserving in the vector is greater than the size then all these changes stand invalidated.

Syntax

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

void reserve (size_type n)

Here n signifies the number of elements that will be stored in the vector. It will not return any value, but it will reserve the space in the memory. The resulting capacity can be equal to or greater than n. size_type is a type that is an unsigned integral type. This can also be referred to as size_t.

How reserve() function work in C ++?

Let us check the working of reserve() function in C ++.

// vector::reserve
#include <iostream>
#include <vector>
int main ()
{
std::vector<int> example;
szc = example.capacity();
example.reserve(100);
std::cout << " Let us change the size of sample:\n:\n";
for (int i=0; i<100; ++i) {
example.push_back(i);
if (szc!=example.capacity()) {
szc = example.capacity();
std::cout << "Capacity of example is changed to: " << szc << '\n';
}
}
}

The reserve function here is reserving 100 bytes. This is allocated in the system once the reserve function is called. The capacity of this variable changes internally. You can then keep assigning values to this variable until this size is full. This function will allocate the said memory beforehand. We will check the working of this function with more examples as below.

Examples

Here are the following examples mention below

Example #1

Code:

#include <iostream>
#include <vector>
using namespace std;
int main(void) {
vector<int> vec1;
vector<int> vec2;
ssize_t size;
size = vec1.capacity();
for (int i = 0; i < 25; ++i) {
vec1.push_back(i);
if (size != vec1.capacity()) {
size = vec1.capacity();
cout << "Increasing the size limit of vector 1 so that it holds" << size
<< " elements" << endl;
}
}
cout << endl << endl;
//Here  we will reserve space for 35 elements using reserve() function
vec2.reserve(35);
for (int i = 0; i < 25; ++i) {
vec2.push_back(i);
if (size != vec2.capacity()) {
size = vec2.capacity();
cout << "Increasing the size limit of vector 2 so that it holds " << size
<< " elements" << endl;
}
}
return 0;
}

Popular Course in this category
C++ Training (4 Courses, 5 Projects, 4 Quizzes)4 Online Courses | 5 Hands-on Projects | 37+ Hours | Verifiable Certificate of Completion | Lifetime Access | 4 Quizzes with Solutions
4.5 (4,882 ratings)
Course Price

View Course

Related Courses
Java Training (40 Courses, 29 Projects, 4 Quizzes)C Programming Training (3 Courses, 5 Project)

The above code is an example where we are comparing reserve() and allocating space separately. We have initially used libraries iostream and vector. This library should be imported as a reserve belongs to the vector library. In the main function, we have taken two vectors.

These are integer vectors and we have defined a size variable that is explained above. capacity() and push_back() are the functions of this class. In the first case, we have used a for loop which is allocating the capacity until it reaches 35. We are using post increment in the loop. As we have not used a reserve() function in the first case, the capacity function can allocate space greater than 35.

While in the second case we are again making use of for loop until it reaches the capacity. The difference that you observe here is we have made use of the vector function reserve(). In this case, will you see that as space is already reserved hence it will not allocate the space again and again, unlike the first case? As space is already allocated there will not be multiple allocations. Observe the output so that you understand this functionality better.

Output:

C++ reserve() output 1

You will see that here space increases in the first case in the second case space is allocated at one go.

Example #2

Code:

#include <cstddef>
#include <new>
#include <vector>
#include <iostream>
// minimal C++11 allocator with debug output
template <class spc>
struct LetAlloc {
typedef spc value_type;
LetAlloc() = default;
template <class Ed> LetAlloc(const LetAlloc<Ed>&) {}
spc* allocate(std::size_t n)
{
n *= sizeof(spc);
std::cout << "Let us allocate space " << n << " bytes\n";
return static_cast<spc*>(::operator new(n));
}
void deallocate(spc* p, std::size_t n)
{
std::cout << "Let us deallocate space " << n*sizeof*p << " bytes\n";
::operator delete(p);
}
};
template <class Ed, class Up>
bool operator==(const LetAlloc<Ed>&, const LetAlloc<Up>&) { return true; }
template <class Ed, class Up>
bool operator!=(const LetAlloc<Ed>&, const LetAlloc<Up>&) { return false; }
int main()
{
int spsz = 100;
std::cout << "We are reserving space here by using reserve function: \n";
{
std::vector<int, LetAlloc<int>> vec1;
vec1.reserve(spsz);
for(int n = 0; n < spsz; ++n)
vec1.push_back(n);
}
std::cout << "Here we are using usual space allocation: \n";
{
std::vector<int, LetAlloc<int>> vec1;
for(int n = 0; n < spsz; ++n)
vec1.push_back(n);
}
}

In the above function, we have created a structure which is allocating and deallocating space using the structure and template format. We have used the sizeof operator which stores the size of the operator needed and allocates space until n is satisfied. Similarly, we are also deallocating the space by using the delete function. Secondly, we have used the reserve function which very easily allocates the space as specified. We have defined a variable known as spsz which has the size allocated as 100. It will allocate space until the condition is satisfied, and space will be reserved for functioning. Observe the below output to understand better.

Output:

C++ reserve() output 2

Conclusion

The reserve() function in CPP is a very useful function of the vector library. It helps in allocating space and reserving it. We can use the two variables size and capacity which will denote the number of elements and the maximum number of elements that can be stored in that vector. These act as the vector which can store without any further reallocation. Once the reserved space is full the library will allocate fresh memory and also it will copy all existing elements. It is a faster and efficient way to reserve space and use it when required. As vectors are dynamic this is a way in which you can store space in advance.

Recommended Articles

This is a guide to the C++ reserve(). Here we discuss how to reserve() function work in C ++ with respective examples for better understanding. You may also have a look at the following articles to learn more –

  1. size() in C++
  2. Operator Precedence in C++
  3. C++ Header Files
  4. C++ any()

C++ Training (4 Courses, 5 Projects, 4 Quizzes)

4 Online Courses

5 Hands-on Projects

37+ Hours

Verifiable Certificate of Completion

Lifetime Access

4 Quizzes with Solutions

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
C plus plus Programming Tutorial
  • Functions
    • C++ String Functions
    • Math Functions in C++
    • Friend Function in C++
    • Recursive Function in C++
    • Virtual Functions in C++
    • strcat() in C++
    • swap() in C++
    • strcmp() in C++
    • ceil function in C++
    • C++ begin()
    • size() in C++
    • C++ test()
    • C++ any()
    • C++ Bitset
    • C++ find()
    • C++?Aggregation
    • C++?String append
    • C++ String Copy
    • C++ end()
    • C++ endl
    • C++ push_back
    • C++ shuffle()
    • malloc() in C++
    • C++ reserve()
    • C++ unique()
    • C++ sort()
    • C++ find_if()
    • Reflection in C++
    • C++ replace()
    • C++ search()
    • C++ Memset
    • C++ size_t
    • C++ Substring
    • C++ Max
    • C++ absolute value
    • C++ memcpy
    • C++ wchar_t
    • C++ free()
    • C++ sizeof()
    • C++ Move Semantics
  • Basic
    • Introduction To C++
    • What is C++
    • Features of C++
    • Applications of C++
    • Best C++ Compiler
    • C++ Data Types
    • C++ Double
    • C++ unsigned int
    • User Defined Data Types in C++
    • Variables in C++
    • C++ Keywords
    • Pointers in C++
    • C++ Void Pointer
    • Function Pointer in C++
    • Iterator in C++
    • C++ Commands
    • Object in C++
    • C++ Literals
    • C++ Reference
    • C++ Undefined Reference
    • String in C++
    • C++ Programming Language (Basics)
    • C++ Identifiers
    • C++ Header Files
    • Type Casting in C++
    • C++ Formatter
  • Operators
    • C++ Operators
    • Arithmetic Operators in C++
    • Assignment Operators in C++
    • Bitwise Operators in C++
    • Relational Operators in C++
    • Boolean Operators in C++
    • Unary Operators in C++
    • C++ Operator[]
    • Operator Precedence in C++
    • C++ operator=()
  • Control Statements
    • Control Statement in C++
    • if else Statement in C++
    • Else If in C++
    • Nested if in C++
    • Continue Statement in C++
    • Break Statement in C++
    • Switch Statement in C++
    • goto Statement in C++
    • C++ Struct
    • Loops in C++
    • Do While Loop in C++
    • Nested Loop in C++
  • Array
    • Arrays in C++
    • 2D Arrays in C++
    • 3D Arrays in C++
    • Multi-Dimensional Arrays in C++
    • C++ Array Functions
    • String Array in C++
    • C++ Length of Array
    • C++ arraylist
  • Constuctor and Destructor
    • Constructor and Destructor in C++
    • Constructor in C++
    • Destructor in C++
    • Copy Constructor in C++
    • Parameterized Constructor in C++
  • Overloading and overriding
    • Overloading and Overriding in C++
    • Overloading in C++
    • Overriding in C++
    • Function Overloading in C++
    • Function Overriding in C++
    • Method Overloading in C++
  • Inhertiance
    • Types of Inheritance in C++
    • Single Inheritance in C++
    • Multiple Inheritance in C++
    • Hierarchical Inheritance in C++
    • Multilevel Inheritance in C++
    • Hybrid Inheritance in C++
  • Sorting
    • Sorting in C++ 
    • Heap Sort in C++
    • C++ Vector Sort
    • Insertion Sort in C++
    • Selection Sort in C++
  • Advanced
    • C++ namespace
    • Encapsulation in C++
    • Access Modifiers in C++
    • Abstract Class in C++
    • C++ Class and Object
    • What is Template Class in C++?
    • C++ Algorithm
    • Data Structures and Algorithms C++
    • C++ Garbage Collection
    • Virtual Keyword in C++
    • Access Specifiers in C++
    • Storage Class in C++
    • Call by Value in C++
    • Multimap in C++
    • C++ Multiset
    • C++ Lambda Expressions
    • Stack in C++
    • C++ Static
    • C++ static_cast
    • Deque in C++
    • C++ Vector Functions
    • C++ 2D Vector
    • C++ List
    • C++ Mutable
    • Enum in C++
    • Abstraction in C++
    • Signal in C++
    • C++ Queue
    • Priority Queue in C++
    • Regular Expressions in C++
    • C++ Hash Table
    • File Handling in C++
    • C++ Stream
    • ifstream in C++
    • C++ ofstream
    • C++ fstream
    • C++ Read File
    • C++ iomanip
    • Macros in C++
    • Templates in C++
    • C++ setprecision
    • C++ Int to String
    • C++ thread( )
    • C++ Thread Pool
    • C++ thread_local
  • Programs
    • Patterns in C++
    • Star Patterns In c++
    • Swapping in C++
    • Reverse Number in C++
    • Palindrome Program in C++
    • Palindrome in C++
    • Factorial Program in C++
    • Fibonacci Series in C++
    • Square Root in C++
    • Random Number Generator in C++
    • Prime Number in C++
    • Leap Year Program in C++
    • Anagram in C++
    • Armstrong Number in C++
    • Reverse String in C++
    • Socket Programming in C++
    • Matrix Multiplication in C++
    • C++ using vs typedef
    • C++ vector vs list
    • C++ vector vs array
  • Interview question
    • C++ Interview Questions
    • Multithreading Interview Questions C++

Related Courses

C++ Training Course

Java Training Course

C Programming Course

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - C++ Training (4 Courses, 5 Projects, 4 Quizzes) Learn More