因此,我在這里看到了有關如何將 astd::vector::iterator作為引數傳遞給函式的問題,但是,在處理std::arrays 時,這些解決方案似乎并不適用。我想用這個是一個快速排序函式,它接受std::arrays。這是我到目前為止的代碼:
#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;
}
正如你所看到的,我已經設法將大部分部分融入這個難題,我只是不知道如何通過lowand high,它們是隨機訪問迭代器型別,作為函式的引數引數。usingstd::array<type, size>::iterator不起作用,因為它不是一種型別。我也嘗試添加#include <iterator>,但無濟于事。
編輯:為了澄清,這不是我試圖通過的索引中包含的值,而是索引本身隨著每次遞回而變化。
uj5u.com熱心網友回復:
您需要使用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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/465381.html
