矢量给出不准确的输出

Vector giving inaccurate output

本文关键字:输出 不准确      更新时间:2023-10-16
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);        
}