如何在地图c ++中获取第三个元素(从头到尾)

how to get the third element (from the beginning and from the end) in a map c++

我想在不迭代映射的情况下访问第三个元素(正向和反向顺序)。

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';