'Accessing vector items in GDB
For example, I have such struct in a templated class:
struct Foo{
int data;
vector<Foo*> children;
}
And to print out the data value, I can simply do this: (let bar be a pointer to a Foo)
print bar->data
and this works fine. However I would like to also follow children to another Foo. I tried:
print bar->children[0]->data
but it doesn't work. How should I access the items in a vector and use it in print?
Solution 1:[1]
With GDB 7.9 and g++ 4.9.2, it works quite well while printing bar->children[0]->data.
But, here is also an indirect method to access these elements:
print (*(bar->children._M_impl._M_start)@bar->children.size())[0]->data
where VECTOR._M_impl._M_start is the internal array of VECTOR and [email protected]() is used for limiting the size of a pointer.
reference: How do I print the elements of a C++ vector in GDB?
Complement:
There is also another not so elegant but more general way:
print bar->children[0]
and you might get something like this:
(__gnu_cxx::__alloc_traits<std::allocator<Foo*> >::value_type &) @0x603118: 0x603090
so you can access to it with the pointer given above:
print ((Foo)*0x603090).data
Solution 2:[2]
template <> Foo* &std::vector<Foo*>::operator[](size_type n) noexcept
{
return this->begin()[n];
}
to use vector operator[], need the Template materialization
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Community |
| Solution 2 | Linhb |
