What is C++ Vector and How to Declare Vector in C++

The IoT Academy
4 min readNov 7, 2023

--

Introduction

C++ is a powerful and versatile programming language that provides a wide range of data structures to manipulate and manage data efficiently. One of the most commonly used data structures in C++ is the C++ vector, which belongs to the Standard Template Library (STL).

In this blog, we will explore what a C++ vector is, how to declare a vector in C++ and provide examples to illustrate its usage.

Understanding C++ Vector

A C++ vector is a dynamic array that can grow or shrink in size as needed. It is part of the C++ Standard Template Library (STL) and provides a convenient and efficient way to store and manipulate collections of objects. Unlike traditional arrays in C++, vectors automatically manage memory and can be resized without the need for manual memory management.

Here are some key characteristics of C++ vectors:

  1. Dynamic Size: Vectors can change in size dynamically, which means you can add or remove elements from them without worrying about memory allocation or deallocation.
  2. Sequential Access: Elements in a vector are stored in a contiguous block of memory, allowing for fast sequential access to the elements.
  3. Automatic Memory Management: Vectors handle memory allocation and deallocation automatically, so you don’t need to worry about managing memory manually.
  4. Efficient Operations: Vectors provide efficient insertion and deletion of elements at the end, as well as random access to elements.

Now that we have a basic understanding of what C++ vectors are, let’s dive into how to declare and use them.

Vector Declaration in C++

To declare a vector in C++, you need to include the <vector> header, which provides the necessary functions and templates for working with vectors. Here’s the basic syntax for declaring a vector:

#include <vector>

std::vector<DataType> vectorName;

  • DataType: Replace this with the data type of the elements you want to store in the vector (e.g., int, double, std::string, or even user-defined types).
  • vectorName: Choose a name for your vector.

Example: Declaring a Vector

Let’s look at some examples of declaring vectors with different data types:

#include <iostream>

#include <vector>

int main() {

// Declare an integer vector

std::vector<int> intVector;

// Declare a double vector

std::vector<double> doubleVector;

// Declare a string vector

std::vector<std::string> stringVector;

return 0;

}

In the code above, we have declared three different vectors to store integers, doubles, and strings, respectively.

C++ Vector Methods

C++ vectors provide a variety of methods and operations for manipulating their contents. Here are some of the most commonly used vector methods:

Push BackThe push_back method is used to add elements to the end of the vector.

std::vector<int> numbers;

numbers.push_back(10);

numbers.push_back(20);

numbers.push_back(30);

After executing this code, the numbers vector will contain the elements 10, 20, and 30.

Accessing Elements: You can access elements in a vector using the at() method or the [] operator. Remember that vector indices start from 0.

std::vector<int> numbers = {10, 20, 30};

int firstNumber = numbers.at(0); // Accessing the first element (10)

int secondNumber = numbers[1]; // Accessing the second element (20)

Size: To determine the number of elements in a vector, you can use the size() method.

std::vector<int> numbers = {10, 20, 30};

int size = numbers.size(); // size is now 3

Pop Back: The pop_back() method removes the last element from the vector.

std::vector<int> numbers = {10, 20, 30};

numbers.pop_back(); // Removes the last element (30)

Clear: The clear() method removes all elements from the vector, leaving it empty.

std::vector<int> numbers = {10, 20, 30};

numbers.clear(); // Vector is now empty

Iterating Over Elements: You can use a loop to iterate over the elements in a vector:

std::vector<int> numbers = {10, 20, 30};

for (int i = 0; i < numbers.size(); ++i) {

std::cout << numbers[i] << “ “;

}

Alternatively, you can use a range-based for loop:

for (const auto& num : numbers) {

std::cout << num << “ “;

}

These are just a few of the many methods and operations you can perform on C++ vectors. Vectors provide a flexible and efficient way to manage collections of data in your C++ programs.

C++ Vector Example

To illustrate the use of C++ vectors, let’s work through a simple example that involves reading a list of numbers from the user and storing them in a vector. We will then calculate the sum of the numbers and display the result.

#include <iostream>

#include <vector>

int main() {

std::vector<int> numbers;

int num;

// Read numbers from the user and store them in the vector

std::cout << “Enter numbers (enter 0 to stop):” << std::endl;

while (true) {

std::cin >> num;

if (num == 0) {

break;

}

numbers.push_back(num);

}

// Calculate and display the sum of the numbers

int sum = 0;

for (const auto& n : numbers) {

sum += n;

}

std::cout << “Sum of the numbers: “ << sum << std::endl;

return 0;

}

In this example, the program continuously reads numbers from the user until they enter 0. The numbers are stored in a vector, and then the program calculates the sum of the entered numbers using a range-based for loop.

Conclusion

C++ vectors are a fundamental data structure that offers dynamic resizing, automatic memory management, and efficient operations for working with collections of data. They are an essential tool for C++ programmers and can simplify the task of managing and manipulating data in your programs. In this blog, we covered what C++ vectors are, how to declare them, and some common vector methods. Armed with this knowledge, you can confidently use vectors in your C++ projects to enhance their functionality and flexibility.

--

--

The IoT Academy
The IoT Academy

Written by The IoT Academy

The IoT Academy specialized in providing emerging technologies like advanced Embedded systems, Internet of Things, Data Science,Python, Machine Learning, etc

No responses yet