簡體   English   中英

C ++迭代器范圍,使用指向數組的指針

[英]C++ Iterator range using pointers to an array

我不想將數組的大小作為索引參數傳遞。

對於我的merge_sort ,我想使用迭代器范圍概念優化參數。 我似乎無法弄清楚如何尊重迭代器范圍並訪問我的數組。 我可以尊重訪問諸如指數lowhighrecursive_merge_sort ,但似乎並沒有被訪問陣列本身就是一個直觀的方式。 我一直使用有關C ++指針和數組的出色指南作為起點。

我的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] << " ";
    }
}

評論部分來自bayou的解決方案

雷米·勒博(Remy Lebeau):“當您通過指針傳遞數組時,您將丟失有關該數組的所有信息。僅通過指針/迭代器就無法返回原始數組,因為取消引用只會給您數組的單個元素,而不會給您數組本身。通過指針傳遞數組時,您別無選擇,只能將數組大小作為另一個參數傳遞;否則,請按引用傳遞數組,如果需要支持不同大小的數組,請使用模板,因此編譯器可以推斷出引用的數組大小。”

迭代器被建模為充當指針。 它們具有相同類型的重載運算符:至少要取消引用和遞增(某些還具有遞減,隨機訪問等)。

最先進的迭代器接口是隨機訪問,其功能完全類似於原始指針(根據設計)。

因此,所有(原始)指針基本上都是進入C樣式(連續)數組的隨機訪問迭代器。 查看以下內容以可視化C樣式數組的開始/結束迭代器:

int vals[] = { 0, 1, 2, 3, 4 };

int *begin = vals;
int *end   = vals + 5;
v vals[]
0   1   2   3   4   ...
^ begin             ^ end (1 past the end of array)

vals[2] == begin[2]
vals[4] == begin[4]
etc.

因此,基本上,您只是將begin迭代器視為數組的前部,並且只是不取消引用begin迭代器之前的任何地方,也不要在結束迭代器的位置或之后進行取消引用,因為標准C ++約定規定end迭代器在末尾是1的范圍。

這是使用迭代器之類的指針的示例:

void print(int *begin, int *end)
{
    // for each element in the range (starting at begin, up to but not including end)
    for (; begin != end; ++begin)
    {
        // print the element
        std::cout << *begin << '\n';
    }
}

int main()
{
    // declare a C-style array
    int arr[] = { 10, 5, 2, 6, 20 };

    // for the sake of example, print only the middle 3 elements
    // begin = arr + 1
    // end   = arr + 4
    print(arr + 1, arr + 4);

    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM