1

我面临着将列表与自身拼接的问题。请注意,我已经在 std::list 和迭代器失效上完成了 splice() 问题是关于两个不同的列表。但我的问题是关于同一个列表。

mylist.splice(mylist.end(), mylist, ++mylist.begin());

似乎 gcc 3.x 使移动的迭代器无效。所以我想它正在重新分配和分配节点。这对于同一个列表没有意义。SGI 确实告诉这个版本的 splice 不应该使任何迭代器失效。如果有任何解决方法,这是 gcc 3.x 的错误吗?

与此同时,我正在浏览 stl_list.h 文件。但是坚持使用 transfer() 函数,我找不到这些的定义。

struct _List_node_base
  {
    _List_node_base* _M_next;   ///< Self-explanatory
    _List_node_base* _M_prev;   ///< Self-explanatory

    static void
    swap(_List_node_base& __x, _List_node_base& __y);

    void
    transfer(_List_node_base * const __first,
         _List_node_base * const __last);

    void
    reverse();

    void
    hook(_List_node_base * const __position);

    void
    unhook();
  };

你知道我在哪里可以找到这些函数定义吗?

4

1 回答 1

0

This functions are in the libstdc++ sources, not the headers. In 3.4 it's in libstdc++-v3/src/list.cc

http://gcc.gnu.org/viewcvs/branches/gcc-3_4-branch/libstdc%2B%2B-v3/src/list.cc?view=markup

Have you tried compiling with -D_GLIBCXX_DEBUG ? That will enable the Debug Mode and tell you if you're using invalid iterators or anything else that causes the problem.

I just tried this simple test with GCC 3.4, with and without debug mode, and it worked fine:

#include <list>
#include <iostream>
#include <string>

int main()
{
  std::list<std::string> l;
  l.push_back("1");
  l.push_back("2");
  l.push_back("3");
  l.push_back("4");
  l.push_back("5");
  l.push_back("6");
  l.splice(l.end(), l, ++l.begin());

  for (std::list<std::string>::iterator i = l.begin(), e = l.end(); i != e; ++i)
    std::cout << *i << ' ';
  std::cout << std::endl;
}

Modifying it further and debugging it I see that no element is destroyed and reallocated when doing the splice, so I suspect the bug is in your program. It's hard to know, as you haven't actually said what the problem is.

于 2012-05-07T02:49:29.223 回答