Powereleven
Powereleven

Reputation: 329

Can you iterate through class objects without a list or vector?

Suppose you have a class Class and you create 2 objects

  Class *obj1 = new Class();
  Class *obj2 = new Class();

I know you can create a list and push_back the objects and then call

  for (auto i : list_name) i->function();

but is there a way to iterate like this?

  for(auto i:Class) i->function();

Upvotes: 2

Views: 567

Answers (3)

Daniel Langr
Daniel Langr

Reputation: 23497

Not exactly clear what you want, but you can also register all instances of your Class (if it's yours):

class Class {
  public:
    static std::set<Class*> instances;
    Class() { instances.insert(this); }
    ~Class() { instances.erase(instances.find(this)); }
    void function();
};
std::set<Class*> Class::instances;

and then iterate over all live Class instances as follows:

Class c;
auto upc = std::make_unique<Class>();
std::vector<Class> vc(4);

for (auto i : Class::instances)
  i->function();

Upvotes: 0

Ron
Ron

Reputation: 15501

No you can not use a class name in place of a range_expression inside a range based loop as class does not represent a container nor a range of values. You have freestanding instances of Class. You would need to store your instances in one of the following:

  • either an array or
  • an object for which begin and end member functions or free functions are defined or
  • a braced-init-list

and then use one of those inside a range based loop.

Upvotes: 3

Slava
Slava

Reputation: 44248

Yes you can:

for( auto i : { obj1, obj2 } ) i->function();

live example

Upvotes: 8

Related Questions