Re: comparing string elements
tazmaster@rocketmail.com
"James Kanze" <james.kanze@gmail.com> wrote in message
news:9765b9c4-9062-4a40-8fc9-7db46286cc70@s13g2000prd.googlegroups.com...
On Feb 20, 11:23 am, "Jim Langston" <tazmas...@rocketmail.com> wrote:
MC felon wrote:
what's the best way to compare two string elements?
std::string cstr;
if ( cstr.at(3) == cstr.at(2)) //do something
or
std::string cstr;
if ( cstr[3] == cstr[2]) //do something
?
[] is a *little* faster, but should only be used when it is
known that the length of the string is greater than the index.
If it is not sure, .at() should be used.
If using an out of bounds index is an error, you should use [],
rather than at(). At least with the implementations I use, []
treats an out of bounds index as an error condition; at() treats
it as an exceptional (but not wrong) situation.
I.E.
if ( cstr.size() < index )
{
if ( cstr[index] == cstr[index] // do something
}
Of course, that check for size() brings it's own overhead, so
in that case just use .
More frequently, you'll have something like:
assert( index < cstr.size() ) ;
Except, of course, that this code is normally in the operator[]
function itself.
============
I see a different result. This program in debug mode:
#include <vector>
#include <iostream>
int main()
{
std::vector<int> data(5);
try
{
data.at(5) = 5;
}
catch (...)
{
std::cout << "Error1\n";
}
try
{
// Causes run time overflow
data[5] = 5;
}
catch (...)
{
std::cout << "Error2\n";
}
}
will output
"Error1"
then tell me that memory has been corrupted.
That being the case isn't it opposite of what you say? That if an overflow
is an error condition then .at() should be used.
I was always lead to be leive that at() would throw on overflow, [] would
not check.