Confusing behavior while using std::vector

The size() method of std::vector appears to be returning -1, I have initialized and assigned a first element.
This is the part of my code that is causing issues:

Brain.Screen.print(m_yellowObjects.size()); // m_yellowObjects.size is a vector with a custom type
if(m_yellowObjects.size() > 0)
{
Brain.Screen.print(m_yellowObjects.size());

The results from this segment are:
-1
-1
This obviously doesn’t make any sense, the only point where m_yellowObjects is interacted with before this is when I give it a value for the first element in the constructor.

I tested quickly with a simple function, not seeing any issues with that.

void
test_vector() {
    std::vector<int> v;
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    v.push_back(4);
    std::cout << "vector size is " << v.size() << std::endl;
    Brain.Screen.print( v.size() );
}

need to see more of your code

5 Likes

This is the code that gives the strange behaviour:

Brain.Screen.print(m_yellowObjects.size());
  if(m_yellowObjects.size() > 0)
  {
      Brain.Screen.print(m_yellowObjects.size());

    for(int i = 0; i < m_yellowObjects.size(); i++)
    {
      m_yellowAverage.fill(m_yellowObjects[i].originX, m_yellowObjects[i].originY, 
                                                m_yellowObjects[i].width, m_yellowObjects[i].height);
    }
}

The objects within the vector contain four integers, and I pushed the first value into the vector in the constructor, I get the same result whether I do this or not.

m_yellowObjects.push_back({0,0,0,0});

still not enough to go on really, write a small test program I can run that demonstrates the error.
I tried this example, still no issues here.

typedef struct _my_data {
    int32_t originX;
    int32_t originY;
    int32_t width;
    int32_t height;
} my_data_t;

void
test_vector() {
    std::vector<my_data_t> v;

    v.push_back({0,0,100,100});
    v.push_back({10,10,100,100});
    v.push_back({20,20,100,100});
    v.push_back({30,30,100,100});
    std::cout << "vector size is " << v.size() << std::endl;
    for(int i=0;i<v.size();i++ ) {
      std::cout << "vector element "  << i << " is " 
                                      << v[i].originX  << " " 
                                      << v[i].originY << " " 
                                      << v[i].width << " " 
                                      << v[i].height << " " 
                                      << std::endl;
    }
    Brain.Screen.print( v.size() );
}
3 Likes

I cant seem to replicate the issue but I have found that the for loop never ends.

for(int i = 0; i < m_yellowObjects.size(); i++)
{
Brain.Screen.print(m_yellowObjects.size());
Brain.Screen.print(i);
}

The results of this code is -1 followed by the iteration number such as:
-1 1 -1 2 -1 3…

The brain is updated, and I get this issue with the new compiler update as well.