如何读/写或遍历 std::array 中的特定元素范围?

How to read/write or iterate through a specific range of elements within a std::array?

本文关键字:元素 范围 array 遍历 std 何读      更新时间:2023-10-16

我想在更大的内存中读/写一些特定范围的内存,基本上我想做这样的事情:

std::array<int, 1024> big_array;
unsigned short int offset = 128;
template<std::size_t SIZE>
void ReadArray(std::array<int, size>&  big_array_with_address_offset)
{
// ... some code in here 
}
ReadArray(big_array + offset); //--> This doesn't work

我能够为我正在处理的另一个函数(下面的代码(做类似的事情,将原始指针作为函数参数,但我正在尝试以现代C++(病房上的 11 个(方式执行此操作,因为我需要使用std::array我不想使用原始指针作为函数参数

int FindMinElement(int * array)
{
// Min element from range: 128 to 384
return *std::min_element(array, array+256);
}
FindMinElements(big_array.data()+128);

注意1:我能够在函数参数中使用较小std::array的唯一方法是使用template<std::size_t SIZE>,否则由于大小不兼容,我会收到编译错误。

注意2:我不想用std::vector来做这件事,因为我需要静态内存而不是动态内存。

将数组在offset元素处的地址传递给FindMinElement函数。请参阅以下示例了解如何执行此操作:

#include<iostream>
#include<array>
#include<algorithm>
using namespace std;
std::array<int, 1024> big_array;
unsigned short int offset = 128;
int FindMinElement(int *array)
{
// Min element from range: 128 to 384
return *std::min_element(array, array+256);
}
int main(void)
{  
int counter = 0;
for(auto & i : big_array) //populates the array from 0 to 1023
{
i = counter++; 
}       
cout << "Min element in the range 128 to 384 is: ";
cout << FindMinElement(big_array.begin() + 128) << endl;
}

输出:

Min element in the range 128 to 384 is: 128

将迭代器发送到数组的开头,而不是在数组中发送。

你的 FindMinElement 函数收到一个指针,而不是一个真正的数组。发送迭代器是最接近的等效项。

我终于弄清楚了,这就是我想要实现的目标,也是我的意思是使用迭代器和没有原始指针的现代C++,P.W. 答案接近我想要实现的目标:

short int FindMinElement(std::array<short int, 1>::iterator it);
{
// Min element from range: 128 to 384
return *std::min_element(it, it + 128);
}
int main()
{
std::array<int, 1024> big_array{{0}}; 
unsigned short int offset = 128;
short int minval = 0;
// Asuming big_array is populated in some other place before calling FindMin..()
minval = FindMinElement(std::begin(big_array) + offset);
return 0;
}

我希望能够在不使用原始指针的情况下操作数据,然后解决方案是使用迭代器作为参数而不是指针。

这也解决了 NOTE1 中提到的编译错误,即我在将较大的 std::array 的引用传递给较小的 std::array 函数参数时遇到的编译错误