29

When stepping through the following sample code in Visual Studio 2012:

std::vector<int> test;
test.resize(1);
test[0] = 4;

I can set a watch on test and inspect its 0th element. However, if I set a watch on test[0], I get the error 'no operator "[]" matches these operands':

enter image description here

How can I inspect the value of test[0] directly?

1''
  • 26,823
  • 32
  • 143
  • 200

4 Answers4

51

I found one solution which does not depend on the internals of the class. The expanded form of the operator call seems to work for me. In this case it's the following code:

v.operator[](0)

I tested it in Visual C++ 2012.

Max
  • 19,654
  • 13
  • 84
  • 122
7

As @NateKohl noted, in Visual Studio 2012 (and possibly earlier versions as well) v._Myfirst gives a pointer to the underlying vector data, allowing you to watch the vector as if it were an array.

1''
  • 26,823
  • 32
  • 143
  • 200
3

Visual Studio doesn't support stl containers' operator[] overloading, you simply have to manually set a watch on the element that you're interested in by selecting it from the list while debugging.

EDIT: if you want to inspect a T object inside a vector, assign it to a T object and set a watch on it instead

mewa
  • 1,532
  • 1
  • 12
  • 20
  • What if the vector has 10000 elements and you want to see element 5000? Is there a convenient way to do that? – 1'' Jul 23 '13 at 00:16
  • unfortunately I'm afraid you'll have to do it manually for the first time. – mewa Jul 23 '13 at 00:18
  • Regarding your edit: that's not an option if you're stepping through a DLL. What would you do in that scenario? – 1'' Jul 23 '13 at 00:28
  • 4
    I think that `v._Myfirst[0]` allows you to watch e.g. the 0-th element of `v` (where `_Myfirst` (which might be `_First` or `_M_start`, depending on your VS version) is the name of the vector's internal storage) – Nate Kohl Jul 23 '13 at 00:32
  • Not sure if that's what you mean, but if you don't know the type you can assign it with auto type – mewa Jul 23 '13 at 00:35
1

if you use 2D vecotr< vector< string > > dp, and you want to get dp[i][j] in watch window in VS2013, you can use (dp.operator [ ] (i)).operator [ ] (j)

vector< vector < string > > dp(n, vector < string >(n, ""));

(dp.operator [ ] (i)).operator [ ] (j)

Terry
  • 700
  • 2
  • 8
  • 17