使用向量而不是数组从最小到最大对数字进行排序C++

Sort numbers from smallest to biggest using vector instead of array in C++

本文关键字:数字 C++ 排序 向量 数组      更新时间:2023-10-16

所以我是C++新手,我正在研究这个问题,它要求我使用向量而不是数组对插入排序的数字进行排序。我已经使用数组进行排序,然后我只是在代码中进行了一些小的更改,试图解决矢量问题。这是我现在得到的:

#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;
void fill_array(vector<int> v,int size, int& number_used);
void sort(vector<int> v, int number_used);
void swap_values(int& v1, int& v2);
int main()     
{
    cout << "This program sorts numbers from lowest to highest.n";
    vector<int> sample;
    int number_used;
    fill_array(sample,10,number_used);
    sort(sample,number_used);
    cout << "In sorted order the numbers are:n";
    for (int index =0; index < number_used; index++)
        cout << sample[index] << " ";
    cout << endl;
    system("PAUSE");
    return 0;
}

void fill_array(vector<int> v, int size, int& number_used)
{ 
         cout << "This program sorts numbers from lowest to highest.n";
         cout << "Enter up to " << size << " nonnegative whole number.n"
              << "Mark the end of the list with a negative number.n";
         int index = 0,next; 
         cin >> next;
         while ((next >= 0) && (index < size))
         {
               v[index]=next;
               index++;
               cin >> next;
         }
         number_used = index;
}
void sort(vector<int> v, int number_used)
{
     int index;
     int index_backwards;
    for(index=0;index<number_used;index++)
    {
       for(index_backwards=index;index_backwards>0;index_backwards--)
       {
           if(v[index_backwards-1]>v[index_backwards])
           {
               swap_values(v[index_backwards-1], v[index_backwards]);
           }
       }
    }
}

void swap_values(int& v1, int& v2)
{
     int temp;
     temp = v1;
     v1=v2;
     v2=temp;
}

它很好地完成了编译。但是当我运行它时,在我输入数字并按回车键后,程序就会停止运行并关闭。有人可以帮助我解决问题吗?谢谢。

当你像数组一样使用std::vector时,你就是在滥用它们。在向量的"一侧"传递大小是没有意义的,因为向量保持自己的大小。

你应该通过引用传递你的向量,使用它的 size() 成员函数而不是count(),并使用 push_back() 向其添加值。函数的签名应如下所示:

// Pass by ref; no "size", no "number_used"
void fill_array(vector<int> &v);
// Pass by ref; no "number_used"
void sort(vector<int> &v);

在实现中使用v.push_back(next)而不是v[index]=next fill_array

fill_array函数中,您没有正确添加已输入到向量 v 的值。您应该将v[index] = next更改为 v.push_back(next)

你可以改变

v[index]=next;

v.push_back(next);

或者你可以像 v[index]=next 一样保留它;并在声明向量时分配内存。

vector<int> sample(10);  // This allocates 10 element. DON'T use push_back in this case

当你走push_back路并且你知道你的向量最终将具有的元素数量时,在开始填充向量之前调用 reserve 是一件好事。所以你想做:

vector<int> sample;
sample.reserve(10);
...
// Now fill it with push_back

储备将设置容量或矢量(容量始终>=到您的矢量大小)。当容量==到大小时,对push_back(或任何插入元素的函数)的调用将需要重新分配内存,然后你会得到一些性能影响。使用储备将防止这种情况发生。

此外,拥有自己的交换功能是没有意义的。标准库已经有一个交换功能。而不是

swap_values(v[index_backwards-1], v[index_backwards]);

你可以做

std::swap(v[index_backwards-1], v[index_backwards]);