是否有任何 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()
的遗留代码兼容。
不幸的是,没有这样的事情。
但是,有一个关于string_ref和array_ref的建议 http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3334.html。
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