dimanche 25 juillet 2021

How to put the iterator to nth element of a custom class?

I have a custom class MyData.

class MyData
{
  private:
      int data;
  public:
      int getData() const
          {
        return data;
      }
      MyData(int val): data(val) { cout<<"Constructor invoked"<<endl; }
      MyData (const MyData &other) 
          {
         cout<<"Copy constructor invoked"<<endl;
         data = other.data;
      }
      MyData& operator =(const MyData &other)
      {
          cout<<"Assignment operator invoked"<<endl;
          data = other.data;
          return *this;
      }
      friend ostream& operator<<(ostream &os, const MyData &d)
          {
           cout<<"<< operator overloaded"<<endl;
           os<<d.data;
           return os;
      }
};

in my main function, I have

list<MyData> data2{12,21,32,113,13,131,31};

I want my iterator to 4th element let's say directly rather than doing increment++ operation each time. How can I do so?

list<MyData>::iterator it = data2.begin();
it+=4; //error since I cannot increment this???-compile time error.

I am doing like this -

it++; it++; it++; it++; 

What is the correct way so that the iterator directly points to the 4th element?

I tried using advance like advance(data2.begin(),3);. However, this throws an error saying

error: cannot bind non-const lvalue reference of type ‘std::_List_iterator<MyData>&’ to an rvalue of type ‘std::__cxx11::list<MyData>::iterator’ {aka ‘std::_List_iterator<MyData>’}
   data1.splice(it, data2,advance(data2.begin(),3),data2.end()); //splice transfer range.

Basically, I am doing this for splicing the list from another list with one element or some time range.

Aucun commentaire:

Enregistrer un commentaire