因此,我在这里看到了有关如何将 astd::vector::iterator
作为参数传递给函数的问题,但是,在处理std::array
s 时,这些解决方案似乎并不适用。我想用这个是一个快速排序函数,它接受std::array
s。这是我到目前为止的代码:
#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;
}
正如你所看到的,我已经设法将大部分部分融入这个难题,我只是不知道如何通过low
and high
,它们是随机访问迭代器类型,作为函数的参数参数。usingstd::array<type, size>::iterator
不起作用,因为它不是一种类型。我也尝试添加#include <iterator>
,但无济于事。
编辑:为了澄清,这不是我试图通过的索引中包含的值,而是索引本身随着每次递归而变化。
您需要使用typename
来提示编译器iterator
是一种类型
template<size_t SIZE>
void QuickSort(typename array<int, SIZE>::iterator low,
typename array<int, SIZE>::iterator high);
但这也行不通,因为SIZE
它是在非推断的上下文中。最好只制作一个iterator
作为模板
template<typename RandomIt>
void QuickSort(RandomIt low, RandomIt high);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句