【发布时间】:2019-11-04 17:48:17
【问题描述】:
请告诉我我的方法有什么问题。 当我运行代码时,计算需要很长时间才能看到结果。
#include <iostream>
#include <vector>
using namespace std;
vector<int> vec;
vector<int> sort(vector<int> x) {
vector<int> y;
int i = 1;
reset:for(i = 1; i <= x.size(); i++){
for (int j = 1; j <= x.size();) {
if (j == i) {
j++;
}
else {
if (x[i - 1] > x[j - 1]) {
j++;
}
else {
i++;
goto reset;
}
}
}
y.push_back(x[i - 1]);
x.erase(x.begin() + i - 1);
}
return y;
}
int main(){
vec.push_back(5);
vec.push_back(9);
vec.push_back(3);
vec.push_back(6);
vec.push_back(2);
for (int i = 1; i <= vec.size(); i++) {
cout << sort(vec)[i-1] << " ";
}
}
我将这个给定的 5 个整数序列按降序排序。请帮忙。
我的计划是在整个向量 x 中搜索最大的整数,然后将其移动到向量 y 并重复该过程。
【问题讨论】:
-
每次你想打印一个对性能没有帮助的元素时,你都在对向量进行排序。
-
你增加
i,然后调用goto reset;-> 那会去哪里,在goto之后i会发生什么? -
如果花费的时间太长,我认为您的意思是它永远不会完成并且它陷入了无限循环。在调试器中单步执行,您将确切地看到该循环在做什么。
-
请查看编辑以了解我想要做什么。
-
有什么理由不使用
std::sort?
标签: c++