C++ vector šŸŽÆ

beginner
10 min

C++ vector šŸŽÆ

Welcome to our deep dive into C++ vectors! We'll explore this powerful container that simplifies managing collections of elements, making your code more efficient and practical.

What is a vector in C++? šŸ“

A std::vector is a dynamic array-like container in the C++ Standard Template Library (STL). It can resize itself as needed, making it perfect for storing collections of elements, such as arrays of different sizes.

Why use a vector? šŸ’”

  • Dynamic size: The size of a vector can change during runtime, making it flexible for varying data amounts.
  • Efficient: Vectors offer fast access to elements, especially when used with standard iterators.
  • Built-in: The C++ Standard Library provides a vector, eliminating the need to reinvent the wheel.

Creating a Vector šŸŽÆ

To create a vector, you need to include the <vector> header and declare a variable of type std::vector.

cpp
#include <vector> int main() { std::vector<int> myVector; // Now we can add elements to myVector }

Adding Elements to a Vector šŸ’”

There are several ways to add elements to a vector, including:

  • Using the push_back() function: This appends an element to the end of the vector.
cpp
myVector.push_back(42); // Adds 42 to the end of myVector
  • Using the constructor: You can create a vector with initial elements.
cpp
std::vector<int> initialVector = {1, 2, 3, 4, 5};

Accessing Elements in a Vector šŸ“

Accessing elements in a vector is straightforward. You use the index of the element, just like a regular array.

cpp
int firstElement = myVector[0]; // Accesses the first element in myVector

Vector Size and Capacity šŸ’”

The size() function returns the number of elements currently in the vector, while the capacity() function tells you the maximum number of elements the vector can currently hold before it needs to resize.

cpp
std::cout << "Vector size: " << myVector.size() << std::endl; std::cout << "Vector capacity: " << myVector.capacity() << std::endl;

Common Vector Operations šŸŽÆ

  • Inserting elements: You can insert an element at a specific position with the insert() function.
cpp
myVector.insert(myVector.begin() + 2, 100); // Inserts 100 at index 2 in myVector
  • Removing elements: You can remove an element at a specific position with the erase() function.
cpp
myVector.erase(myVector.begin() + 1); // Removes the second element in myVector
  • Swapping elements: You can swap the values of two elements using the swap() function.
cpp
myVector[0].swap(myVector[2]); // Swaps the first and third elements in myVector

Quiz šŸ’”

Quick Quiz
Question 1 of 1

What does the `size()` function of a vector return?


Remember, the more you practice, the better you'll get! Keep coding and enjoy your C++ journey with CodeYourCraft. šŸ’»šŸŽ‰

Stay tuned for our upcoming lessons on advanced vector concepts and techniques! šŸŽÆšŸ“