C++ 打印C+的第一个元素+;gdb中的字符串集?

C++ 打印C+的第一个元素+;gdb中的字符串集?,c++,gdb,C++,Gdb,正如所解释的,在std::set中没有通过索引进行的“直接”随机访问-因此,这里我尝试使用返回迭代器的.begin()方法。。。下面是一个简单的示例: // g++ --std=c++11 -g test.cpp -o test.exe #include <iostream> #include <set> int main() { std::set<std::string> my_set; my_set.insert("AA"); my_set

正如所解释的,在
std::set
中没有通过索引进行的“直接”随机访问-因此,这里我尝试使用返回迭代器的
.begin()
方法。。。下面是一个简单的示例:

// g++ --std=c++11 -g test.cpp -o test.exe

#include <iostream>
#include <set>

int main()
{
  std::set<std::string> my_set;
  my_set.insert("AA");
  my_set.insert("BB");
  std::cout << "Hello World!" << std::endl;
  return 0;
}

是否可以使用
gdb
printf
在这样的上下文中打印
std::set
的第一个值,而不必更改代码(例如,添加迭代器变量)?

好吧,多亏了@AndreyStarodubtsev和@Amadeus的评论,我终于找到了答案

首先,正如@Amadeus所指出的,事实证明,你必须在程序中有某种类型的引用,否则它可能会被优化掉。因此,OP示例在调试时将给出:

(gdb) p ((std::string*)(my_set._M_t._M_impl._M_header._M_left+1))->c_str()
A syntax error in expression, near `)(my_set._M_t._M_impl._M_header._M_left+1))->c_str()'.
(gdb) p std::string
No symbol "string" in namespace "std".
。。。然而,仅仅一个变量引用似乎就足以解决以下问题:

// g++ --std=c++11 -g test.cpp -o test.exe

#include <iostream>
#include <set>

std::string aa; // just to have reference to std::string

int main()
{
  std::set<std::string> my_set;
  my_set.insert("AA");
  my_set.insert("BB");
  std::cout << "Hello World!" << std::endl;
  return 0;
}

至于访问
my_set
的第一个节点(显然是节点的“红黑树”)的语法,我查阅了@AndreyStarodubtsev注释的
gdb
脚本,特别是函数
pset
(出于某种原因,这会给我带来语法错误-可能是因为对
std::string
的优化引用)

似乎您可以调整脚本以转储STL容器内容,非常感谢@AndreyStarodubtsev-但是,我仍然无法访问第一个元素,
。begin()
仍然提供语法错误“无法计算函数--可能是内联的”
my_set[0]
在当前上下文中仍然给出“无符号”运算符[]”。“我看到有一个
pset
命令,但也无法让它工作。有什么建议吗?我可能大错特错,但我想编译器需要查看函数的用法,以便将其放入可执行文件中。请尝试调用我的_set.begin()在代码中的任何地方查看它是否工作谢谢,@Amadeus-事实上,你完全正确:我添加了一些用法,如
std::set::iterator my_iter;my_iter=my_set.begin();您可以尝试将
std::string aa;
放入一个新文件中,对其进行编译,并创建一个链接这两个文件(新文件和test.cpp)的可执行文件。这样,您就不需要更改test.cpp了
// g++ --std=c++11 -g test.cpp -o test.exe

#include <iostream>
#include <set>

std::string aa; // just to have reference to std::string

int main()
{
  std::set<std::string> my_set;
  my_set.insert("AA");
  my_set.insert("BB");
  std::cout << "Hello World!" << std::endl;
  return 0;
}
$ gdb --args ./test.exe
...
Reading symbols from ./test.exe...done.
(gdb) b 13
Breakpoint 1 at 0x8048c38: file test.cpp, line 13.
(gdb) r
Starting program: /tmp/test.exe 

Breakpoint 1, main () at test.cpp:13
13    std::cout << "Hello World!" << std::endl;
(gdb) p ((std::string*)(my_set._M_t._M_impl._M_header._M_left+1))->c_str()
$1 = 0x804d014 "AA"
(gdb) printf "'%s'\n", ((std::string*)(my_set._M_t._M_impl._M_header._M_left+1))->c_str()
'AA'