vector parameters in C++ array form

Asked 2 years ago, Updated 2 years ago, 23 views

#include <iostream>
#include <vector>

// // Ascending order
void bubbleSort(std::vector<int> arr) { <--- !
    int length = (int)arr.size();
    int temp = 0;

    for (int i = 0; i < length; ++i) {
        for (int j = 0; j < length - (1 + i); ++j) {
            if (arr[j] > arr[j + 1]) {
                temp = arr[j + 1];
                arr[j + 1] = arr[j];
                arr[j] = temp;
            }
        }
    }
}

int main() {
    std::vector<int> inputArr = {5, 3, 1, 2, 7, 6, 4};
    bubbleSort(inputArr);

    for (int i : inputArr) {
        std::cout << i << " ";
    }
    std::cout << "\n";

    return 0;
}

Running this code ensures that the arr array is aligned well within the bubbleSort() function, but it remains unordered in the main() function.

By any chance, does the parameter arr not refer to the same vector as inputArr, but only the element value is assigned a new vector?

In Java, when executing the same code, the parameters refer to the same array as inputArr, so there is no need for a separate function return statement...I'm a little confused.

c++

2022-09-21 16:18

1 Answers

You've diagnosed it correctly.
In languages such as JAVA and C#, variables basically act as references, so even if you write it like that, you get the desired result.
However, in C++, you must use the '&' symbol to receive it as a reference because that would result in a copy (calling the copy generator).

// Ascending order
void bubbleSort(std::vector<int>& arr) {
    int length = (int)arr.size();
    int temp = 0;

    for (int i = 0; i < length; ++i) {
        for (int j = 0; j < length - (1 + i); ++j) {
            if (arr[j] > arr[j + 1]) {
                temp = arr[j + 1];
                arr[j + 1] = arr[j];
                arr[j] = temp;
            }
        }
    }
}


2022-09-21 16:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.