Vector subscript out of range when incrementing an int?

So strange situation, I am creating a list of structs, and then I am trying to update one of the list members with new values, and then move it back into the list.

I seem to be able to copy the values of the struct at iterator just fine, but when I attempt to update the value of the struct's member (using int++;) it throws an exception in the vector class of all things.

Any kind of explanation as to what might be happening here would be helpful.

struct Blob
{
    int x;
    int y;
};

list<Blob> blob; 
// Add a Blob to blob using .push_back(); here 
for(list<Blob>::iterator iterator=blob.begin(); iterator!=blob.end(); ++iterator)
{
    Blob temp;
    temp.x = ((Blob)*iterator).x; 
    temp.y = ((Blob)*iterator).y; 
    if (temp.x < 10 - 1)
        temp.x++; /* Exception: vector: line 932 - "Vector subscript out of range"  */
    ((Rain)*iterator) = temp; 
}   

Answers


When you want to update the existing value of object then take a reference of it. I have written a sample code to explain the same

#include<list>
#include<iostream>
using namespace std;
struct Test
{
    int x;
    int y;
};

int main()
{
    list<Test> lTest;
    int i = 0;
    for(i=0;i<5;i++)
    {
        Test t1;
        t1.x = i;
        t1.y = i*i;
        lTest.push_back(t1);
    }

    list<Test>::iterator lIter = lTest.begin();
    for(;lIter != lTest.end();++lIter)
    {
        Test &t1 = *lIter;
        cout<<"1 Val is:"<<t1.x<<"|"<<t1.y<<endl;
        t1.x += 2;
        t1.y += 2;
        cout<<"2 Val is:"<<t1.x<<"|"<<t1.y<<endl;
    }

    lIter = lTest.begin();
    for(;lIter != lTest.end();++lIter)
    {
        Test t1 = *lIter;
        cout<<"3 Val is:"<<t1.x<<"|"<<t1.y<<endl;
    }

    return 0;
}

If you're writing a loop it's likely there's another way to do it. You can use std::for_each:

#include <list>
#include <algorithm>

struct Blob
{
    int x;
    int y;
};

void incrementXIfLessThanNine(Blob& blob)
{
    if(blob.x < 9)
    {
        blob.x++;
    }
}

int main()
{
    std::list<Blob> blobs;
    std::for_each(blob.begin(), blob.end(), incrementXIfLessThanNine);
    return 0;
}

If you're using C++11:

#include <list>

struct Blob
{
    int x;
    int y;
};

int main()
{
    std::list<Blob> blobs;
    for(Blob& blob: blobs)
    {
        if(blob.x < 9)
        {
            blob.x++;
        }
    }
    return 0;
}

Need Your Help

What is the difference between SqlCommand.CommandTimeout and SqlConnection.ConnectionTimeout?

.net sqlconnection sqlcommand

Is there any difference between SqlCommand.CommandTimeout and SqlConnection.ConnectionTimeout in .NET?