How to swap values in a vector in C++

In this tutorial, we are going to learn how to swap values in a vector in C++. This topic is quite useful and is used often while working with vectors. A step-by-step process will help you understand how to understand the code. Vectors are the same as dynamic arrays and have dynamic size. We can change their size even after declaration.

Swap values in a vector in C++

Let us begin with our tutorial, but first, we must have a good understanding of vectors and the in-built functions of vectors in vector stl.

Here are some useful links you might want to check out before we begin this tutorial.

First, we are going to create a function to swap values at any two indexes in the vector named “swapvectorelements“. We will pass indexes and the vector as parameters in the function.

#include <bits/stdc++.h>
using namespace std;

void swapvectorelements(int index1,int index2,vector<int> &vec){

  int x=vec[index1];
  vec[index1]=vec[index2];
  vec[index2]=x;
  //swap(vec[index1],vec[index2]);
}

We can also use the swap function instead of swapping them by ourselves. We have added it in the comments starting with //.

Next, we will take an input vector v and pass it in the function named “swapvectorelements” in the main function. We will be swapping 1st and last index that is 0 and 4. You can swap any indexes.

int main(){

  vector<int> v={1,2,3,4,5};
  //swapping first(0) and last(4) indexes
  swapvectorelements(0,4,v);

  cout<<"After swaping elements in vector:"<<endl;
  
  for(int i=0;i<v.size();i++){
    cout<<v[i]<<" ";
  }

 

Here is the full code:

#include <bits/stdc++.h>
using namespace std;

void swapvectorelements(int index1,int index2,vector<int> &vec){

  int x=vec[index1];
  vec[index1]=vec[index2];
  vec[index2]=x;
  /*swap(vec[index1],vec[index2]);*/
}

int main(){

  vector<int> v={1,2,3,4,5};
  /*swapping first(0) and last(4) indexes*/
  swapvectorelements(0,4,v);

  cout<<"After swaping elements in vector:"<<endl;
  
  for(int i=0;i<v.size();i++){
    cout<<v[i]<<" ";
  }
}

 

Output:

After swaping elements in vector:
5 2 3 4 1

Leave a Reply

Your email address will not be published. Required fields are marked *