r/cpp_questions • • 5d 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.

33 Upvotes

63 comments sorted by

View all comments

-5

u/vyuniverse 4d ago

Using the `[]` operator on a vector performs bounds checking; i.e. a check is done to see if you’re accessing an element within the size of the vector.

Try using `.at(n)` instead; this method doesn’t enforce bounds checking and should be equivalent to your workaround

5

u/esspeebee 4d ago

You have those two backwards. at() performs bounds checking while [] doesn't.

0

u/jevndev 4d ago

This comment isn't correct. std::vector<T>::operator[](size_type) (cppref) is standardized to not do bounds checking1. std::vector<T>::at(size_type) (cppref) is standardized to do bounds checking and throw a std::out_of_range if out of bounds. Whether a given implementation does bounds checking is vendor defined (and in some release modes, operator[] will do so), but it's against the standard.

1 (unless you're using C++26 with contract assertions and the implementation is hardened. But that's a new and widely unsupported feature and not really relevant here. I just figured I'd mention it in case I get "whatabout"-ed)

0

u/PijanyRuski 4d ago

Do one or two most popular compilers do it?