gpt4 book ai didi

c++ - 删除 map 的最后 5 个元素

转载 作者:太空宇宙 更新时间:2023-11-03 10:42:29 25 4
gpt4 key购买 nike

我想从 std::map 中删除最后 5 个元素。

一种方法是:

  for(int i=0; i < 5; i++)
{
map<string, LocationStruct>::iterator it = myLocations.end();
it--;
myLocations.erase(it);
}

有没有不用循环的好方法?

谢谢,

最佳答案

一种实现方法的可编译演示。请注意,因为 map 迭代器不是随机访问迭代器,所以在调用 std::prev() 期间很可能在幕后涉及一个循环。

#include <iostream>
#include <map>
#include <string>

using namespace std::string_literals;

std::map<int, std::string> m = {
{ 0, "zero"s },
{ 1, "one"s },
{ 2, "two"s },
{ 3, "three"s },
{ 4, "four"s },
{ 5, "five"s }
};

auto main() -> int
{
for (const auto& entry : m) {
std::cout << entry.first << ", " << entry.second << std::endl;
}

// erase operation here
m.erase(std::prev(m.end(), 5), m.end());

std::cout << "\nafter erase \n\n";
for (const auto& entry : m) {
std::cout << entry.first << ", " << entry.second << std::endl;
}

return 0;
}

预期输出:

0, zero
1, one
2, two
3, three
4, four
5, five

after erase

0, zero

关于c++ - 删除 map 的最后 5 个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32161052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com