简体   繁体   English

std::map::upper_bound 与 std::upper_bound 性能

[英]std::map::upper_bound vs std::upper_bound performance

In some CP contest (it is important) I have used 2 versions of upper_bound to find upper bound in my std::map :在一些 CP 比赛中(这很重要),我使用了两个版本的 upper_bound 来在我的std::map找到上限:

Algorithm upper bound (1) :算法上限(1)

auto itr = std::upper_bound(s.begin(),s.end(), somenumber);

if(itr == s.end() || *itr > somenumber2)
{
//dosth
} else
//dosth2
}

std::map::upper_bound (2) : std::map::upper_bound (2)

auto itr = s.upper_bound(somenumber);

if(itr == s.end() || *itr > somenumber2)
{
//dosth
} else
//dosth2
}

Both versions works if I put small input by hand.如果我手动输入小输入,两个版本都可以使用。 But when comes to ~500.000 input (1) exceeded the time limit ( 4 seconds ) but (2) do the job in 0.5/4.0 second .但是当涉及到~500.000输入时(1)超过了时间限制 ( 4 seconds ) 但(2)0.5/4.0 second
I checked at docs algorithm/upper_bound and map/upper_bound and both have O(c log(n)) complexity (I think that in both cases c should be similar.我检查了 docs algorithm/upper_boundmap/upper_bound并且都具有O(c log(n))复杂度(我认为在这两种情况下c应该相似。
So the question is - what caused that difference?所以问题是 - 是什么导致了这种差异?

The cppreference page for std::upper_bound says that the number of comparisons done is logarithmic, but it also continues: std::upper_boundcppreference 页面说完成的比较次数是对数的,但它也继续:

However, for non-LegacyRandomAccessIterators, the number of iterator increments is linear.但是,对于非 LegacyRandomAccessIterators,迭代器增量的数量是线性的。

std::map does not have random access iterators and therefore std::upper_bound will be allowed to have linear time complexity in the iterator distance due to increments, while std::map::upper_bound is required to have logarithmic time complexity in the size of the container. std::map没有随机访问迭代器,因此std::upper_bound由于增量将被允许在迭代器距离上具有线性时间复杂度,而std::map::upper_bound需要在大小上具有对数时间复杂度的容器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM