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

16

u/Total-Box-5169 12d ago

Probably because optimizations are not enabled. Also instead a std::vector you should take a std::span so that function is not tied to a very specific type used to store data.

8

u/AndriesG04 12d ago

I think using std::span is only preferable if they know that they want the exact same function to be usable with the different storage type, otherwise using std::vector or a plain pointer is definitely fine. No need to overcomplicate the code when not needed

1

u/conundorum 11d ago

It's better to take std::vector if you know that the data is stored in a vector. It's bad design to genericise code when you know that the data is already tied to a single specific type.

Your advice is good in general, but it sounds like being specific is better for his assignment.