I have been trying to solve the above problem for a friend, everytime the last element of the vector gets removed although I feel that its size should increase dynamically after insertion. Here's the Code:
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
void display(vector<int> arr){
cout<<"Result"<<endl;
for(auto &p: arr){
cout<<p<<endl;
}
}
void indsert(vector<int> arr, int size, int element, int ind){
for(int i=size 1; i>=ind; i--)
arr[i] = arr[i-1];
arr[ind] = element;
display(arr);
}
int main()
{
int ind,size,element;
cout<<"Enter the size of the array"<<endl;
cin>>size;
vector<int> arr;
cout<<"Enter the elements of the array"<<endl;
for(int i=0;i<size;i ){
int temp;
cin>> temp;
arr.push_back(temp);
}
cout<<"Enter the element to be inserted"<<endl;
cin>>element;
cout<<"Enter the index"<<endl;
cin>>ind;
indsert(arr, size, element, ind);
return 0;
}
CodePudding user response:
You have two problems.
The first is with the function signature:
void indsert(vector<int> arr, ...)
You pass the vector by value. That means a copy of the vector is made, and that copy is passed to the function.
You can modify this copy as much as you want, but the original vector will still not change.
You need to pass the vector by reference:'
void indsert(vector<int>& arr, ...)
// ^
// Note ampersand here, making this a reference
The second problem is much worse: You seem to assume that you can insert into a vector using the []
operator. That's not what's happening.
Instead you go out of bounds of the vector, which leads to undefined behavior.
You need to explicitly resize the vector, either using insert
, push_back
/emplace_back
, or resize
.
Also remember that since indexes are zero-based, the top-index is the same as the vector size minus one. Using the vector size as index will be out of bounds. Using the vector size plus one is even more out of bounds.
CodePudding user response:
Your code exhibits undefined behaviour. You are accessing arr[size 1]
in a vector arr
of size size
. Such a vector has values at positions 0
up to and including size-1
.
If you want to append a value, use std::vector::push_back()
. Alternatively you can std::vector::resize()
the vector beforehand.
Also, you don't need to pass the size argument because std::vector::size()
will tell you the current size of the vector. Furthermore, as has been pointed out to you, pass the vector by reference to avoid copying data for no reason.