如何最好地为 C++11 中的 unique_ptr 中的普通数组制作迭代器?

How best to make iterators for a plain array within a unique_ptr in C++11?

我想将 的丰富功能与 unique_ptr 持有的数组一起使用。 这是我想编写的代码与我目前必须编写的代码:

void question() {
 const int len = 10;
 int a[len];
 unique_ptr<int[]> p(new int[len]);

 // i can do this with a bare array
 for_each(begin(a), end(a), [](int& v) { v = 0; });

 // but this doesn't compile cuz unique_ptr<T[]> doesn't implement dereference
 //  for_each(begin(*p), end(*p), [](int& v) { v = 0; });

 // this works, but ugly, and begin() and end() are not abstracted.
 for_each(&p[0], &p[len], [](int& v) { v = 0; });

 // how best to make iterators for an array within a unique_ptr?
}

或者使用容器 class 而不是数组会更好吗?

详细说明:

我的完整用例是一个 Buffer 对象,其中包含将传递到音频设备的原始音频样本数组。数组的长度在Buffer构造时确定,之后保持固定。

我没有使用容器 class 因为数据在内存中必须是连续的。但我想遍历缓冲区以用数据填充它。

#include <iostream>
#include <algorithm>
#include <cmath>
#include <iterator>

using namespace::std;

struct Buffer {
 unique_ptr<double[]> buf;
 size_t len;
 int frameRate;
 Buffer(size_t len) : buf(new double[len]), len(len) {}
};

class Osc {
 double phase, freq;
public:
 Osc(double phase, double freq) : phase(phase), freq(freq) {}
 void fill(Buffer& b) {
  double ph = phase;
  for_each(b.buf.get(), next(b.buf.get(), b.len), [&ph, &b](double& d) {
   d = sin(ph);
   ph += 1.0/b.frameRate;
  });
 }
};

int main() {
 Buffer buf(100);
 Osc osc(0, 440);
 osc.fill(buf);
 return 0;
}
#include <iostream>
#include <algorithm>
#include <memory>

void question() {
 const int len = 10;

 std::unique_ptr<int[]> p(new int[len]);
 int x = 0;
 std::for_each(std::next(p.get(), 0), std::next(p.get(), len), [&](int& a) { a = ++x; }); // used std::next(p.get(), 0) instead of p.get().
 std::for_each(std::next(p.get(), 0), std::next(p.get(), len), [](int a) { std::cout << a << "\n" ;});

}

int main()
{
    question();
}