-1

I have the following two structs that I use to define a line:

struct Point{
    double x;
    double y;
};

struct Line {
    unsigned int n_points;
    std::vector<Point> points;
};

I would like to iterate through the points vector after adding some data. I tried

int main(){
    Line line;
    // add some data to points vector with `push_back`

    // print content of `points`
    iter = line.points.begin();
    for(; iter != line.points.end(); ++iter){
        std::cout << iter.x << " " << iter.y << std::endl;
    }
}

This, however, does not work. Can someone explain me why?

Gilfoyle
  • 3,282
  • 3
  • 47
  • 83

2 Answers2

4

You only have syntax errors in your example. Fixed:

int main(){
    Line line;

    //vvv added auto
    auto iter = line.points.begin();
    for(; iter != line.points.end(); ++iter){
        //           vvvvvvv iter->x instead of iter.x. Same for iter.y
        std::cout << iter->x << " " << iter->y << std::endl;
    }
}

However, with modern C++, you can do the same more easily:

int main() {
  Line line;

  //            vvv make a reference if that matters
  for (auto const [x, y] : line.points) {
    std::cout << x << ' ' << y << '\n';
  }
}

This version uses the Range-based for loop and Structured binding declaration features from C++11 and C++17 respectively.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
2

There is syntax error in your code. Assuming you defined the type of iter before or you can use: auto iter = line.points.begin();

Here, iter is a type of an iterator. A . operator won't work & you need to use -> operator just like pointers as follows:

auto iter = line.points.begin();
    for(; iter != line.points.end(); ++iter){
        std::cout << iter->x << " " << iter->y << std::endl;
    }

You can refer here for more information http://www.cplusplus.com/reference/iterator/

simran-ahuja
  • 165
  • 4
  • Can you please explain in more detail why the `.` operator won't work? – Gilfoyle May 12 '20 at 11:26
  • 1
    @random9 `iter` is of type iterator. Using `.` you can access members of the iterator class. If you want to access object that iterator points to, you need to use `->` or dereference is first: `(*iter).x` – Yksisarvinen May 12 '20 at 12:01