c++ - 将原始数据包装在 std 容器中,如数组,具有运行时大小

标签 c++ arrays c++11 containers std

有没有像 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/

相关文章:

c++ - 一元 + 运算符有什么实际用途吗?

c - 为什么我不能像 C 中的指针一样对待数组?

java - java中一种产品的库存只减少?

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

c++ - lcov 报告未执行静态成员变量析构函数中的行

c++ - 删除一个 char* 崩溃程序

c++ - 类似于\see 或\sa 的 Doxygen 别名

c++ - bsearch包装器

c++ - 从基于 c++0x std::thread 的 C++ 库中公开完整的(C 语言)pthread 接口(interface)

c++ - 当用户输入大量数字时无限循环