pv******@gmail.com wrote:
Hi,
Once more a question (sorry for the different e-mail addresses [in
regard
to my other posts], here @ work we have to use Google to post to
newsgroups):
If I use an iterator, say from std::map, I initialize it like so:
<--- --->
std::map<int, myClass*myCollection;
std::map<int, myClass*>::iterator it = myCollection.begin();
for(; it != myCollection.begin(); ++it) { // do something }
---><---
For which reasons C++ uses the syntax above (I guess
because we use templates) ? Why is it not possible to
use myCollection.iterator it = myCollection.begin(); like
a kind of an inner class (Java style...)?
That would eliminate the need to retype std::map<int, myClass*>...
just to get an iterator. I know that I could use a typedef...
Binary regards (as one suggested in stead of my Brgds tag ;-) ),
Peter
Whats preventing you from doing so? Since this is a std::map?
Its your choice if you choose to expose iterators or to embed an
iterator class.
You only need to insure any exposed iterator is reset appropriately.
Note that resetting iterators is not neccessarily a costly operation
since you could, say, provide an overloaded swap(...) member function
that works with other containers.
#include <iostream>
#include <map>
template< typename T, typename P >
class Container
{
typedef typename std::map< const T, const P* const MapType;
typedef typename MapType::iterator IterType;
MapType themap;
public:
IterType iter_begin;
IterType iter_end;
IterType iter;
// lifecycle
Container() : themap(),
iter_begin(themap.begin()),
iter_end(themap.end()),
iter()
{
}
Container(const Container& copy)
{
std::swap(copy.themap, themap);
iter_begin = themap.begin();
iter_end = themap.end();
}
void insert(const T& r_t, const P* const ptr_m)
{
themap.insert(std::make_pair(r_t, ptr_m));
iter_begin = themap.begin();
iter_end = themap.end();
}
};
struct MyClass
{
int n;
};
int main()
{
const MyClass array[] = {{0},{1},{2},{3},{4}};
Container< int, MyClass container;
for( size_t i = 0; i < sizeof(array)/sizeof(MyClass); ++i)
{
container.insert(static_cast<int>(i), &array[i]);
}
for( container.iter = container.iter_begin;
container.iter != container.iter_end;
++container.iter )
{
// do whatever
}
}