gpt4 book ai didi

c++ - 为什么 boost-multi-index 会返回一个错误的迭代器?

转载 作者:行者123 更新时间:2023-11-28 00:54:42 24 4
gpt4 key购买 nike

Boost 文档说 iterator_to 返回一个有效的迭代器,但下面的代码显示发生了其他事情。

All indices of Boost.MultiIndex provide a member function called iterator_to which returns an iterator to a given element of the container

http://www.boost.org/doc/libs/1_51_0/libs/multi_index/doc/tutorial/indices.html#iterator_to

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/random_access_index.hpp>

using boost::multi_index_container;
using namespace boost::multi_index;

struct Test
{
int id;
std::string name;
};

struct idx{};
struct id{};
struct name{};

typedef boost::multi_index_container<
Test*,
indexed_by<
random_access<tag<idx> >,
ordered_unique<tag<id>, member<Test, int, &Test::id> >,
ordered_unique<tag<name>, member<Test, std::string, &Test::name> >
>
> TTestTable;

class TestTable : public TTestTable
{
public:
// Fill table with some values
TestTable()
{
Test* test1 = new Test();
Test* test2 = new Test();
Test* test3 = new Test();
Test* test4 = new Test();
test1->id = 1;
test2->id = 2;
test3->id = 3;
test4->id = 4;
test1->name = "name1";
test2->name = "name2";
test3->name = "name3";
test4->name = "name4";

push_back(test1);
push_back(test2);
push_back(test3);
std::cout << at(0)->name << std::endl;
std::cout << at(1)->name << std::endl;
std::cout << at(2)->name << std::endl;

typedef TTestTable::index<idx>::type test_table_by_index;
test_table_by_index::iterator it = get<0>().iterator_to(test1); // gives back a wrong iterator

std::cout << get<idx>().iterator_to(test1) - get<idx>().begin() << "\n"; // WRONG
replace(iterator_to(test1), test4); // CRASH
replace(it, rule4); // CRASH
}
};

int
main(int argc, char **argv)
{
TestTable table;

return 0;
}

最佳答案

从您提供的链接:

// The following, though similar to the previous code,
// does not work: iterator_to accepts a reference to
// the element in the container, not a copy.
int x=c.back();
c.erase(c.iterator_to(x)); // run-time failure ensues

您没有将引用传递给 iterator_to,您传递的是一个拷贝。

以下应该有效:

Test* const& test1_ref = at(0);

typedef TTestTable::index<idx>::type test_table_by_index;
test_table_by_index::iterator it = get<0>().iterator_to(test1_ref);

std::cout << get<idx>().iterator_to(test1_ref) - get<idx>().begin() << "\n";
replace(iterator_to(test1_ref), test4);

顺便说一句,我不认为 boost::multi_index_container 被设计成用作基类,因为它们 don't provide a virtual destructor .

关于c++ - 为什么 boost-multi-index 会返回一个错误的迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12126637/

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