0

I have a vector of integers in a C++ program:

  1 #include <iostream>
  2 #include <vector>
  3 using std::vector;
  4 using std::cout;
  5 using std::endl;
  6
  7 int main()
  8 {
  9     vector<int> a;
 10     for (size_t i=0; i<7; ++i)
 11         a.push_back(i*2);
 12     cout << a.size() << endl;
 13     return 0;
 14 }

In GDB, when I break at line 12, I can inspect the value of a.size(). However, if I tried to inspect a[1], GDB complained "Could not find operator[]." If I tried to inspect a.at(1), GDB complained "Cannot evaluate function -- may be inlined". What should I do to inspect the content of the vector?

angelaTIEN
  • 11
  • 1

1 Answers1

-1

You may define a function

void print(vector<int> A) {
    for (int i=0; i<A.size(); ++i)
        cout << A[i] << ' ';
    cout << endl;
}

Then in GDB, you may "call print(a)" to see the contents of the vector a.

By the way, the main reason why you failed to call a[i] or a.at(i) in GDB is that, these methods are not used in your program so they are not instantiated. Please check https://stackoverflow.com/a/24131961/7588831 for more details.

  • If I have a vector of integers, and a vector of strings, does this imply I have to define a print_int() and a print_str()? Isn't there an elegant solution? – angelaTIEN Jul 22 '21 at 13:56
  • You may utilize the "function overloading" feature in C++. You define "void print(vector A)" and "void print(vector A)". Then in GDB, you may "call print(a)" and "call print(b)". – Aaron Solomon Jul 22 '21 at 13:58