C 数组和 C++ 迭代器

问题描述 投票:0回答:2

我必须对存储为 C 数组的缓冲区进行一些图像处理。 处理必须相对中心柱对称进行。

所以我必须处理从中心到左边缘的所有左半部分,以及从中心到右边缘的所有右半部分。因此,要在水平轴上滚动,在处理左半部分时,我必须减少 X 坐标(因此指针),而在处理右半部分时,我必须增加 X 坐标(因此指针)。

我计划做一个只处理一半的函数,并发送一个正向或反向迭代器作为参数。但是如果我调用

std::begin(myCArray)
,我会得到一个原始指针,如果我调用
std::rbegin(myCArray)
,我会得到一个
std::reverse_iterator
。我没有通用类型,也不想用模板,因为功能会很重。

我应该创建自己的迭代器吗?

c++ iterator c++17
2个回答
0
投票

一种替代方法是根本不使用迭代器,而只使用带有

int
增量的循环:

// proccess all pixel from middle to edge (inclusive)
void do_processing(Pixel* middle, Pixel* edge)
{
    int increment = middle < edge ? 1 : -1;

    for (auto p = middle; p != edge; p += increment) {
        process(*p); // Current work on given pixel
    }
    // We cannot check (p != edge + increment) which would be UB when increment is negative
    // so process it outside of the loop
    process(*edge);
}

0
投票

您不需要自定义迭代器:

pixel row[N];
pixel* begin = std::begin(row);
pixel* end = std::end(row);
pixel* middle = begin + (end - begin) / 2;

void process(pixel* begin, pixel* middle, pixel* end) {
    // note: the pixel index can always be computed with: it - begin
    for (auto i = begin; i != middle; ++i) {
        process_forward(*i);
    }
    for (auto j = end; j-- != middle; ) {
        process_reverse(*j);
    }
}

当然,这是手动完成

std::reverse_iterator
的工作,但在这种情况下非常简单。

如果您想要一个可以接受正向和反向迭代器的函数,它需要是一个函数模板。

© www.soinside.com 2019 - 2024. All rights reserved.