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.
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.
To create a vector, you need to include the <vector> header and declare a variable of type std::vector.
#include <vector>
int main() {
std::vector<int> myVector;
// Now we can add elements to myVector
}There are several ways to add elements to a vector, including:
push_back() function: This appends an element to the end of the vector.myVector.push_back(42); // Adds 42 to the end of myVectorstd::vector<int> initialVector = {1, 2, 3, 4, 5};Accessing elements in a vector is straightforward. You use the index of the element, just like a regular array.
int firstElement = myVector[0]; // Accesses the first element in myVectorThe 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.
std::cout << "Vector size: " << myVector.size() << std::endl;
std::cout << "Vector capacity: " << myVector.capacity() << std::endl;insert() function.myVector.insert(myVector.begin() + 2, 100); // Inserts 100 at index 2 in myVectorerase() function.myVector.erase(myVector.begin() + 1); // Removes the second element in myVectorswap() function.myVector[0].swap(myVector[2]); // Swaps the first and third elements in myVectorWhat 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! šÆš