有没有像 std::array 这样固定大小的 std 容器,但大小不是编译时的,而是运行时的?
我想将存储在 std::array
中的部分数据传递给 std::acculumate
和类似的函数。我不想使用 std::vector(在嵌入式平台上工作),因此我正在寻找介于两者之间的东西。
假设这样的代码,我想要的是用来代替 array_part
的东西:
#include <array>
#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
int main()
{
std::array<float,100> someData;
// fill the data
int dataCount = 50;
std::array_part<float> partOfData(someData.data(),dataCount)); // <<<<< here
const auto s_x = std::accumulate(partOfData.begin(), partOfData.end(), 0.0);
}
如果没有这样的容器,我如何包装我拥有的原始数据并将它们呈现给 std::accumulate
和其他 std 算法?
最佳答案
std::accumulate
采用迭代器。您可以将包含感兴趣范围的迭代器传递给它:
auto start = partOfData.begin() + 42;
auto end = partOfData.begin() + 77;
const auto s_x = std::accumulate(start, end, 0.0);
或者,您可以推出自己的非拥有类容器对象。参见 this question举个例子。
关于c++ - 将原始数据包装在 std 容器中,如数组,具有运行时大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26754394/