Methods available with vector in C++
The vector class in C++ provides various methods to perform different operations on vectors. Here are some commonly used methods:
push_back()
: Inserts a new element at the end of the vector.pop_back()
: Removes the last element from the vector.size()
: Returns the number of elements in the vector.empty()
: Returns true if the vector is empty.clear()
: Removes all elements from the vector.begin()
: Returns an iterator pointing to the first element of the vector.end()
: Returns an iterator pointing to the past-the-end element of the vector.insert()
: Inserts an element at a specified position in the vector.erase()
: Removes an element from a specified position in the vector.resize()
: Resizes the vector to a specified size.swap()
: Swaps the contents of two vectors.at()
: Returns a reference to the element at a specified position in the vector.front()
: Returns a reference to the first element in the vector.back()
: Returns a reference to the last element in the vector.data()
: Returns a direct pointer to the memory array used internally by the vector.
Here's an example code snippet that demonstrates the usage of some of these methods:
#include <iostream> #include <vector> int main() { std::vector<int> vec; // Insert elements using push_back() vec.push_back(10); vec.push_back(20); vec.push_back(30); // Access elements using indexing std::cout << "Element at index 1: " << vec[0] << std::endl; // Access elements using at() std::cout << "Element at index 2: " << vec.at(2) << std::endl; // Size of the vector std::cout << "Size of the vector: " << vec.size() << std::endl; // Check if the vector is empty if (vec.empty()) { std::cout << "Vector is empty" << std::endl; } else { std::cout << "Vector is not empty" << std::endl; } // Clear the vector vec.clear(); // Check if the vector is empty after clearing if (vec.empty()) { std::cout << "Vector is empty" << std::endl; } else { std::cout << "Vector is not empty" << std::endl; } return 0; }
Element at index 1: 20 Element at index 2: 30 Size of the vector: 3 Vector is not empty Vector is empty
Please note that this is not an exhaustive list of all the methods available with the vector class. You can refer to the C++ documentation or the provided sources for more information on the vector class and its methods.
Comments
Post a Comment