How do I insert elements of a first vector into another second vector, at a given user position? and still print step by step

Asked

Viewed 91 times

0

Entradas - Tam do 1 vetor:5/
Elementos do 1 vetor: 1 2 3 4 5 /
Elementos do 2 vetor: 6 7 8 9 10/
Pos a ser inserida: 1

Saida- 
6 1 7 8 9 10 /
6 2 1 7 8 9 10 /
6 3 2 1 7 8 9 10 /
6 4 3 2 1 7 8 9 10/ 
6 5 4 3 2 1 7 8 9 10

NOTE: The size of the second vector should be twice the size of the first vector, but the second vector will only have half its size occupied.

I’m a little lost, so far this is my code:

#include <iostream>
using namespace std;

int main(){ 
  int tam1, tam2, pos;
  cin>>tam1;
  int vet1[tam1];
  for(int i=0; i<tam1; i++){
    cin>>vet1[i];
  }
  tam2=tam1*2;
  int  vet2[tam2],vetaux[tam2];
  for(int i=0; i<(tam2/2); i++){
    cin>>vet2[i];
    vetaux[i]=vet2[i];
  }
  cin>>pos;
  for(int i=0; i<tam2; i++){
    vet2[pos]=vet1[i];  
    vet2[pos+1]=vetaux[pos];
    cout<<vet2[i]<<" ";
    pos++;
  }
}
  • What is the problem you are having with your code? Some error? maybe unexpected result (which)?

1 answer

0

I don’t think you can create vectors with a variable, I think only with constants or you need to dynamically allocate memory to the vector. Using new or malloc.

Here is an example code using vector that will facilitate insertion and allocation operation.

#include <iostream>
#include <vector>
using namespace std;
int main(){
    vector<int> vetor1;
    vector<int> vetor2;
    int tam1;
    cout<<"digite o tamanho do vetor 1: ";
    cin>>tam1;
    for(int i=0;i<tam1;i++){
        int aux;
        cout<<endl<<"digite o numero para a posicao "<<i<<" do primeiro vetor: ";
        cin>>aux;
        vetor1.push_back(aux);
    }
    for(int i=0;i<tam1;i++){
        int aux;
        cout<<endl<<"digite o numero para a posicao "<<i<<" do segundo vetor: ";
        cin>>aux;
        vetor2.push_back(aux);
    }
    cout<<"saida"<<endl;
    for(int i=0;i<tam1;i++){
        vetor2.insert(vetor2.begin()+1,vetor1[i]);
        for(int j=0;j<vetor2.size();j++){
            cout<<vetor2[j];
        }
        cout<<endl;
    }
    return 0;
}

links that can help:
http://www.cplusplus.com/reference/vector/vector/
http://www.cplusplus.com/reference/new/operator%20new[]/
http://www.cplusplus.com/reference/cstdlib/malloc/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.