0

I have a class that i'm using for a trie

class Node {
public:
    map<char,Node*> node;
    bool flag = false;
};

int main(){
    Node table;
    for(auto x: table){}
    return 0;
}

I'm trying to iterate through it's elements but I keep getting errors

I checked stack for solutions and tried to use the iterator map method :

error: 'class Node' has no member named 'begin'
for (it = table->begin(); it != table->end(); it++){
                ^~~~~
error: 'class Node' has no member named 'end'
    for (it = table->begin(); it != table->end(); it++){

Also tried to use a for loop and got a similar error:

error: 'begin' was not declared in this scope
for(auto x: table){
            ^~~~

How can I iterate through the elements in another way or how can I fix these errors?

Hkyben
  • 5
  • 4
  • what's the type of `table`? – Harry Dec 29 '20 at 14:44
  • The table is of type (Node*) – Hkyben Dec 29 '20 at 14:47
  • 1
    Hi, welcome to StackOverflow! Please make a [Minimal Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) that shows exactly what you're writing and what errors you get. – Sprite Dec 29 '20 at 14:57
  • Doesn't change when I change it though – Hkyben Dec 29 '20 at 15:13
  • Your class `Node` should inherit `std::map` publicly. – KaiserKatze Dec 29 '20 at 15:16
  • 1
    @KaiserKatze That is dubious advice because standard containers are not designed to be polymorphic. I can work, but you have to beware of object slicing. Additionally standard containers do not have a `virtual` destructor so you also have to be careful how you store your derived type. See [Is it okay to inherit implementation from STL containers, rather than delegate?](https://stackoverflow.com/questions/2034916/is-it-okay-to-inherit-implementation-from-stl-containers-rather-than-delegate). Deriving from standard containers should not be recommended without mentioning the caveats. – François Andrieux Dec 29 '20 at 16:25
  • @FrançoisAndrieux Upvoted your comment. I didn't realize such an issue before. Thank you for your lesson. :D – KaiserKatze Dec 30 '20 at 10:08

1 Answers1

0

Node is not an iterable class. It's just a regular class, that happens to have a std::map as a member. What you want is to access the map object within `Node:

for (auto x : table->node)

Also, in the code you showed us, table is never initialized. I am assuming that in your real code, it is, but if not, fix that too. You can either use new Node to create an object, or else declare it as a value and not a pointer: Node table;

Tumbleweed53
  • 1,491
  • 7
  • 13