Reputation: 971
I'm trying to remove the biggest int element in a vector and insert it into a new vector.I already have an int that represent the highest number in the vector and one that represents the position of that number.
Heres my code:
vector2.push_back(highest);
vector1[highestpos] = vector1[vector1.size()-1];
vector1[vector1.size()-1] = highest;
vector1.pop_back();
But it returns an error. Is there anything wrong with this code?
EDIT::::::HERE IS MORE OF MY CODE. The error I get is an assertion error that says vector subscript is out of range.
while(vector1.size() > 0)
{
highest = 0;
for (int i = 0; i < vector1.size(); i++)
{
if (vector1[i] > highest)
{
highest = vector1[i];
int highestpos = i;
}
}
vector2.push_back(highest);
vector1[highestpos] = vector1[vector1.size()-1];
vector1[vector1.size()-1] = highest;
vector1.pop_back();
}
Upvotes: 0
Views: 3134
Reputation: 72479
int highestpos = i;
You're just defining a variable inside the loop. It doesn't change the value of the variable outside the loop. Change to:
highestpos = i;
Upvotes: 2
Reputation: 47428
Based on the edit, the problem is that the highestpos
inside the loop, to which the value of i
was assigned, is not the same as the highestpos
outside the loop.
Try a std::cout << highestpos << '\n';
right before vector1[highestpos] = ...
(it may also be helpful to use max_element()
instead of the hand-written loop to determine the highest value and vector1.erase()
to delete from the vector, although erase may indeed be less efficient than swap+pop_back)
Upvotes: 2