|
-
January 13th, 2004, 08:19 AM
#1
Creating a list with different (derived) elements
Hi !
I have lots of STL lists, lets say
list< A* > m_listA;
list< B* > m_listB;
list< C* > m_listC;
…..
where B derives from A, and C from B,….
Many times I have to return two or more different lists as one result, e.g.
list<A*> getList()
{
// return elements of m_listA + elements of m_listB
}
Of course, I can solve this by something like:
list< A* > res = m_listA;
List< B* >::iterator it = m_ListB.begin();
while( it != m_ListB.end() )
{
res.push_back( *it );
it++;
}
.. But it's annyoing to write this everytime I have to add two lists.
Do you have any ideas how to handle this typesafe, fast, fast-to-write,….. ?
Best regards,
Chris
-
January 13th, 2004, 09:06 AM
#2
Can't you just put all your objects in one list<A*> intead of different lists?
-
January 13th, 2004, 09:08 AM
#3
unfortunately not, because each list is used in its own context, but at many circumstances I need a collection of elements from two or more lists.
-
January 13th, 2004, 10:09 AM
#4
The insert() member function for std::list should work:
Code:
list<A*> res = m_listA;
res.insert(res.end(),m_listB.begin(),m_listB.end());
I have an old version of VC++ (version 5). It does not compile
with that compiler. In that case you can use std::copy()
Code:
#include <algorithm> // for std::copy()
#include <iterator> // for back_inserter()
list<A*> res = m_listA;
copy(m_listB.begin(),m_listB.end(),back_inserter(res));
-
January 13th, 2004, 11:00 AM
#5
The first version also doesn't compile in VC6.0 (that's what I've tried in my first attempt), but std::copy is fine !
Thanks a lot !!!!
-
January 14th, 2004, 05:42 AM
#6
A different approach (and even more advanced) would possibly be more performant:
I create a new type of iterator, which can iterate over different lists (with derived elements), e.g.
list< A* >::myIterator it = getListItr();
while( it.next() )
{
// do the work
it++;
}
the iterator should only store pointers to the lists (not copy the elements of the list)
The question is, how can I store pointers to different lists (m_listA, m_ListB,.....) in one common list (which should be done in "getListItr") ?
Or is there any possibility to store iterators of these lists ?
Thanks !!
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|