[英]Is there a way to reverse the order of an array in C++?
我正在制作一个小型照片程序,该程序需要一个.ppm文件,然后应用滤镜,例如对红色,绿色,蓝色,水平翻转和灰度进行求反(用户选择要应用的滤镜)。 我弄清楚了一切,除了在水平翻转方面遇到困难。 我认为没有必要发布WHOLE程序,因为我在执行一项功能时遇到困难。 但是,如果需要,请告诉我,然后我将其发布。
这是取反红色,绿色和蓝色的示例函数。
void negate_red(int image[], int w, int h)
{
for(int i = 0; i<h; i++)
for(int j=0; j<w; j++)
{
image[(i*w+j)*3] = 255 - image[(i*w+j)*3];
}
}
void negate_green(int image[], int w, int h)
{
for(int i = 0; i<h; i++)
for(int j=0; j<w; j++)
{
image[(i*w+j)*3+1] = 255 - image[(i*w+j)*3+1];
}
}
void negate_blue(int image[], int w, int h)
{
for(int i = 0; i<h; i++)
for(int j=0; j<w; j++)
{
image[(i*w+j)*3+2] = 255 - image[(i*w+j)*3+2];
}
}
据我了解,为了水平翻转图像,您必须反转阵列的顺序。 例如,第一个RGB值将是最后一个,对吗? 有没有一种方法可以反转数组的顺序? 在问这个问题之前,我做了一些搜索,然后发现: 图像像素的翻转/镜像正确吗?
因此,如果我正确地解释了这一点,我应该像这样启动函数:
void flip (int image[], int w, int h)
{
for(int i = 0; i<h/2; i++)
for(int j=0; j<w/2; j++)
{
//code
}
}
现在有一种方法可以反转数组的顺序,使其从最后一个元素开始并转到第一个元素?
感谢您的帮助,非常感谢! 谢谢!
我会推荐<algorithm>
std::reverse()
。 您可以使用(arr, arr+size)
调用数组来传递数组。 它将反转数组。
为了解决下面的讨论:尽管用普通C语言以外的其他语言将RGB值表示为3个独立的int有点奇怪,但对于OP来说这应该不是问题:确保数组的大小是P的倍数。 3,定义一个这样的结构:
struct rgb_value {
int red;
int green;
int blue;
};
然后将数组转换为struct rgb_value,并使用(cast_array,cast_array + original_size / 3)调用反向。 这样,将保持结构内部的顺序。
我有点不喜欢自己做这种类型转换的想法,但是替代方法是编写一个自己的反向函数,该函数进行交换以保持rgb顺序,或将数据复制到数据结构中,其中rgb-值就这样表示并正确交换。
编辑2:首先,我想指出的是,这不是对“如何水平翻转图像?”的答案,而是对“是否有一种方法可以反转C ++中数组的顺序?”的答案。 因此,我尽力避免OP的图像翻转算法是否正确的问题。
其次,即使假设OP的算法本来是错误的,也可以选择反向算法。 其他解决方案所建议的不过是一种相当复杂的表达方式:
rgb_color *pos = reinterpret_cast<rbg_color *>(image);
for (int i = 0; i < num_rows; ++i){
pos += i * rgb_per_row //select row
std::reverse(pos, pos + rgb_per_row);//reverse row
}
其中rgb_per_row是该行的长度除以sizeof(rgb_value)/sizeof(int)
,
您需要遍历图像左侧的每个像素,并将其对应的像素翻转到右侧。 这意味着您需要查看整个图像中的每一行,但仅需经过一半。
void swap_int (int *a, int *b)
{
int temp = *b;
*b = *a;
*a = temp;
}
void h_flip (int image[], int w, int h)
{
for(int i = 0; i<h; i++) // every row
for(int j=0; j<w/2; j+=3) // halfway through the row
{
// We now swap this pixel (i,j) with its mirror pixel
// on the right (i,w-j), swapping red, green, and blue values
swap_int (&image [(i*w + j) * 3 + 0], &image [(i*w + (w-j)) * 3 + 0]);
swap_int (&image [(i*w + j) * 3 + 1], &image [(i*w + (w-j)) * 3 + 1]);
swap_int (&image [(i*w + j) * 3 + 2], &image [(i*w + (w-j)) * 3 + 2]);
}
}
Iterative way:
1) Initialize start and end indexes.
start = 0, end = n-1
2) In a loop, swap arr[start] with arr[end] and change start and end as follows.
start = start +1; end = end – 1
/* Function to reverse arr[] from start to end*/
void reverseArray(int arr[], int start, int end)
{
int temp;
while(start < end)
{
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
尝试将此解决方案应用于您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.