0
struct Vertex {
    float x, y, z;
};

std::ostream& operator<<(std::ostream& stream, const Vertex& vertex) {
    stream << vertex.x << "," << vertex.y << "," << vertex.z;
    return stream;
}

int main() {
    std::vector<Vertex> vertices;
    vertices.push_back({ 1, 2, 3 });
    vertices.push_back({ 4, 5, 6 });

    for (int i = 0; i < vertices.size(); i++) {
        std::cout << vertices[i] << std::endl;
    }

    for (Vertex& v : vertices) {
        std::cout << v << std::endl;
    }

    std::cin.get();
}

"vertices" is the name of the vector and "Vertex" is the type so what exactly is "v"? Is that a name?

  • 1
    The two loops are equivalent; one is just using a range-based for loop, probably to demonstrate that it's easier to read and write. (Should probably be `const Vertex&` though just to be sure) – AndyG Oct 21 '20 at 18:18
  • @AndyG Actually `vertices[i]` would be a non-const reference. – cigien Oct 21 '20 at 18:20
  • do you know what a range based for loop is ? Not quite clear why you only ask about `v` not anything surrounding that – 463035818_is_not_an_ai Oct 21 '20 at 18:20
  • 1
    @cigien: Yes, I know. The two loops are equivalent like I said. But if we can specify `const` here, we should in order to better indicate we don't intend to change anything. – AndyG Oct 21 '20 at 18:21
  • If you don't plan to change the items in the vector in the range based for loop you should use this: `for (const Vertex& v : vertices) {` or `for (const auto& v : vertices) {` – drescherjm Oct 21 '20 at 18:26
  • @AndyG Yes, definitely. I just thought the comment meant, it needs to be `const Vertex&` to be equivalent. – cigien Oct 21 '20 at 18:26
  • 1
    @cigien: I can see why you left your reply then! Sorry for the ambiguity! – AndyG Oct 21 '20 at 18:27
  • @idclev463035818 yeah I know what range based loops are conceptually I just didn't know what v specifically was for. The answer below cleared it up. – Taylor Reich Oct 21 '20 at 18:32

1 Answers1

2

v is a reference to each element in the vector when iterating over it

Martin G
  • 17,357
  • 9
  • 82
  • 98