Vector 通过引用对向量的修改不持久

Vector 通过引用对向量的修改不持久,vector,pass-by-reference,Vector,Pass By Reference,我正在尝试实现一个排序算法,其中一个向量被传递到一个函数中并进行修改。但是,打印时,更改不会持续。请忽略未实现完整simpleSort的事实(目标是实现快速排序)。这个问题与向量行为有关。我签出的一些资源是: 我想我在做他们所说的,但我遗漏了一些基本的东西。 下面是代码示例: #include "stdafx.h" #include <iostream> #include <vector> void simpleSort(std::vector<float>

我正在尝试实现一个排序算法,其中一个向量被传递到一个函数中并进行修改。但是,打印时,更改不会持续。请忽略未实现完整simpleSort的事实(目标是实现快速排序)。这个问题与向量行为有关。我签出的一些资源是:

我想我在做他们所说的,但我遗漏了一些基本的东西。 下面是代码示例:

#include "stdafx.h"
#include <iostream>
#include <vector>

void simpleSort(std::vector<float>& theta , int);
void printArray(std::vector<float> & arr, int size)

int main()
{
    std::vector<float> theta;
    theta.push_back(10);
    theta.push_back(-5);
    theta.push_back(-3);

    simpleSort(theta, theta.size()-1);
    printf("Sorted array: \n");
    printArray(theta, theta.size());
    system("pause");

    return 0;
}

void simpleSort(std::vector<float>& theta, int n)
{
    for (int i = 0; i < n ; ++i)
    {
        if (theta[i] < theta[i + 1]) std::swap(theta[i], theta[i + 1]);
    }
}

void printArray(std::vector<float> & arr, int size)
{
    int i;
    for (i = 0; i < size; i++)
        printf("%d ", arr[i]);
    printf("\n");
}
#包括“stdafx.h”
#包括
#包括
void simpleSort(std::vector&theta,int);
void printary(std::vector&arr,int size)
int main()
{
向量θ;
θ推回(10);
θ.向后推_(-5);
θ推回(-3);
simpleSort(θ,θ.size()-1);
printf(“排序数组:\n”);
打印数组(θ,θ.size());
系统(“暂停”);
返回0;
}
void simpleSort(标准::向量和θ,int n)
{
对于(int i=0;i
可以看出,输入是{10,-5,-3}。在main中打印结果时得到的结果是{0,0,0}。但是如果我在函数本身中打印向量,我得到{-5,-3,10}


我认为我使用“&”通过引用正确地传递了向量,但我想情况并非如此。

您唯一的问题是在printArray中。您正在使用“%d”,但您的向量是一个浮点数,因此您需要使用%f。

您是救世主!我非常专注于向量部分,我从来没有去质疑打印部分。我想我仍然在测试中使用整数。