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:

  1. push_back(): Inserts a new element at the end of the vector.
  2. pop_back(): Removes the last element from the vector.
  3. size(): Returns the number of elements in the vector.
  4. empty(): Returns true if the vector is empty.
  5. clear(): Removes all elements from the vector.
  6. begin(): Returns an iterator pointing to the first element of the vector.
  7. end(): Returns an iterator pointing to the past-the-end element of the vector.
  8. insert(): Inserts an element at a specified position in the vector.
  9. erase(): Removes an element from a specified position in the vector.
  10. resize(): Resizes the vector to a specified size.
  11. swap(): Swaps the contents of two vectors.
  12. at(): Returns a reference to the element at a specified position in the vector.
  13. front(): Returns a reference to the first element in the vector.
  14. back(): Returns a reference to the last element in the vector.
  15. 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

Popular posts from this blog

Book review : Complete Guide to Standard C++ Algorithms

Multiplication table in html with python

Differences between references and pointers in C++ with use cases