Steve Pope wrote in message ...
Alan said:
Alf P. Steinbach wrote:
1. Use 'at' instead of '[]' (except perhaps after profiling).
See my other post in this thread.
{ // main() or function
try{
std::vector<int> Vint( 2 );
std::cout<< Vint.at( 3 ); // out_of_range
} // try
catch( const std:
ut_of_range &Oor ){
std::cout<<"caught: "<<Oor.what()<<std::endl;
}
catch( ... ){ // catch anything not caught above.
std::cout<<"caught something (maybe the flu!!)"<<std::endl;
}
}
Alf,
Could you explain why you advise #1 [snip] and what is going
on in #2?
I'm curious as well. What is wrong with resize(0) ?
(Tangentially, I keep reading the subject line of this thread
as containing vector<newbie>.)
S.
// Prove it for yourself:
{ // main() or function
std::vector<double> values(10);
std::cout << values.size() << std::endl;
std::cout << values.capacity() << std::endl;
values.clear();
// values.resize(0); // same
std::cout << values.size() << std::endl; // S/B '0'
std::cout << values.capacity() << std::endl; // clear() doesn't re-size
std::vector<double>( ).swap( values );
// You are swapping an empty (un-named) vector with your vector 'values'.
std::cout << values.size() << std::endl; // S/B '0'
std::cout << values.capacity() << std::endl; // S/B '0'
}