[英]C++ fixed-size vector backed by custom buffer
是否有任何STL容器实现由自定义缓冲区支持的固定大小的矢量,并允许我执行以下操作:
int arr[] = {1, 2, 5, 12, 34, 12, 56, 12};
std::mysteryvector<int> vec(arr + 2, 3); // <-- No copy here, and 3 can be a variable
// (no compile-time template parameter)
std::cout << *vec.begin() << std::endl; // prints 5
std::cout << vec.size() << std::endl; // prints 3
// There is no push_back() or resize(), but size(), begin(), end(), etc.
// work as in std::vector
arr[4] = 1212;
std::cout << vec[2] << std::endl; // prints 1212
还是我应该自己实施? 是否建议使用针对std::vector
的自定义分配器之类的黑客/变通方法?
编辑。 为什么呢 与假定存在size()
, begin()
, end()
, []
但不调用push_back()
旧代码的兼容性。
不幸的是,没有这样的事情。
但是,在http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3334.html上有关于string_ref和array_ref的建议。
Boost似乎已经实现了string_ref,您可以在此处查看: http : //www.boost.org/libs/utility/doc/html/string_ref.html 。
因此,您只需要带有begin
, end
, size
和[]
吗? 这样的事情行吗?
class FakeVector{
int* m_begin;
int* m_end;
size_t m_size;
public:
FakeVector(int* begin, size_t size)
: m_begin(begin), m_end(begin + size), m_size(size) { }
int* begin() { return m_begin; }
int* end() { return m_end; }
size_t size() { return m_size; }
int& operator[] (size_t index) { return m_begin[index]; }
// And, in case you need const access:
const int* begin() const { return m_begin; }
const int* end() const { return m_end; }
const int& operator[] (size_t index) const { return m_begin[index]; }
};
int arr[] = {1, 2, 5, 12, 34, 12, 56, 12};
FakeVector vec(arr + 2, 3);
std::cout << *vec.begin() << std::endl; // prints 5
std::cout << vec.size() << std::endl; // prints 3
arr[4] = 1212;
std::cout << vec[2] << std::endl; // prints 1212
现在已经将其硬编码为int
了,但是模板化应该相当简单。
std::array<int, 3>* mymistvector = new (arr + 2) std::array<int, 3>();
我有一个称为fector的固定大小的矢量类,其行为类似于std :: vector,但具有类似于std :: array的模板化大小。 你可以在这里找到它。 它是一个包含150 LOC的自包含标头
sweet::fector<int,128> f;
for(int i = 0; i < 128; ++i) {
f.push_back(i);
}
// the next push_back will throw
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.