Vectors - Separate negatives and positives

2

I have to make a program that receives a vector of 8 numbers and returns 2 vectors, the first with the positive numbers of the 8-position vector, and the second with the negative numbers.

The problem is that I do not know how to use VECTOR, since the last two vectors should not have definite capacity ..

This is causing my second vector to "lose" somehow the positions of the positive numbers that are typed first. I do not know if it was clear.

If you can help, I would be grateful.

MY CODE:

using namespace std; int main () {

vector<int> vet(8);

for(int i=0;i<8;i++){
    cin>>vet.at(i);
}

vector<int> vet1(8);
vector<int> vet2(8);

int cont1=0,cont2=0;

for(int i=0;i<8;i++){
    if(vet.at(i)>=0){
        vet1.at(i)=vet.at(i);
        cont1++;
    }else{
        vet2.at(i)=vet.at(i);
        cont2++;
    }
}

for(int i=0;i<cont1;i++){
    cout<<vet1.at(i)<<" ";
}
cout<<endl;
for(int i=0;i<cont2;i++){
    cout<<vet2.at(i)<<" ";
}

return 0;
    
asked by anonymous 16.06.2017 / 05:01

1 answer

1

The problem is that it is inserting into the vectors in an erroneous way, since it is using the same int to iterate loop and to add in each vector.

For example, if vector 1, -1.67, ...

the vector vet1 will get 1, "garbage", 67, ... and the vector vet2 will get "garbage", - 1, "garbage"

You should use the counters as indices of the storage vectors as follows:

for(int i=0;i<8;i++){
    if(vet.at(i)>=0){
        vet1.at(cont1)=vet.at(i);
        cont1++;
    }else{
        vet2.at(cont2)=vet.at(i);
        cont2++;
    }
}

Tell me later if it worked. = D

    
16.06.2017 / 12:42