I'm trying to design a simple container class for some data of different types based on a vector of structs, but the vector and struct are protected so that the implemenation of my container class can change independently of the interface.
[CODE=cpp]
using namespace std;
class MyContainer {
public:
// public stuff
protected:
struct Item {
float dataFlt;
int dataInt;
string dataStr;
} element;
vector<Item> storage;
};
[/CODE]
Now I want to provide an iterator for the items in MyContainer. One rather silly way would be to add to my class
[CODE=cpp]
class MyContainer {
...
public:
vector<Item>::i terator itr;
vector<Item>::i terator begin() { return storage.begin() }
vector<Item>::i terator end() { return storage.end()}
}
// to use iterator:
int main() {
MyContainer stuff;
// add some items
for(stuff.itr = stuff.begin(); itr < stuff.end(); itr++) {
//process items
}
return 0;
}
[/CODE]
I'm sure you're cringing at this point. I'd really like to do it in an STL-compliant way, something like defining stuff::iterator itr in main() and using that iterator. It seems I need do something like
[CODE=cpp]
#include <iterator>
class MyIterator :
public MyContainer,
public std::iterator <std::bidirecti onal_iterator_t ag, type> {
// overload the various operators
};
[/CODE]
but I'm not sure how do use this, in particular since 'type' should be something like vector<Item> but of course the Item struct is not defined in the global scope. Any tips would be greatly appreciated!
Thanks in advance,
Arnaud
[CODE=cpp]
using namespace std;
class MyContainer {
public:
// public stuff
protected:
struct Item {
float dataFlt;
int dataInt;
string dataStr;
} element;
vector<Item> storage;
};
[/CODE]
Now I want to provide an iterator for the items in MyContainer. One rather silly way would be to add to my class
[CODE=cpp]
class MyContainer {
...
public:
vector<Item>::i terator itr;
vector<Item>::i terator begin() { return storage.begin() }
vector<Item>::i terator end() { return storage.end()}
}
// to use iterator:
int main() {
MyContainer stuff;
// add some items
for(stuff.itr = stuff.begin(); itr < stuff.end(); itr++) {
//process items
}
return 0;
}
[/CODE]
I'm sure you're cringing at this point. I'd really like to do it in an STL-compliant way, something like defining stuff::iterator itr in main() and using that iterator. It seems I need do something like
[CODE=cpp]
#include <iterator>
class MyIterator :
public MyContainer,
public std::iterator <std::bidirecti onal_iterator_t ag, type> {
// overload the various operators
};
[/CODE]
but I'm not sure how do use this, in particular since 'type' should be something like vector<Item> but of course the Item struct is not defined in the global scope. Any tips would be greatly appreciated!
Thanks in advance,
Arnaud
Comment