Vector Initialization: You can initialize a vector with a specified size and an initial value using the following syntax:
vector<int> v(size, initial_value);
For example:
vector<int> v(5, 0); // initialize a vector of size 5 with all elements set to 0
Vector Size: You can get the number of elements in a vector using the
size()
method:int num_elements = v.size();
Pushing Elements to the Back: You can push a new element to the back of a vector using the
push_back()
method:v.push_back(element);
For example:
vector<int> v; v.push_back(5); // Add an element with value 5 to the back of the vector
Accessing Elements: You can access the elements of a vector using their index, starting from 0:
int element = v[index];
For example:
vector<int> v = {1, 2, 3, 4, 5}; int element = v[2]; // Access the element with index 2, which is 3
Finding the Largest Element: You can find the largest element in a vector using the
max_element()
function from the <algorithm>
library:auto it = max_element(v.begin(), v.end()); int largest_element = *it;
For example:
vector<int> v = {5, 10, 3, 7, 1}; auto it = max_element(v.begin(), v.end()); // Find the iterator to the largest element int largest_element = *it; // Get the value of the largest element
Sorting a Vector: You can sort the elements of a vector using the
sort()
function from the <algorithm>
library:sort(v.begin(), v.end());
For example:
vector<int> v = {5, 10, 3, 7, 1}; sort(v.begin(), v.end()); // Sort the vector
Finding the Lower Bound: You can find the iterator to the first element that is equal to or greater than a given element using the
lower_bound()
function from the <algorithm>
library:auto it = lower_bound(v.begin(), v.end(), element);
For example:
vector<int> v = {1, 2, 3, 4, 5}; auto it = lower_bound(v.begin(), v.end(), 3); // Find the iterator to the first element that is >= 3
Finding the Upper Bound: You can find the iterator to the first element that is greater than a given element using the
upper_bound()
function from the <algorithm>
library:auto it = upper_bound(v.begin(), v.end(), element);
For example:
vector<int> v = {1, 2, 3, 4, 5}; auto it = upper_bound(v.begin(), v.end(), 3); // Find the iterator to the first element that is > 3
Note: Make sure to include the
<algorithm>
header file to use the above functions.PRACTICE QUESTIONS :