currently I am trying to understand how to move an element in Boost::ptr_list to the front.
I have been trying stuff like开发者_如何学编程 this:
boost::ptr_list<myObj> mylist;
boost::ptr_list<myObj> myiter;
// Do something useful
mylist.transfer(mylist.begin(), myiter, mylist);
This version the compiler acccepts, but my program crashes on the first call to transfer.
Another thing I tried was
mylist.push_front(mylist.release(myiter));
This the compiler rejects due to incompatible types.
What am I doing wrong? Thanks for your help.
I am assuming here you want to move the last element in the list to the front. If so here is one possible way to do it:
struct myObj
{
myObj( int i ) : m_i(i)
{
}
void print() const
{
std::cout << "i == " << m_i << std::endl;
}
private:
int m_i;
};
typedef boost::ptr_list<myObj> tMyList;
void PrintList( const tMyList& list )
{
std::cout << "List contains: " << std::endl;
tMyList::const_iterator itEnd = list.end();
for (tMyList::const_iterator it = list.begin(); it != itEnd; ++it )
{
it->print();
}
}
void test()
{
tMyList mylist;
mylist.push_back(new myObj(1));
mylist.push_back(new myObj(2));
mylist.push_back(new myObj(3));
PrintList(mylist);
//move last element to the front
tMyList::auto_type pBack = mylist.pop_back();
mylist.push_front( pBack.release() );
PrintList(mylist);
}
int main()
{
test();
return 0;
}
精彩评论