STL列表问题C

发布于 2024-10-09 06:44:29 字数 364 浏览 0 评论 0原文

我在 c: 中有列表指针,

list<int> * pointer = (list<int> *)malloc(sizeof(list<int>));

当我尝试:时

pointer->push_back(1);

出现错误,因为 malloc 不调用列表构造函数。我知道在 C++ 中这样做:

list<int> * pointer = new list<int>();

但我需要在 C 中这样做?

有人知道这个问题的解决方案吗?

I have list pointer in c:

list<int> * pointer = (list<int> *)malloc(sizeof(list<int>));

when I try:

pointer->push_back(1);

I get error, because malloc doesn't call list constructor. I know to do this in c++ with:

list<int> * pointer = new list<int>();

but i need this in c?

Does anybody know solution for this?

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

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

发布评论

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

评论(2

高冷爸爸 2024-10-16 06:44:29

不,因为这些是不同的语言。仅仅因为名称中的常见字母后面有文本字符串“++”并没有任何意义 - 这与尝试在 Python 中使用 Java 容器的功能等效。

如果你想使用STL,你就必须使用C++编译器。

No, because these are different languages. Just because one only has the text string "++" after a common letter in the name doesn't mean anything - this is the functional equivalent of trying to use a Java container in Python.

If you want to use STL, you have to use a C++ compiler.

浅听莫相离 2024-10-16 06:44:29

您还可以使用 new() 的“放置”版本。在由 malloc() 分配的内存块上调用构造函数。

/* allocate memory using malloc */
list<int> * pointer = (list<int> *)malloc(sizeof(list<int>));

/* invoke the C++ constructor using the placement version of new */
pointer = new(pointer) list<int>();

You can also use the "placement" version of new(). to invoke the constructor on a chunk of memory allocated by malloc().

/* allocate memory using malloc */
list<int> * pointer = (list<int> *)malloc(sizeof(list<int>));

/* invoke the C++ constructor using the placement version of new */
pointer = new(pointer) list<int>();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文