Re: vector subscript out of range
On May 11, 1:27 am, Andy <fru...@gmail.com> wrote:
[rearranged inline]
And what would you have us do? guess?
Can't you simply write a simple test program that iterates through the
vector's elements and recreates the problem? And post it? Any chance
that you compiled the program on Windows in debug mode (assuming
assertions won't trigger in release mode on that MAC?) Did you know
that vector has the at() member function that throws an exception when
'subscript' is out of range in both debug and release mode? What
version of VC++ is involved?
Why is it that these questions need be asked at all?
perhaps I am not in that detail about my question - cuz I am new to c+
+ and also new to this group.
On the Mac the error does not appear - also when I compile it in
Release mode. Everything works fine
Yes, I compiled it on Windows in Debug Mode
I will take a look at the at() member
I also use sometimes things like that instead of an iterator
(for i=0; i < vector.size(); i++) { ... }
(for i=vector.size()-1; i>0 ;i--) { ... }
This is your problem.
(for i=vector.size()-1; i>0 ;i--) { ... }
That loop does not access vector[0] so you probably modified i in the
body somehow. If i is of type unsigned int and it is set to 0 in the
body, the statement i-- does *not* result in a negative number (there
are no negative numbers in an unsigned range). Scary, isn't it?
I am using MS Visual C++ Express Edition on Windows XP Pro
with vector.begin and vector.end - so I wonder why this error happens.
Thanks a lot for any tip or hint
Andy
Uncomment the obvious error to catch the cute exception. The
std::vector is not required to throw anything when its elements are
accessed using operator[], not unlike the primitive array. Thats why
at() is there for.
#include <iostream>
#include <vector>
#include <stdexcept>
int main()
{
std::vector< int > v( 10 );
try
{
std::cout << "indexing up through vector:" << std::endl;
for ( size_t i = 0; i < v.size(); ++i )
{
std::cout << "v[" << i;
std::cout << "] = " << v.at( i );
std::cout << std::endl;
}
std::cout << "indexing down through vector:" << std::endl;
for ( size_t i = v.size(); i > 0; --i )
{
std::cout << "v[" << i - 1;
std::cout << "] = " << v.at( i - 1 );
std::cout << std::endl;
}
// std::cout << v.at(v.size()); // throws range_error
}
catch ( const std::exception & r_e )
{
std::cout << "Error: " << r_e.what();
std::cout << std::endl;
}
}
/*
indexing up through vector:
v[0] = 0
v[1] = 0
v[2] = 0
v[3] = 0
v[4] = 0
v[5] = 0
v[6] = 0
v[7] = 0
v[8] = 0
v[9] = 0
indexing down through vector:
v[9] = 0
v[8] = 0
v[7] = 0
v[6] = 0
v[5] = 0
v[4] = 0
v[3] = 0
v[2] = 0
v[1] = 0
v[0] = 0
*/
moral of the story: use iterators instead.