【发布时间】:2019-09-19 13:56:09
【问题描述】:
问题
我不想将数组的大小作为索引参数传递。
对于我的merge_sort,我想使用迭代器范围概念优化我的参数。我似乎无法弄清楚如何尊重迭代器范围并访问我的数组。我可以在recursive_merge_sort 中访问像low 和high 这样的索引,但似乎没有一种直观的方式来访问数组本身。我一直在使用C++ Pointers and Arrays 上的这个很棒的指南作为起点。
我的Merge Sort C++11 C++17 问题揭示了这个概念,我喜欢使用迭代器范围来减少排序参数数量的想法。
代码
void recursive_merge_sort(int* low, int* high) {
// deference to get starting index "low" and ending index "high"
if(*(low) >= *(high) - 1) { return; }
int mid = *(low) + (*(high) - *(low))/2;
// what's the correct syntax to access my array from the iterator range
// int* d = some how deference low or how to get the data array they iterate on
recursive_merge_sort_v(d + low, d + mid);
recursive_merge_sort_v(d + mid, d + high);
merge(d + low, mid, d + high);
// delete d;
}
void merge_sort(int* data) {
// what's the correct syntax to access my array from the passed in iterator range
// is this event possible? incorrect syntax below
recursive_merge_sort(data + 0, data + std::size(*(data)));
}
int main()
{
int data[] = { 5, 1, 4, 3, 65, 6, 128, 9, 0 };
int num_elements = std::size(data);
std::cout << "unsorted\n";
for(int i=0; i < num_elements; ++i) {
std::cout << data[i] << " ";
}
merge_sort(data);
std::cout << "\nsorted\n";
for(int i=0; i < num_elements; ++i) {
std::cout << data[i] << " ";
}
}
评论部分来自河口的解决方案
Remy Lebeau:“当你通过指针传递一个数组时,你会丢失关于它的所有信息。你不能回到只给定指针/迭代器的原始数组,因为取消引用只会给你一个单一的元素数组,而不是数组本身。通过指针传递数组时,只能将数组大小作为另一个参数传递。否则,通过引用传递数组,如果需要支持不同大小的数组,则使用模板,以便编译器可以推断出引用的数组大小。”
【问题讨论】:
-
将数组的大小作为额外参数传递。
-
Please read this SO post and answers,并阅读“合并排序”部分。您看到您的版本缺少比较两个通用项目的方法,而排序算法应该能够提供这种方法。
-
@0x499602D2 我想避免传入任何额外的参数,并希望使用迭代器来代替传入数组大小。
-
当你通过指针传递一个数组时,你会丢失所有关于它的信息。仅给定指针/迭代器就无法返回原始数组,因为取消引用只会为您提供数组的单个元素,而不是数组本身。通过指针传递数组时,您别无选择,只能将数组大小作为另一个参数传递。否则,改为通过引用传递数组,如果您需要支持不同大小的数组,请使用模板,以便编译器可以推断出引用的数组大小。
-
@RemyLebeau 我将改用我之前的方法,感谢您的澄清,并感谢您在繁忙的日程中抽出时间处理 Fox Disney 的交易。
标签: c++ arrays pointers iterator