-3

we have to merge the two vector and i am do so but i do not get the output from the give code ...please help me to find out the problem..

#include<iostream>
#include<vector>
using namespace std;
int main()
{
  vector<int> v1={1,2,4,5};
  vector<int> v2={10,9,6,3};
   vector<int> v3;
   int i=0;
        for(int value1:v1)
        {
            v3[i]=value1;
            i++;
        }
        for(int value2:v2)
        {
            v3[i]=value2;
            i++;
        }
        for(int value3:v3)
        {
           cout<<value3<<" ";
        }
        
}

a correct code for my question

273K
  • 29,503
  • 10
  • 41
  • 64
  • Looks like you want [`std::vector:::push_back`](https://en.cppreference.com/w/cpp/container/vector/push_back). – Jerry Coffin Jun 11 '23 at 20:34
  • I looked at the duplicate Q&A but it doesn't seem to answer your question about what the problem with your code is. I've tried to explain it in my answer below. Does that answer your question or do you want me to clarify it further? – Ted Lyngmo Jun 12 '23 at 19:19

1 Answers1

4

v3 is empty so v3[i]=...; is out of bounds. You need v3.push_back(value) or v3.emplace_back(value) to add elements to it. Example:

std::vector<int> v3;
v3.reserve(v1.size() + v2.size());

for(int value : v1) {
    v3.push_back(value);
}
for(int value : v2) {
    v3.push_back(value);
}

A simpler way would be to copy construct v3 from v1 and then use the member function insert to add all the elements from v2 at the end of v3 at once:

std::vector<int> v3 = v1;
v3.insert(v3.end(), v2.begin(), v2.end());

Demo

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108