r/cpp_questions • u/MillenniumDev • 8d 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.
View all comments
Show parent comment
0
u/jevndev 8d 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 astd::out_of_rangeif 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)