RAW指针容器包装器

发布于 2024-10-04 21:19:55 字数 359 浏览 0 评论 0原文

我有一个指向数据数组的原始指针。我想将此指针包装到具有 STL 容器语义的容器中(例如 std::vector)。 STL 有什么功能可以实现这一点吗?

例如

class my_class
{
public:

   std::some_container<char> get_data() { return std::some_container(my_data, my_data_size);}

private:
   char* my_data;
   size_t my_data_size;
};

编辑:

我不能直接使用 std::vector 因为内存是由外部 api 分配的。

I have a raw pointer which points to an array of data. I would like to wrap this pointer into a container with STL container semantics (e.g. std::vector). Does the STL have any feature which allows this?

e.g.

class my_class
{
public:

   std::some_container<char> get_data() { return std::some_container(my_data, my_data_size);}

private:
   char* my_data;
   size_t my_data_size;
};

EDIT:

I cannot use std::vector directly since the memory is allocated by an external api.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一桥轻雨一伞开 2024-10-11 21:19:55

STL 没有,boost 可以:

boost::iterator_range<char*> get_data() { 
    return boost::iterator_range<char*>(my_data, my_data+my_data_size);
}

STL doesn't, boost does:

boost::iterator_range<char*> get_data() { 
    return boost::iterator_range<char*>(my_data, my_data+my_data_size);
}
流殇 2024-10-11 21:19:55

如果您将 std::vector 与自定义内存“分配器”一起使用,这可能是可行的,但对我来说这听起来不是一个好主意。

由于据我所知,您不可能在不编写代码的情况下摆脱这种情况,因此我建议花时间为这种情况编写您自己的类似 STL 的容器(或者更好的是,找到一个开源容器!)。

Possibly this is doable if you use std::vector with a custom memory "allocator", but it doesn't sound like a good idea to me.

Since there is no way I know of that would let you get away with this without writing code, I suggest taking the time to write your own STL-like container for this scenario (or better yet, find an open source one!).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文