Saturday, June 3, 2023

Vector in C++

 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) erase()
//Removes an element at a specific position or a range of elements

myVector.erase(myVector.begin() + 1);
myVector.erase(myVector.begin() + 2, myVector.begin() + 4); //Removes index from 2 to 4; (exclusive)


4) Getting information about the vector

a) size()
//Retrieves the number of elements in the vector.
b)empty()
//This function checks if the vector in empty.

===================================================================

Other General Info

1) Iterating over a vector

a) for loop
for(size_t i = 0; i < myVector.size(); ++i)
{
    // Access and process each element using myVector[i];
}

b) Using a range based `for` loop

for (const auto& element : myVector) {

    // Access and process each element using 'element'

}

2) Clearing the vector:

          myVector.clear();  // Removes all elements from the vector

3) Sorting 

sort(myVector.begin(), myVector.end());  // Sorts the vector in ascending order

4)Find elements

auto it = std::find(myVector.begin(), myVector.end(), targetValue);  // Searches for 'targetValue'
if (it != myVector.end()) {
    // Element found
}


5)Using vector as function parameters:
  • 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.

void myFunction(const std::vector<int>& vec) {
    // Access and process the vector elements
}

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);  

std::vector<int> myVector(5, 42);  // Resizes the vector to have 5 elements, each initialized to 42

orting a vector with a custom comparison function or lambda expression:

cpp
std::sort(myVector.begin(), myVector.end(), [](const auto& a, const auto& b) { return a > b; // Custom sorting logic (descending order) });
std::reverse(myVector.begin(), myVector.end()); /


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));