-6

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?

New contributor
dawidg81 is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
3
  • you can find answer here stackoverflow.com/questions/21991369/bubble-sort-c. Commented Nov 16 at 17:42
  • Just some feedback on your use of C++ : You don't need an init, that's what constructors (and initializers) are for. you can do int array[8]{1,2,3,4,5,6,7,8}; And std::shuffle should be called as std::shuffle(std::begin(array), std::end(array)) and in general I think your array should be a std::vector<int> so it can be any size later (fixed sizes of arrays are very inflexible), and then you can initialize it using std::vector<int> array{1,2,3,4,5,6,7,8}; , and your shuffle becomes std::shuffle(array.begin(), array.end());. Also unlearn to use using namespace std;. Commented Nov 17 at 6:04
  • Even if the array will forever be of size 8, use the C++ std::array class 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. Commented 2 days ago

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.