To declare vector in C++, need to include
#include <vector>
using namespace std;
//Declare an empty vector of integers
vector<int> myVector;
//Declare a vector of strings and initialize it with values
vector<string> myStringVector = {"apple","banana","orange"};
//Declare a vector with specific initialize size
vector<double> myDoubleVector(10);
===========================================================
Operations
Adding Elements to a Vector
1) push_back()
This function adds an element to the end of the vector.
eg
v.push_back("orange");
v.insert(v.begin() + 2, "peach");
=========
2)Accessing Elements []
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v = {1, 2, 3, 4, 5};
// Use at() to access the element at index 2.
int element = v.at(2);
cout << element << endl;
// Use [] to access the element at index 3.
element = v[3];
cout << element << endl;
// Try to access the element at index 6.
// This will throw an out_of_range exception.
try {
element = v.at(6);
} catch (out_of_range& e) {
cout << "Index out of range: " << e.what() << endl;
}
return 0;
}
3) Removing Elements
a) pop_back()
//Removes the last element from the vector
myVector.pop_back(); // Removes the last element from the vector
b) Using a range based `for` loop
for (const auto& element : myVector) {
// Access and process each element using 'element'
}
myVector.clear(); // Removes all elements from the vector
- Pass by reference: When passing a vector to a function, you can pass it by reference to avoid making a copy of the entire vector.
Initializing vector with a range of values:
- Using the constructor with iterators: You can initialize a vector with values from another container or a range of elements.cpp
std::vector<int> anotherVector(myVector.begin(), myVector.begin() + 5);
orting a vector with a custom comparison function or lambda expression:
cppstd::sort(myVector.begin(), myVector.end(), [](const auto& a, const auto& b) {
return a > b; // Custom sorting logic (descending order)
});
Using vector as a multidimensional array:
- You can create a vector of vectors to represent a 2D array.cpp
std::vector<std::vector<int>> matrix(rows, std::vector<int>(cols, 0));