Basic Vector Operations in c++

In our last article we learn about What is vector in C++ ? and How it is working ? So in this article we will try to explain different Vector Operations.

Different ways to Initialize a vector in c++


std::vector provides a constructor that accepts the size as an argument. It initialize the vector using default copy constructor. 

Example :
 
// Initialize vector with 3 integers
// Default value of all 3 ints will be 0.
std::vector<int> vecOfInts(3);
 
for(int x : vecOfInts)
 std::cout<<x <<std::endl;

Output:
0
0
0

Initialize a vector by filling similar copy of an element.

It's possible using overloaded constructor, it accepts the size of vector and an element as an argument, then it initializes the vector with second parameter value.

Example :

// Initialize vector to 3 string objects with value "Hi"
std::vector<std::string> vecOfStr(3, "Hi");
 
for(std::string str : vecOfStr)
 std::cout<<str<<std::endl;
Output:
Hi
Hi
Hi

Initialize a vector with an array

Vector provides an overloaded constructor, it accepts array pointer and array size as arguments.

Example:
// Create an array of string objects
std::string arr[] = {"first", "sec", "third"};

// Initialize vector with a string array
std::vector<std::string> vecOfStr(arr, arr + sizeof(arr)/sizeof(std::string));

for(std::string str : vecOfStr)
 std::cout<<str<<std::endl;
Output:

first
sec
third

Initialize a vector with std::list

Vector provides an overloaded constructor, it accepts list start pointer (iterator) and end pointer (iterator).

Example:
// Create an std::list of 3 string objects
std::list<std::string> listOfStr;
listOfStr.push_back("first");
listOfStr.push_back("sec");
listOfStr.push_back("third");


// Initialize a vector with std::list
std::vector<std::string> vecOfStr(listOfStr.begin(), listOfStr.end());

for(std::string str : vecOfStr)
  std::cout<<str<<std::endl;
Output:

first
sec
third

Initializing a vector with an other vector

Vector provides an copy constructor, it accepts other vector as arguments.

Example:
std::vector<std::string> vecOfStr;
vecOfStr.push_back("first");
vecOfStr.push_back("sec");
vecOfStr.push_back("third");

// Initialize a vector with other string object
std::vector<std::string> vecOfStr3(vecOfStr);

for(std::string str : vecOfStr3)
  std::cout<<str<<std::endl;
Output:

first
sec
third

Member Functions of Vector


push_backpush_back() is used for inserting an element at the end of the vector.

Example:
#include <iostream>
#include <vector>

using namespace std;

int main()
{
  vector<int>  v;
  v.push_back(1);  //insert 1 at the back of v
  v.push_back(2);  //insert 2 at the back of v
  v.push_back(4);  //insert 3 at the back of v

  for(vector<int>::iterator i = v.begin(); i != v.end(); i++) {
   cout << *i <<" ";   // for printing the vector
  }
}
Output:
1 2 4

insertinsert(iterator, element) method inserts the element in vector before the position pointed by iterator

Example:
#include <iostream>
#include <vector>

using namespace std;

int main()
{
  vector<int>  v;
  v.push_back(1);  //insert 1 at the back of v
  v.push_back(2);  //insert 2 at the back of v
  v.push_back(4);  //insert 3 at the back of v
  
  vector<int>::iterator i = v.begin();
  v.insert(i,3);
  for(vector<int>::iterator i = v.begin(); i != v.end(); i++) {
   cout << *i <<" ";   // for printing the vector
  }
}
Output:
3 1 2 4

Also insert function is overloaded by third argument count. This count parameter defines how many times the element is to be inserted before the pointed position.

Suppose v.insert(i,2,3); means insert 3 twice, Second parameter as count and third parameter as number which we want to insert.

Also possible to insert other vector elements using below call :
v.insert(i, v2.begin(), v2.end());
Above code will insert the elements from v2.begin() to v2.end() before index pointed by i.

pop_back : used to remove the last element from the vector.

Example:
#include <iostream>
#include <vector>

using namespace std;

int main()
{
  vector<int> v1 {10,20,30,40};
  
  v1.pop_back();  

  vector<int>::iterator it;
  
  for(it = v.begin(); it != v.end(); it++) {
      cout << *it <<" ";   // for printing the vector
  }
}
Output:
10 20 30

eraseerase(itr_pos) removes the element pointed by the iterator itr_pos. erase method can also be overloaded with an extra iterator specifying the end point of the range to be removed, i.e erase(itr_start, itr_end).

Example:
#include <iostream>
#include <vector>

using namespace std;

int main()
{
  vecto<int>v1 {10,20,30,40};
  vector<int>iterator:: it = v.begin();
  
  v.erase(it);   //removes first element from the vector

  v.erase(v1.begin(), v1.end() - 2 )  
  /*removes all the elements except last two */

  for(it = v.begin(); it != v.end(); it++) {
      cout << *it <<" ";   // for printing the vector
  }
}
Output:
30 40

resize: resize(size_type n, value_type value) method resizes the vector to n elements. If the current size of the vector is greater than n then the trailing elements are removed from the vector and if the current size is smaller than n than extra value elements are inserted at the back of the vector.

For example, If the size of the vector is 4 right now, with elements {10, 20, 30, 40} and we use resize method to resize it to size 5. Then by default a fifth element with value 0 will be inserted in the vector. We can specify the data to not be zero, by explicitly mentioning it as the value while calling the resize method.

swap:  It used interchanges value of two vectors.

If we have two vectors vec1 and vec2 and we want to swap the elements inside them, you just need to call vec1.swap(vec2), this will swap the values of the two vectors.

clear: clear() moves all the elements from the vector but do not delete the vector.

size: size() returns the size of the vector.

capacity: capacity() returns actual size allocated for vector.

at: at(i) returns the element at ith index in the vector.

front: front() returns the element at the front of the vector (i.e. leftmost element).

back: back() returns the element at the back of the vector (i.e. rightmost element).


No comments:

Post a Comment