problem in removing an element from vector array

I have two index values in my vector.
i want to remove one element from vector. i am doing like this

[output]if( (velleys[1] == velleys[0])  )
  velleys.erase( velleys.begin());

When i remove one element either from begin or last element . i get run time error which says "Expression : vector subscript is out of range"

What mistake i am doing ? Can any one guide me thanks
Note: my vector size is 2.
Note: my vector size is 2.

Not after you start removing elements.
hmm . so that's y i got run time error ?
So , i need to resize vector after removing element ?
That depends on what you're trying to accomplish.
Only one thing is for certain: don't try to access the second element of a vector that has less than two elements.
but i am removing 1st element in the vector. so why have run time error ? i think after removing i need to resize .but i checked many people example . they didnot resized it .
When you remove the first element, then vec[1] will become vec[0]. The vector size is now down to 1 and there isn't a vec[1] anymore.
When an element is erased, the size of the vector changes. It's not that you need to resize it, it's that the container is resized for you.

If, originally, your vector has a size of 2 a couple things happen when you erase the first element:

The first element is destroyed.
The 2nd element is moved to the former first element's position.
The vector is resized.

So, what was formerly at velleys[1] is now at velleys[0], and velleys[1] is no longer a valid way to access the vector.
yes i understand, but why my program crash then ? if velleys[1] is no longer exist then it should not make any problem.
It is a problem if you're trying to access velleys[1] again.
There's not enough context to determine what's causing your code to crash. Not respecting the new size of the vector was simply the most likely candidate.
Oh ok ,i catched my bug .

" It is a problem if you're trying to access velleys[1] again. "

You are right , i am code . i did that.
I found it just after reading your comment . thanks . :)
And tanks cire too .. :)

Last edited on
Topic archived. No new replies allowed.