矢量给出不准确的输出
Vector giving inaccurate output
vector<int> vect;
vector<int> sorted;
vect.push_back(5);
vect.push_back(3);
vect.push_back(7);
vect.push_back(2);
vect.push_back(9);
vect.push_back(6);
//Print vector elements
for (int x=0; x<vect.size(); x++)
cout << vect[x] << endl;
int min = 99999, idx=0;
while (vect.size() > 0)
{
for (int x=0; x<vect.size(); x++)
{
if (vect[x] < min)
{
min = vect[x];
idx = x;
}
}
cout << "Min index: " << idx << endl;
sorted.push_back(vect[idx]);
vect.erase(vect.begin()+idx);
}
for (int x=0; x<sorted.size(); x++)
cout << sorted[x] << endl;
我想通过将排序后的数字存储在vector<int> sorted
中来对整数向量进行排序。但是程序总是在遇到未知的程序错误后中途终止。
The only output I get is:
5
3
7
2
9
6
Min Index: 3
Min Index: 3
Min Index: 3
Min Index: 3
<Program Terminated At This Point>
我已经做了几个小时了,我不知道为什么我总是把索引3作为最小的数字。我在实现中做错了什么?我已经考虑了几个小时了,我的逻辑似乎是正确的。
在你的第一次测试中,它发现min = 2。然后擦除索引为3的2。然后再来一遍,除了没有比2小的。所以它的下标仍然是3,然后把它擦掉。这个过程一直持续到你的物品不再超过3件为止。然后操作失败,因为vector太小,无法擦除索引3。
在for循环前将min重新设置为99999
正如Blastfurnace用户指出的那样。我忘了重置最小值。这应该能解决问题。
int idx=0;
while (vect.size() > 0)
{
int min = 99999;
for (int x=0; x<vect.size(); x++)
{
if (vect[x] < min)
{
min = vect[x];
idx = x;
}
}
cout << "Min index: " << idx << endl;
sorted.push_back(vect[idx]);
vect.erase(vect.begin()+idx);
}
相关文章:
- VS Code C++:不准确的系统包括路径错误(wchar.h,boost/lambda/lambda.hpp)
- GDB 断点在 Mac 上是不准确的
- 为什么Qt Creator的应用程序输出不能从spdlog记录器打印
- Windows 10命令提示符的输出不正确
- 为什么数组到指针的输出不相关
- 我的求解(字符串 a、字符串 b)的输出与随机哈希中的预期输出不匹配
- 程序的输出不是来的,它是一个链表程序
- cout 打印不准确的结果,printf 打印准确的结果
- C++ - 为什么 unicode 输出不正确?
- 存储和打印字符,但输出不是预期的
- 两种情况下的输出不应该相同吗?
- 我的叉子输出不正确
- Opengl 4 调试输出不起作用
- C++中的 Json:将数字解析为字符串以避免浮点不准确
- 为什么OpenCV Templete匹配函数根本不准确
- bcdedit 文件输出不起作用,但其他命令可以
- u张量模型输出不等于预期输出
- 输出不是我想要C++的
- LIBCURL:网络上传下载速度的输出不准确
- 矢量给出不准确的输出