【问题标题】:My list of pointers to std::string objects is not working right, and I can't figure out why我的指向 std::string 对象的指针列表无法正常工作,我不知道为什么
【发布时间】:2011-10-02 02:19:36
【问题描述】:

你能帮我弄清楚这段代码吗: onCreate(xMsg) 由 WindowProcedure 在 WM_NCCREATE 消息上调用。问题在于迭代器取消引用。我似乎无法将迭代器设置为列表的 begin(),然后获取迭代器的内容,它应该是指向可以与 MessageBox 中的 ->c_str() 一起使用的字符串的指针。

class MyController
{
public:
    MyController() { }
    ~MyController() { }
    void onCreate(xMessage *msg);

protected:
    std::list<std::string *> m_stringlist;
    std::list<std::string *>::iterator m_stringlistiter;
};

void onCreate(xMessage *msg)
{
    std::string *first_string = new std::string("Hello world");
    m_stringlist.push_back(first_string);
    // This is where my iterator comes into play and it doesn't seem to do the trick.

    m_stringlistiter = m_stringlist.begin();
    MessageBox(NULL, (*m_stringlistiter)->c_str(), "Title", MB_OK);
}

【问题讨论】:

  • 运行时错误?编译时错误?错误信息?
  • 有什么理由不直接使用std::string 而是使用指针? std::string 具有安全复制(现在是移动)语义,因此在容器中使用它比使用指向它的指针或 char* 更安全。
  • 您的代码看起来不错。 “工作不正常”是什么意思???
  • 运行时错误只是它有一个错误并决定通过微软检查它的解决方案我猜。至于将容器用于字符串,我只知道我以前遇到过这个问题并且无法弄清楚,而我只是一个解决这个问题的坚持者。
  • 如果你在你的代码中分配const char* striter = (*m_stringlistiter)-&gt;c_str();,你会得到“Hello world”吗?它似乎对我有用......

标签: c++ string list iterator


【解决方案1】:

我们没有给出完整的示例,但我假设您在迭代器的创建和使用之间进行了其他操作。

不保证迭代器在容器上进行各种操作后有效。您应该保存它们。

我愿意打赌这会奏效吗?

class MyController
{
public:
    MyController() : title("Hello World") {}
    void onCreate(xMessage *msg);
    {
         MessageBox(NULL, title.c_str(), "Title", MB_OK);
    }
protected:
    std::string title;  // generic lists of strings with 
                        // magic indexes are hard to maintain.
};

这也更容易阅读和调试,这比软件开发的任何其他部分都要高得多。

在大多数情况下,您应该将迭代器用作临时对象。它们很少扩展到函数/方法的范围之外。

struct some_struct {

  some_struct() {
    gui_text.push_back( std::string("Hello World!") );
  }
  void some_function() {
    std::list<std::string>::iterator iter = gui_text.begin();
    for (; iter != gui_text.end(); iter++) {
      std::cout << *iter << std::endl;
    }
  }

  std::list<std::string> gui_text;
};

从容器中添加、删除等操作将使迭代器无效。所以只需在每个点重新创建迭代器。字符串和迭代器非常轻量级,因此您无需担心以这种方式进行优化。真的。

【讨论】:

  • 这基本上是问题所在,但我认为我需要一个静态声明的对象。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-27
相关资源
最近更新 更多