gpt4 book ai didi

C++ 查找并删除 multimap 元素

转载 作者:行者123 更新时间:2023-11-30 00:55:15 25 4
gpt4 key购买 nike

我需要添加、存储和删除一些对象对,例如个人-爱好。任何人都可以有多个爱好,几个人也可以有相同的爱好。那么,multimap 是一个很好的容器,对吧?

在添加一对之前,我需要知道它是否尚未添加。如我所见here没有标准的类方法可以知道,如果具体的对,例如Peter-Football 存在于 MM 中。因此,我编写了一个方法,如果该对存在则返回一个正整数(等于 mm.begin() 和对迭代器之间的距离),否则返回 -1

然后我需要删除一些对。我调用我的 find 方法,该方法返回一些正整数。我调用 myMultiMap.erase(pairIndex); 但由于某种原因没有删除该对。那是我的问题。显然 erase 方法需要一个 iterator,而不是 int。问题是:如何将整数转换为迭代器?

谢谢!

更新:我试过这个 c.begin() + int_value 但得到一个错误 error: no match for ‘operator+’ on this line....

最佳答案

并不是我赞成你的方法,但是如果 intbegin() 和有问题的迭代器之间的距离,你可以只使用

c.begin() + int_value

std::advance(c.begin(), int_value)

获取迭代器。不是随机访问迭代器的迭代器需要第二个版本。

为了您的个人理智(以及程序的速度),我建议您以某种形式直接返回迭代器。

有许多可能的接口(interface)可以以这种或另一种方式解决这个问题。我所谓的“旧 C 方式”将通过 out 参数返回:

bool find_stuff(stuff, container::iterator* out_iter) {
...
if(found && out_iter)
*out_iter = found_iter;
return found;
}

使用它:

container::iterator the_iter;
if(find_stuff(the_stuff, &the_iter)) ...

if(find_stuff(the_stuff, 0)) // if you don't need the iterator

这不是惯用的 C++,但 Linus 会很高兴。

第二种可能且理论上合理的版本是使用类似 boost::optional 的东西来返回值。这样,您要么返回一些值,要么不返回任何值。

boost::optional<container::iterator> find_stuff(stuff) {
...
if(found && out_iter)
return found_iter;
return boost::none;
}

使用:

boost::optional<container::iterator> found = find_stuff(the_stuff);
if(found) {
do something with *found, which is the iterator.
}

if(find_stuff(the_stuff)) ...

第三种可能的解决方案是采用 std::set::insert 方式,即。返回由标志和值组成的一对:

std::pair<bool, container::iterator> find_stuff(stuff) {
...
return std::make_pair(found, found_iter);
}

使用:

std::pair<bool, container::iterator> found = find_stuff(the_stuff);
if(found.first) ...

关于C++ 查找并删除 multimap 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12781201/

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