c ++向量操作 [英] c++ vector manipulation
本文介绍了c ++向量操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的代码:
vector2.push_back
vector1 [highestpos] = vector1 [vector1.size() - 1];
vector1 [vector1.size() - 1] = highest;
vector1.pop_back();
但它返回一个错误。这个代码有什么问题吗?
EDIT ::::::这里是我的代码。我得到的错误是一个声明错误,说向量下标超出范围。
while(vector1.size()> 0)
{
highest = 0;
for(int i = 0; i {
if(vector1 [i] b $ b {
highest = vector1 [i];
int highestpos = i;
}
}
vector2.push_back(highest);
vector1 [highestpos] = vector1 [vector1.size() - 1];
vector1 [vector1.size() - 1] = highest;
vector1.pop_back();
}
解决方案
int highestpos = i;
你只是在循环中定义一个变量。它不会更改循环外部的变量的值。更改为:
highestpos = i;
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();
}
解决方案
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;
这篇关于c ++向量操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文