1

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)?

Bob Gilmore
  • 12,608
  • 13
  • 46
  • 53
linofex
  • 340
  • 1
  • 2
  • 17
  • 3
    `iter->` and `(*iter).` are semantically identical, completely up to your style preference. The only (potential) difference is that the `->` operator is [able to be overloaded](https://stackoverflow.com/questions/221346/what-can-i-use-instead-of-the-arrow-operator). – Cory Kramer Jun 15 '16 at 17:45
  • 2
    Use `->`, it's what people typically expect to see. – GManNickG Jun 15 '16 at 17:49
  • @CoryKramer thank you! In C I use them as I prefer, but in C++, with classes, STL and other I thought that there was difference. – linofex Jun 15 '16 at 17:50
  • @CoryKramer the indirection operator `*` can also be overloaded, otherwise how `iterator` object indirection would work? – Ajay Jun 15 '16 at 18:51

3 Answers3

2
  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();

Davit Tevanian
  • 861
  • 8
  • 16
1

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 ->.

Austin Day
  • 141
  • 1
  • 8
1

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;
}
Ajay
  • 18,086
  • 12
  • 59
  • 105