linofex
linofex

Reputation: 340

Access an element with iterator

Consider this code:

#include <vector>
#include <iostream>
class num{
  int a;
  int b;

    public:
        num(int a_, int b_): a(a_), b(b_){}
        int Geta(){return a;}
        int Getb(){return b;}

};

int main(){
    num a(2, 5);
    num b(32, 654);
    std::vector<num> nums;
    nums.push_back(a);
    nums.push_back(b);
    std::vector<num>::iterator iter = nums.begin();
    std::cout << iter->Geta()<< " " <<(*iter).Getb() << std::endl;
    return 0;
}

This works, but I don't know which way is better to access the element of the array with the iteratoriter-> or (*iter).

I think that this example is a particular case where both works. Can you give me a code where is possible to see the difference (and why)?

Upvotes: 1

Views: 16986

Answers (3)

Davit Tevanian
Davit Tevanian

Reputation: 861

  1. -> for accessing object member variables and methods via pointer to object.

  2. . for accessing object member variables and methods via object instance.

But container iterators like pointers to some data structures and in my opinion (1.) more convenient for usage.

In case when you have vector of pointers, you need notice that you have pointers (iterators) to pointers (vector elements) and use this syntax (*iter)->Geta();

Upvotes: 2

AmirShrestha
AmirShrestha

Reputation: 21

With C++11 features, we can also make accessing of elements cleaner as in the following example using range based for loop.

for(const auto& elem:nums)
{
    std::cout << elem.Geta() << " " <<elem.Getb() << std::endl;
}

Upvotes: 1

Austin Day
Austin Day

Reputation: 161

An example where it would make a real difference, is when you are iterating over pointers, like so:

std::vector<num*> nums;
for (auto it = nums.begin(); it != nums.end(); it++) {
    (*it)->getA();
}

I don't know of any way of accomplishing this with using only ->.

Upvotes: 3

Related Questions