Блог пользователя Jbi

Автор Jbi, история, 2 года назад, По-английски

Hey cf ppl,

I was just wondering why set.count() works a lot faster than using vector.find(), from personal coding experience

This question seems to have already been answered on stack overflow, but it gave a what I thought as an incorrect answer, telling me that vector.find() would run faster than set.count() because it breaks as soon as it reaches the first occurence while set.count() would continually iterate through the whole array.

Thanks

  • Проголосовать: нравится
  • +7
  • Проголосовать: не нравится

»
2 года назад, скрыть # |
 
Проголосовать: нравится +13 Проголосовать: не нравится

std::set::count is logarithmic in size, std::find on vector is linear in size.

https://cplusplus.com/reference/set/set/count/

https://cplusplus.com/reference/algorithm/find/

»
2 года назад, скрыть # |
 
Проголосовать: нравится +3 Проголосовать: не нравится

Because set is sorted so presence of any element (element can only occur once in a set so finding count is equivalent to finding presence of element) can be found in log(n) time