【问题标题】:Please help me understand what 'list<Msg*>' is请帮我理解什么是'list<Msg*>'
【发布时间】:2021-06-25 05:42:35
【问题描述】:
#include <iostream>
#include <list>
#include <string.h>

struct message
{
    int id;
    char mesg[100]; 
}; 

int main()    
{
    struct message Msg;
    Msg.id=111;
    strcpy(Msg.mesg," am fine");
    list<Msg*> l1;
}

我需要这个l1 列表大小不为空。但是当我编译这段代码时,它显示了一个错误。

【问题讨论】:

  • list&lt;Msg *&gt; l1; ==> std::list&lt;Msg *&gt; l1;
  • 你好先生/女士,实际上我需要 l1.size() 值不为空,但如果我运行此代码意味着我只显示为空
  • @mohan 列表是空的,因为你没有在列表中放入任何值,例如使用它的push_back() 方法,例如:l1.push_back(&amp;Msg);
  • 无关:您在 C++ 中使用 C 字符串是否有原因? Msg.mesg = " am fine"; 怎么了?
  • no.. 用于插入值,正在使用 C 字符串

标签: c++ list dictionary vector stl


【解决方案1】:

在 c++ 中可以使用push_back() 函数的列表

您的列表为空的原因是因为您没有向其中添加任何内容

你需要类似的东西

l1.push_back(msg);

也根据 cmets 在 C++ 中,你不必使用 C 风格的字符串 而不是strcpy(),您可以只为变量分配一个字符串,例如:

std::string msg = "我很好";

【讨论】:

    【解决方案2】:

    您的代码中有两个错误:

    1. 您需要为list添加范围

    2. 在您的情况下,模板参数必须是类型而不是值

    #include <iostream>
    #include <list>
    #include <string.h>
    
    struct message
    {
        int id;
        char mesg[100]; 
    }; 
    
    int main()    
    {
        struct message Msg;
        Msg.id=111;
        strcpy(Msg.mesg," am fine");
        std::list<message*> l1;
    }
    

    【讨论】:

      猜你喜欢
      • 2011-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-09
      • 1970-01-01
      • 2022-06-29
      相关资源
      最近更新 更多