r/cpp_questions • • 7d ago

SOLVED Performance of std::vector

In the university we had to implement quicksort, the unsigned ints are stored in std::vector. I have accidentally discovered, that all algorithms, despite how students implemented them, are much faster when instead of directly accessing data from the vector like that:

arr[n]

we write:

unsigned int *a = arr.data()

and access that data by writing:

a[n]

But I can't understand why is that, in both cases it translates to one and the same: *(a + n)

The code is compiled on Clion IDE if that changes anything, no custom settings for compilation are used.

I can't directly share the algorithms for copyright reasons as they are not mine.

34 Upvotes

63 comments sorted by

View all comments

Show parent comment

4

u/Flimsy_Complaint490 7d ago

[] has no bound checks.

at() does bound checking.

6

u/didntplaymysummercar 7d ago

at() is guaranteed to throw if you're out of bounds.

[] on some standard library implementations will bounds check in debug or if you opt into it. MSVC does it out of the box in debug: "Expression: vector subscript out of range"

1

u/Normal-Narwhal0xFF 7d ago

That's true in the standard but debug builds could add vendor-specific range checks, just like optional "checked iterators". Since debug builds are for catching bugs ...