简体   繁体   English

C ++将向量传递给排序函数实际上并未对其进行排序

[英]C++ Passing vector to a sort function does not actually sort it

I have a function prototype: 我有一个函数原型:

void bubbleSort(std::vector<float>);

and an implementation: 和一个实现:

void bubbleSort(std::vector<float> inputVector)
{
    std::cout << "Executing bubble sort." << std::endl;
    int pass;
    int comparisons;
    float hold;

    for (pass = 1; pass < VECSIZE; pass++)
    {
        for (comparisons = 0; comparisons < VECSIZE - 1; comparisons++)
        {
            if (inputVector[comparisons] > inputVector[VECSIZE + 1])
            {
                hold = inputVector[comparisons];
                inputVector[comparisons] = inputVector[comparisons + 1];
                inputVector[comparisons + 1] = hold;
            }
        }
    }

    for (int i = 0; i < VECSIZE; i+=10)
    {
        std::cout << "Element " << i << " is " << inputVector[i] << std::endl;
    }
    return;
}

It's called from this main : 这是从这个main

#define VECSIZE 1000
int main(void)
{
    std::string fileName = "randFloats.txt";
    std::cout << "Processing " << fileName << "..." << std::endl;
    std::ifstream fileInput(fileName);

    //vector to hold the floats
    std::vector<float> fltVector(VECSIZE);

    if(fileInput.is_open())
    {
        std::string line;
        int i = 0;
        while(getline(fileInput, line))
        {
            fltVector[i] = (::atof(line.c_str()));
            i++;
        }
    }
    bubbleSort(fltVector);
}

Basically, the main function takes a 1000-element-long file of floats, reads it into a vector structure, and sends it to a function to be sorted. 基本上,main函数接收一个1000个元素长的float文件,将其读入向量结构,然后将其发送给要排序的函数。 It's been far too long since I've done any work with pointers in a language, so when I pass the std::vector<float> to the bubbleSort function, I'm finding that it's not outputting a sorted vector. 自从我完成了某种语言中的指针的任何工作以来,已经太久了,所以当我将std::vector<float>传递给bubbleSort函数时,我发现它没有输出排序的向量。 How would I pass the vector to the function in order to get it sorted? 我如何将向量传递给函数以便对其进行排序?

Bubble sort is needed here... I'm just doing this for my own purposes to refresh myself with memory management. 这里需要冒泡排序...我只是出于自己的目的执行此操作,以通过内存管理刷新自己。

Here's an input file for testing: 1000 Line file 这是用于测试的输入文件: 1000行文件

There are several problems. 有几个问题。 Some of them are: 他们之中有一些是:

  1. The vector is passed by value, not by reference, so you're modifying the local copy. 向量是通过值而不是通过引用传递的,因此您正在修改本地副本。

  2. You're accessing out-of-bounds data: inputVector[VECSIZE + 1] does't exist. 您正在访问越界数据: inputVector[VECSIZE + 1]不存在。

  3. Use inputVector.size() instead of using the VECSIZE macro. 使用inputVector.size()而不是使用VECSIZE宏。 Ideally, use the begin() , end() and iterators. 理想情况下,请使用begin()end()和迭代器。

  4. There's no need for VECSIZE at all. 完全不需要VECSIZE Simply append to the vector in the reading loop: 只需在阅读循环中附加到向量即可:

     while(getline(fileInput, line)) fltVector.push_back(::atof(line.c_str())); 
  5. "It's been far too long since I've done any work with pointers in a language" It's C++, you can do a lot without ever touching a pointer directly :) “自从我完成了某种语言中的指针的任何工作以来,已经太久了”这是C ++,您可以做很多事情而无需直接触摸指针:)

You are passing the vector to your function by value: 您正在按值将向量传递给函数:

void bubbleSort(std::vector<float>);

Which means you are sorting a copy of the vector, not the actual vector. 这意味着您正在排序向量的副本,而不是实际的向量。 You need to change your function signature to 您需要将功能签名更改为

void bubbleSort(std::vector<float>&);
                                  ^ -- note the pass by reference

Another problem you have is that you are invoking Undefined Behavior: 您遇到的另一个问题是您正在调用未定义行为:

if (inputVector[comparisons] > inputVector[VECSIZE + 1])
                                           ^^^^^^^^^^^ -- accessing an element 2 beyond 

the size of your array, and you are not swapping the items you are comparing. 数组的大小,并且您不交换要比较的项目。

I think what you wanted to do is: 我认为您想做的是:

bool swapped = false;
do
{
    swapped = false;
    for (int j = 0; j < inputVector.size() - 1; ++j)
    {
        if (inputVector[j + 1] > inputVector[j])
        {
            std::swap(inputVector[j + 1], inputVector[j]);
            swapped = true;
        }
    }
} while (swapped);

Notice the problems this fixes: 请注意此修复的问题:

if (inputVector[comparisons] > inputVector[VECSIZE + 1]) // UB
{
    hold = inputVector[comparisons];
    inputVector[comparisons] = inputVector[comparisons + 1]; // not swapping elements you compared!
    inputVector[comparisons + 1] = hold; // same problem as above!
}

Each time you put the highest element at the end, so there's no need to compare to the end of the array each time: 每次将最高元素放在末尾,因此无需每次都与数组末尾进行比较:

bool swapped = false;
int k = inputVector.size();
do
{
    k--;
    swapped = false;
    for (int j = 0; j < k; j++)
    {
        if (inputVector[j] > inputVector[j + 1])
        {
            std::swap(inputVector[j], inputVector[j + 1]);
            swapped = true;
        }
    }
} while (swapped);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM