jeudi 17 octobre 2019

Why does my pointer to the first element of a vector lost?

#include <iostream>
#include <vector>
//#include <string>

struct Point {
    Point(int _x, int _y) {
        x = _x;
        y = _y;
    }

    int x;
    int y;
    Point *parent;
};

int main() {

    Point start(3, 4);
    std::vector<Point> points; 
    points.push_back(start);
    std::cout << points.back().x << "," << points.back().y << "\n";

    Point one(4, 5);
    one.parent = &points.at(0);
    //std::cout <<  "testing: " << one.parent->x << "," << one.parent->y << "\n";
    points.push_back(one);
    std::cout << "One: " << points[1].x << "," << points[1].y << "\n";
    std::cout << "One's parents: " << points[1].parent->x << "," << points[1].parent->y << "\n";

    Point two(10, 3);
    two.parent = &points.back();
    points.push_back(two);
    std::cout << "Two: " << points[2].x << "," << points[2].y << "\n";
    std::cout << "Two's parent: " << points[2].parent->x << "," << points[2].parent->y << "\n";

    Point three(12, 7);
    three.parent = &points[1];
    points.push_back(three);
    std::cout << "Three: " << points[3].x << "," << points[3].y << "\n";
    std::cout << "Three's parents: " << points[3].parent->x << "," << points[3].parent->y << "\n";


    return 1;
}

I get the following results: 3,4 One: 4,5 One's parents: 0,0 Two: 10,3 Two's parent: 4,5 Three: 12,7 Three's parents: 4,5

Even though I made one's parent point to the vector's first element, the value ends up being 0,0. But, the other pointers point to the element that I want it to.

Aucun commentaire:

Enregistrer un commentaire