我想在不迭代地图的情况下访问第三个元素(以正向和反向顺序)。
int main() {
map<int,int>mp;
vector<int>v={1,4,2,5,4,2,5,7,6,9,7,9,8};
for(int i=0;i<v.size();++i)
{
mp[v[i]]++;
}
return 0;
}
这里的预期输出是 4 2 和 7 2。
您可以使用std::advance函数,但请注意,地图容器不是为随机访问而设计的,因此即使您出于性能原因避免自己进行迭代,无论如何都会发生在幕后的情况,从而提供了线性时间复杂度。
// forward iterator
auto it_fwd = mp.begin();
std::advance(it_fwd, 2); // go to the 3rd item from the beggining
// backward iterator
auto it_bwd = mp.rbegin();
std::advance(it_bwd, 2); // go to the 3rd item from the end
std::cout << it_fwd->first << ':' << it_fwd->second << '\n';
std::cout << it_bwd->first << ':' << it_bwd->second << '\n';
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句