[英]Storing vector in memory mapped file
我試圖在一個內存映射文件中存儲一個任意元素的向量(現在我試圖用一個int向量成功,但它應該與任意對象的向量一起工作)。 我已經找到了大量關於使用共享內存的文檔,但沒有找到適當的內存映射文件。 由於我已經成功地在內存映射文件中制作和使用了R-tree(就像在那個例子中 ),我試圖用向量復制過程,但我想我錯過了一些關鍵元素,因為它不起作用。 這是我的代碼:
namespace bi = boost::interprocess;
typedef bi::allocator<std::vector<int>, bi::managed_mapped_file::segment_manager> allocator_vec;
std::string vecFile = "/path/to/my/file/vector.dat";
bi::managed_mapped_file file_vec(bi::open_or_create,vecFile.c_str(), 1000);
allocator_vec alloc_vec(file_vec.get_segment_manager());
std::vector<int> * vecptr = file_vec.find_or_construct<std::vector<int> >("myvector")(alloc_vec);
可能我的最后一行是錯誤的,因為“alloc_vec”作為參數傳遞給向量構造函數,它不期望它(我得到的錯誤是/usr/include/c++/4.8/bits/stl_vector.h:248:7: note: candidate expects 0 arguments, 1 provided
)。 但是,我不知道如何將分配器傳遞給find_or_construc(),我認為這對於在內存映射文件中正確創建向量至關重要。 在最后一行的末尾刪除(alloc_vec)
導致另一個錯誤,我(alloc_vec)
解決:
error: cannot convert ‘boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index>::construct_proxy<std::vector<int> >::type {aka boost::interprocess::ipcdetail::named_proxy<boost::interprocess::segment_manager<char, boost::interprocess::rbtree_best_fit<boost::interprocess::mutex_family>, boost::interprocess::iset_index>, std::vector<int>, false>}’ to ‘std::vector<int>*’ in initialization
std::vector<int> * vecptr = file_vec.find_or_construct<std::vector<int> >("myvector");
任何幫助將不勝感激
就像示例展示一樣,告訴vector類關於你的自定義分配器,而不是
typedef std::vector<int> MyVec;
MyVec * vecptr = file_vec.find_or_construct<MyVec>("myvector")(alloc_vec);
采用
typedef bi::allocator<int, bi::managed_mapped_file::segment_manager> int_alloc;
typedef std::vector<int, int_alloc> MyVec;
int_alloc alloc(file_vec.get_segment_manager());
MyVec * vecptr = file_vec.find_or_construct<MyVec>("myvector")(alloc);
注意
vector
使用分配器作為元素類型(不適用於vector; segment_manager分配) allocator<>
的構造函數是隱式的,所以你也可以只傳遞segment_manager
: #include <boost/interprocess/managed_mapped_file.hpp>
namespace bi = boost::interprocess;
int main() {
std::string vecFile = "vector.dat";
bi::managed_mapped_file file_vec(bi::open_or_create,vecFile.c_str(), 1000);
typedef bi::allocator<int, bi::managed_mapped_file::segment_manager> int_alloc;
typedef std::vector<int, int_alloc> MyVec;
MyVec * vecptr = file_vec.find_or_construct<MyVec>("myvector")(file_vec.get_segment_manager());
vecptr->push_back(rand());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.