Language: EN

cpp-que-son-vector

What are Vectors in C++ and How to Use Them

In C++, a vector is a collection that implements a dynamically sized array (that is, it automatically adjusts in size as needed).

The std::vector class in the C++ standard library provides an implementation. Unlike traditional arrays, vectors allow for the addition and removal of elements.

Declaring Vectors

To declare a vector in C++, the following syntax is used:

#include <vector>

std::vector<type> vectorName;

Where:

  • type: This is the data type that the vector will contain, such as int, double, std::string, etc.
  • vectorName: This is the identifier for the vector.

For example, to declare a vector of integers:

#include <vector>

std::vector<int> numbers;

Creating and Initializing Vectors

Once a vector is declared, it must be initialized before use.

Empty Initialization

You can create an empty vector and then add elements to it:

#include <vector>

std::vector<int> numbers; // Empty vector

Initialization with Specific Size

You can initialize a vector with a specific size, where all elements are initialized to a default value (usually 0 for numeric types):

#include <vector>

std::vector<int> numbers(5); // Vector with 5 elements, all initialized to 0

Initialization with Specific Values

To initialize a vector with specific values, you can use the following syntax:

#include <vector>

std::vector<int> numbers = {1, 2, 3, 4, 5}; // Vector with values 1, 2, 3, 4, 5

Initialization with Value and Size

You can also initialize a vector with a specific size and an initial value for all elements:

#include <vector>

std::vector<int> numbers(5, 10); // Vector with 5 elements, all initialized to 10

Basic Usage of Vectors

Accessing Elements

Elements of a vector can be accessed using indices, starting from 0:

#include <vector>
#include <iostream>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    int firstNumber = numbers[0]; // firstNumber will be 1
    std::cout << "The first number is: " << firstNumber << std::endl;

    return 0;
}

Modifying Elements

You can modify the elements of the vector by assigning new values to specific indices:

#include <vector>
#include <iostream>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    numbers[1] = 20; // The second element of the vector will now be 20
    std::cout << "The modified second number is: " << numbers[1] << std::endl;

    return 0;
}

Adding Elements to a Vector

To add elements to the end of the vector, the push_back method is used:

#include <vector>
#include <iostream>

int main() {
    std::vector<int> numbers = {1, 2, 3};
    numbers.push_back(4); // Adds the number 4 to the end of the vector

    std::cout << "Vector after adding an element: ";
    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}

Removing Elements from a Vector

To remove an element from the end of the vector, use the pop_back method:

#include <vector>
#include <iostream>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4};
    numbers.pop_back(); // Removes the last element (4)

    std::cout << "Vector after removing an element: ";
    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}

You can also remove an element at a specific position using the erase method:

#include <vector>
#include <iostream>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    numbers.erase(numbers.begin() + 2); // Removes the third element (3)

    std::cout << "Vector after removing an element at position 2: ";
    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}

Inserting Elements at a Specific Position

To insert an element at a specific position in the vector, use the insert method:

#include <vector>
#include <iostream>

int main() {
    std::vector<int> numbers = {1, 2, 4, 5};
    numbers.insert(numbers.begin() + 2, 3); // Inserts the number 3 at position 2

    std::cout << "Vector after inserting an element at position 2: ";
    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}

Useful Properties and Methods

vectors in C++ offer various properties and methods for efficiently manipulating and accessing their elements:

Size Property

The size() function returns the number of elements in the vector:

#include <vector>
#include <iostream>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    std::cout << "Number of elements in the vector: " << numbers.size() << std::endl;

    return 0;
}

Capacity Method

The capacity() function returns the current capacity of the vector, that is, the number of elements it can hold before needing a relocation:

#include <vector>
#include <iostream>

int main() {
    std::vector<int> numbers = {1, 2, 3};
    std::cout << "Capacity of the vector: " << numbers.capacity() << std::endl;

    return 0;
}

Clear Method

The clear() method removes all elements from the vector:

#include <vector>
#include <iostream>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    numbers.clear(); // Removes all elements

    std::cout << "Number of elements after clear: " << numbers.size() << std::endl;

    return 0;
}

Sort Method

To sort the elements of a vector, you can use the sort function from the <algorithm> library:

#include <vector>
#include <algorithm>
#include <iostream>

int main() {
    std::vector<int> numbers = {5, 3, 1, 4, 2};
    std::sort(numbers.begin(), numbers.end()); // Sorts the vector in ascending order

    std::cout << "Sorted vector: ";
    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}

Reverse Method

To reverse the order of the elements, you can use the reverse function from the <algorithm> library:

#include <vector>
#include <algorithm>
#include <iostream>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    std::reverse(numbers.begin(), numbers.end()); // Reverses the order of elements

    std::cout << "Reversed vector: ";
    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}

Practical Examples

Calculating the Sum of Elements in a Vector

This example uses a for loop to calculate the sum of the elements in a vector:

#include <vector>
#include <iostream>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    int sum = 0;

    for (int num : numbers) {
        sum += num;
    }

    std::cout << "The sum of the elements is: " << sum << std::endl;

    return 0;
}

Filtering Elements from a Vector

This example uses a for loop to filter even elements from a vector:

#include <vector>
#include <iostream>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    std::vector<int> evenNumbers;

    for (int num : numbers) {
        if (num % 2 == 0) {
            evenNumbers.push_back(num);
        }
    }

    std::cout << "Even numbers: ";
    for (int num : evenNumbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}

Finding the Maximum Value in a Vector

This example uses the max_element function from the <algorithm> library to find the maximum value in a vector:

#include <vector>
#include <algorithm>
#include <iostream>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    int maximum = *std::max_element(numbers.begin(), numbers.end());

    std::cout << "The maximum value is: " << maximum << std::endl;

    return 0;
}

Counting How Many Elements Meet a Condition

This example uses the count_if function from the <algorithm> library to count how many elements in a vector are greater than a specific value:

#include <vector>
#include <algorithm>
#include <iostream>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    int counter = std::count_if(numbers.begin(), numbers.end(), [](int num) { return num > 3; });

    std::cout << "There are " << counter << " elements greater than 3" << std::endl;

    return 0;
}

Removing Elements from a Vector

This example uses the remove_if function from the <algorithm> library to remove all odd elements from a vector:

#include <vector>
#include <algorithm>
#include <iostream>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    numbers.erase(std::remove_if(numbers.begin(), numbers.end(), [](int num) { return num % 2 != 0; }), numbers.end());

    std::cout << "Remaining numbers: ";
    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}