-3

Now in my program I have some data to store. I can store them in std::map or std::vector, either works. But I want to know which is faster push_back in vector or insert in map?

Taitai
  • 584
  • 2
  • 7
  • 18
  • 3
    `vector` and `map` are quite different. What is the actual type you're storing? A `map` wont allow duplicates, and they both denote different things, so think first about readability. – Tas Oct 16 '18 at 04:41
  • There is already a question like this: Visit – Archit J Oct 16 '18 at 04:43

1 Answers1

0

According to https://en.cppreference.com the complexity of map::insert is "Logarithmic in the size of the container" while vector::push_back is "Amortized constant".

This doesn't tell us which one is fastest when the container holds e.g. 10 elements but it does tell us that for large containers vector::push_back will be fastest.

Also notice that a vector allows you to reserve capacity up front.

Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
  • 1
    "This doesn't tell us which one is fastest when the container holds e.g. 10 elements but it does tell us that for large containers vector::push_back will be fastest." - No, that's not what it does. In fact, it's a lot slower for large containers in the bad case. What it does say is that while a single push_back can be slow, repeated calls to push_back will average out to constant complexity. – Sebastian Redl Oct 16 '18 at 05:21