C++ 在内存映射文件中存储向量

C++ 在内存映射文件中存储向量,c++,boost,memory-mapped-files,boost-interprocess,C++,Boost,Memory Mapped Files,Boost Interprocess,我试图将任意元素的向量存储在内存映射文件中(目前我试图成功地使用int向量,但它应该可以使用任意对象的向量)。我已经找到了大量关于使用共享内存执行此操作的文档,但没有找到正确的内存映射文件。因为我已经成功地在内存映射文件(如中)中创建并使用了R树,所以我尝试用向量复制这个过程,但我想我缺少了一些关键元素,因为它不起作用。这是我的密码: namespace bi = boost::interprocess; typedef bi::allocator<std::vector<int&g

我试图将任意元素的向量存储在内存映射文件中(目前我试图成功地使用int向量,但它应该可以使用任意对象的向量)。我已经找到了大量关于使用共享内存执行此操作的文档,但没有找到正确的内存映射文件。因为我已经成功地在内存映射文件(如中)中创建并使用了R树,所以我尝试用向量复制这个过程,但我想我缺少了一些关键元素,因为它不起作用。这是我的密码:

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);

任何帮助都将不胜感激。`

如示例所示,告诉vector类有关您的自定义分配器的信息,而不是

typedef std::vector<int>  MyVec;
MyVec * vecptr = file_vec.find_or_construct<MyVec>("myvector")(alloc_vec);

分配器总是有重载,只是分配器与默认的
allocator
模板参数类型(
std::allocator
)不匹配(请参见)为什么要尝试此操作?为什么(为什么)要在内存映射文件中使用向量(“高级容器”)(低级内容)。请编辑您的问题以改进它。您的代码在调试模式下在MSVC14上崩溃:。你知道如何解决这个问题吗?试着删除mm文件,让它重新创建。同时尝试更改为boost::container::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);
#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());
}