So I've seen questions on here about how to pass through a std::vector::iterator
as an argument parameter for a function, however, those solutions don't seem to apply when dealing with std::array
s. What I want to use this for is a Quick Sort function that takes in std::array
s. This is the code I have thus far:
#include <iostream>
#include <array>
#include <random>
#include <time.h>
using namespace std;
// Function declarations.
template<size_t SIZE>
void QuickSort(array<int, SIZE> arrayName, array<int, SIZE>::iterator low, \
array<int, SIZE>::iterator high);
template<size_t SIZE>
auto Partition(array<int, SIZE> arrayName, array<int, SIZE>::iterator low, \
array<int, SIZE>::iterator high);
// Main function.
int main()
{
// Set rand() seed to current time (NULL).
srand((unsigned)time(NULL));
// Declare array "randomNumberArray" of size #.
static array<int, 5> randomNumerArray = { 0 };
// Initialize array with random numbers.
for (auto it = randomNumerArray.begin(); it != randomNumerArray.end(); ++it)
*it = rand() % 500 + 1;
/*
This is where I would want to use the Quick Sort function to sort the array and
then print it out to the console.
*/
cin.get();
return 0;
}
// Function definitions. Standard Quick Sort syntax.
template<size_t SIZE>
void QuickSort(array<int, SIZE> arrayName, array<int, SIZE>::iterator low, \
array<int, SIZE>::iterator high)
{
if (low < high) {
// Function definition to be finished.
}
return;
}
/* Partition() returns auto to easily return the variable type I need
which is a Random Access Iterator.*/
template<size_t SIZE>
auto Partition(array<int, SIZE> arrayName, array<int, SIZE>::iterator low, \
array<int, SIZE>::iterator high)
{
auto pivot = high;
auto i = (low - 1);
for (auto j = low; j < pivot; ++j) {
if (*j < *pivot) {
int tempNum = 0;
tempNum = *(++i);
*i = *j;
*j = tempNum;
}
}
int tempNum = 0;
tempNum = *(++i);
*i = *pivot;
*pivot = tempNum;
return i;
}
As you can see, I've managed how to fit most of the pieces to this puzzle, I just don't know how to pass through low
and high
, which are meant to be of Random Access Iterator types, as argument parameters to the functions. Using std::array<type, size>::iterator
doesn't work as it's not a type. I've also tried to add #include <iterator>
, but to no avail.
EDIT: To clarify, it's not the value contained within the index that I'm trying to pass through, but the index itself which changes with each recursion.
You need to use typename
to hint to the compiler that iterator
is a type
template<size_t SIZE>
void QuickSort(typename array<int, SIZE>::iterator low,
typename array<int, SIZE>::iterator high);
But that won't work either since SIZE
is in a nondeduced context. It would be better to just make an iterator
as a template
template<typename RandomIt>
void QuickSort(RandomIt low, RandomIt high);