我有以下的(簡化)代碼:升壓multi_index反向迭代擦除麻煩
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
namespace bmi = boost::multi_index;
#include <string>
#include <iostream>
#include <cassert>
using Container = boost::multi_index_container<
std::string,
bmi::indexed_by< bmi::ordered_non_unique< bmi::identity<std::string> > >
>;
/// Get the base of a non-reverse iterator. It's the iterator itself.
inline
Container::iterator const&
iter_base(Container::iterator const& it)
{
return it;
}
/** Get a non-reverse iterator that points at the same element as the given reverse_iterator.
*
* @param rit reverse_iterator
* @return a (non-reverse) iterator that points to the same element.
* @pre @p rit is dereferenceable (not equal to @c rend() of whatever container @p rit came from)
*/
inline
Container::iterator
iter_base(Container::reverse_iterator const& rit)
{
auto bit = rit.base();
// if 'rit' is a reverse iterator: &*(rit.base() - 1) == &*rit
return --bit;
}
template <typename IT>
void evict(Container& c, IT rb, IT fin)
{
std::vector<std::string> result;
for (; rb != fin;) {
if (rb->size() == 3) {
auto victim = rb;
++rb;
std::cout << "victim->" << *victim << ", next->" << (rb==fin ? std::string{"THE END"} : *rb) << "\n";
auto next = c.erase(iter_base(victim));
std::cout << "size=" << c.size() << "\n";
for (auto const& s : c) {
std::cout << "remain: " << s << "\n"; // bar - baz - foo
}
rb = IT(next);
(void)next;
}
else {
result.push_back(*rb);
}
}
}
int main(int argc, char**)
{
bool forward = (argc == 1);
Container c;
c.insert("foo"); // will be last
c.insert("bar");
c.insert("baz");
if (forward) {
auto b = c.lower_bound("baz");
std::cout << ">> " << *b << "\n"; // prints baz
auto rb = (b);
std::cout << "<< " << *rb << "\n"; // prints baz
std::cout << "<< " << *iter_base(rb) << "\n"; // prints baz
evict(c, rb, c.end());
}
else {
auto b = c.upper_bound("baz");
std::cout << ">> " << *b << "\n"; // prints foo
auto rb = Container::reverse_iterator(b);
std::cout << "<< " << *rb << "\n"; // prints baz
std::cout << "<< " << *iter_base(rb) << "\n"; // prints baz
evict(c, rb, c.rend());
}
}
真正的代碼並不僅僅是抹去更多,但這足以說明行爲。
EDITED顯示循環中不會發生任何刪除。 根據使用哪種迭代器,項目應按正向或反向順序添加到result
。
當不帶參數運行,如預期forward==true
和輸出:
>> baz
<< baz
<< baz
victim->baz, next->foo
size=2
remain: bar
remain: foo
victim->foo, next->THE END
size=1
remain: bar
當與一個參數,forward==false
運行並且輸出是:
>> foo
<< baz
<< baz
victim->baz, next->bar
size=2
remain: bar
remain: foo
segmentation fault (core dumped)
(未如預期)
使用地址清理程序進行編譯顯示了第42行(++ rb行)中的免費堆使用情況。
看起來,調用erase(victim)
以某種方式使rb
失效,即使擦除不應該使任何其他迭代器失效。
任何想法我做錯了什麼?
不幸的是,這並沒有幫助。剩餘堆使用(在'++ next'行中)。 – Bulletmagnet
您是否直接複製了建議的代碼*逐字*?注意例如(if; rb!= fin)for(;;)'部分。 –
對不起,提出的解決方案確實是錯誤的。編輯一個希望正確的選擇。 –