vendredi 29 octobre 2021

How to cycle through smart pointer to a class with custom iterator

I have a smart pointer to a class with custom iterator. I need to iterate through it and couldn't find any examples.

struct SomeContrainer
{
   int a;
}

struct ListClass
{
   std::vector<SomeContrainer>::iterator begin() { return m_devs.begin(); }
   std::vector<SomeContrainer>::iterator end()   { return m_devs.end();   }                                         

   void add( const SomeContrainer& dev ) { m_devs.push_back( dev ); }

   private:
      std::vector<SomeContrainer> m_devs;
};

typedef std::unique_ptr<ListClass> ListPtr_t;


void Foo_Add( const ListPtr_t& list )
{
   SomeContrainer dev1, dev2;
   dev1.a = 10;
   dev2.a = 100;
   list->add(dev1);
   list->add(dev2);
}

void DoSomeWorkOtherList( const ListPtr_t& list )
{
   for( auto const& dev : list )    // <-- how to iterate other list ???
   {}
}

// -----------

ListPtr_t pMyList( new ListClass() );

Foo_Add( pMyList );
DoSomeWorkOtherList(pMyList );

It works fine if I don't use a smart pointer and have just an object ListClass list I'm using C++11 and can't upgrade.

Aucun commentaire:

Enregistrer un commentaire