I have a simple class that contains a fixed size int array. The class can initialize the array, shuffle it, and print it:
#include <iostream>
#include <algorithm>
#include <random>
using namespace std;
class Array
{
public:
int array[8];
void init() {
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
array[4] = 5;
array[5] = 6; array[6] = 7;
array[7] = 8;
}
void shuffle()
{
random_device rd;
mt19937 g(rd());
std::shuffle(
&array[0],
&array[8],
g
);
}
void show()
{
for (int i = 8 - 1; i >= 0; i--)
cout << array[i] << "\n";
}
};
int main()
{
Array arr;
arr.init();
arr.shuffle();
arr.show();
return 0;
}
My goal is to implement bubble sort in a separate function outside the class.
What is the correct way to sort the array from outside the class while keeping the class structure as it is?
init, that's what constructors (and initializers) are for. you can doint array[8]{1,2,3,4,5,6,7,8};And std::shuffle should be called asstd::shuffle(std::begin(array), std::end(array))and in general I think your array should be astd::vector<int>so it can be any size later (fixed sizes of arrays are very inflexible), and then you can initialize it usingstd::vector<int> array{1,2,3,4,5,6,7,8};, and your shuffle becomesstd::shuffle(array.begin(), array.end());. Also unlearn to useusing namespace std;.std::arrayclass template, which was introduced in C++11. After 14 years and a few months, it is time to move on and quit using C-style arrays.