Wrap raw data in std container like array, with runtime size

半世苍凉 提交于 2019-12-11 11:28:22

问题


Is there any std container which would be fixed size like std::array, but the size would not be compile time, but runtime?

I want to pass a part of some data I have stored in std::array to std::acculumate and similar functions. I do not want to use std::vector (working on embedded platform), therefore I am looking for something in between.

Assume code like this, what I want is something to be used in place of 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);

}

If there is no such container, how can I wrap the raw data I have and present them to std::accumulate and other std algorithms?


回答1:


std::accumulate takes iterators. You can pass it iterators that contain the range of interest:

auto start = partOfData.begin() + 42;
auto end = partOfData.begin() + 77;
const auto s_x  = std::accumulate(start, end, 0.0);

Alternatively, you can roll out your own non-owning container-like object. See this question for an example.



来源:https://stackoverflow.com/questions/26754394/wrap-raw-data-in-std-container-like-array-with-runtime-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!