Click here to Skip to main content
15,867,877 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a class which is derived from several types of STL containers and I wish to perform a range based for loop over a particular one of them such as in the example below What is the correct syntax Thank You Kindly

class cfoobar : public vector<int> , public map<int, int>
{
public:
     void foobar()
     {
// how to perform a range based for loop over the contents of vector<int>
          for (auto x : ? )
          {
               // ...
          }
     }
};


What I have tried:

C++
for(auto x : vector<int>::this>
for(auto x : vector<int>::*this>
for(auto x : *vector<int>::this>
Posted
Updated 14-May-20 7:54am
v2
Comments
Rick York 14-May-20 3:17am    
I can't think of a good reason for deriving from both a map and a vector. I can think of several good reason why not to.
BernardIE5317 14-May-20 13:51pm    
Your comment got me to realize I should be utilizing "is a" and "has a" relationships in my design Since a node is not a particular kind of vector or map but instead "has" children the vector of child nodes should be a member class not a base class As for the map it is simply a tool to access the vector and of course is not a base form of node so it also should be a member class Thank you kindly Cheerios
Rick York 15-May-20 2:30am    
That sounds much better to me. Best of luck with it.
BernardIE5317 14-May-20 4:33am    
I have a multiary tree Each node is a vector because it has children However when traversing the tree iteratively it is necessary to maintain a record of the pointer to the previously visited node When that node is a child of the current node it is then necessary to find the next child node in the vector in an efficient manner The map uses child node pointers as keys to provide the indices into the vector so that the next child pointer can be easily obtained Thank you for your comment Cheerios

1 solution

You derive your class from vector and map so class have both begin() and end() inherited from vector and the map. It actually does not make any sense but the syntax is this:
C++
class cfoobar : public std::vector<int>, public std::map<int, int>
{
public:
   void foobar()
   {
      // how to perform a range based for loop over the contents of vector<int>
      for (std::vector<int>::iterator it = std::vector<int>::begin(); it != std::vector<int>::end(); it++)
      {
         // ...
      }
   }
};
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900