vector function 'at'
Since the other direct access methods front(), back() and []开发者_C百科 do not check for bounds, does 'at' introduce too much overhead for these checking if the vectors are large and one wants to iterate over them sequentially? I guess if one is sure of the bounds, [] is a better direct access option.
That's why there're separate []
and at()
. If you're sure that you don't access out of bounds you use []
(or iterators), otherwise you may use at()
if you wish.
at()
cannot be quicker than []
, but "too much overhead" is really up to you to decide. I suggest profiling the code with []
and at()
and see whether it makes a significant difference.
If you want to iterate sequentially, then do neither.
It is preferable to use:
// C++03
BOOST_FOREACH(T const& t, vec) { }
// C++0x
for (T const& t: vec) { }
You'll get the maximum speed with no risk of stepping outside the defined range.
at
method is slightly slower than the subscript []
operator.
Here is a simple timing test.
#include <ctime>
#include <cstdio>
#include <vector>
#include <stdint.h>
#include <algorithm>
using namespace std;
// Pentium clock timer
extern "C" {
__inline__ uint64_t rdtsc() {
uint32_t lo, hi;
__asm__ __volatile__ (
"xorl %%eax,%%eax \n cpuid"
::: "%rax", "%rbx", "%rcx", "%rdx");
__asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
return (uint64_t)hi << 32 | lo;
}
}
vector<int>A;
uint64_t time_at()
{
uint64_t start=rdtsc();
srand(11101);
for(int i=0;i<10000000;i++)
int x=A.at(rand()%10000000);
uint64_t end=rdtsc();
return end-start;
}
uint64_t time_subscript()
{
uint64_t start=rdtsc();
srand(11101);
for(int i=0;i<10000000;i++)
int x=A[(rand()%10000000)];
uint64_t end=rdtsc();
return end-start;
}
int main()
{
for(int i=0;i<10000000;i++)
A.push_back(i);
printf("At ===> %llu\n",time_at());
printf("[] ===> %llu\n",time_subscript());
return 0;
}
For one, at
throws exception if the index is out of bounds, therefore requiring a compilation with exceptions enabled. That's likely one of the reasons it is just an additonal method for accessing vector elements.
精彩评论