int vectorLength = 10;
vector<int> bothSigns(vectorLength);
cout << " Input vector: ";
for (int i = 0; i < vectorLength; i = i + 1)
{ bothSigns[i] = rand()%201 - 100;
cout << "\t" << bothSigns[i];
}
cout << "\n";
vector<int> noNegs;
////////////////////////////////////////////
noNegs = bothSigns;
for(int i = 0; i < vectorLength; i = i + 1)
{
if(noNegs[i] < 0)
{
int j = i;
while(noNegs[j] < 0)
{
j = j + 1;
cout << endl << endl << "I: " << i << endl << "J: " << j << endl;
}
for(j; j < vectorLength - 1; j = j + 1)
{
noNegs[i] = noNegs[j];
}
noNegs.pop_back();
}
}
I'm getting incorrect outputs, obviously. Basically my idea of the code was look at each element, and if that element was less than 0, you look for the next non-neg element and replace it with that. Maybe my code doesn't do what I think? Is there a better way of going about this all together?
> the only vector class function i can use is pop_back and push_back.
That is naive.
1. Before we can use pop_back() at all, we need to make sure that the vector is not empty.
2. If we can't use any other function, then we also can't examine the value of any element in the vector.
How then are we going to know if a value is negative?
Using empty() and back() in addition to pop_back() and push_back():