Objects in vector accessing

Hello! I need help with one task.

class Data {
int x;
int y;
};

class Container {
private:
vector<Data> v1;
public:
// push object into a vector
void add(Data d) {
v1.push_back(d);
}

int main() {

Data ob1(3,4);
Data ob2(7,9);

Container myobjects;
myobjects.add(ob1);
myobjects.add(ob2);

return 0;
}

My job is to change y to 5 in ob1 and x to 10 in ob2, but it must be through container "myobjects". So for ex. program must find in Container "myobjects" ob2 access y and chages its value to 5.

I don't know how to access variable x or y

Thank you for any help!
Last edited on
That isn't your actual code, because you don't have a 2-arg constructor for Data declared or implemented. But anyway,

Assuming you want to keep vector<Data> v1 private, you need to have access functionality.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Data {
  public:
    Data(int x, int y) : x(x), y(y) {}

    int x;
    int y;
};

class Container {
  private:
    vector<Data> v1;
  public:
    void add(Data d) {
        v1.push_back(d);
    }
    Data& get(size_t index) {
        return v1[index];
    }
};

//  First object is index 0, second object is index 1
myobjects.get(0).x = 42; //or whatever.
myobjects.get(1).y = 3; 


Note: I suggest only having ob1 and ob2 be temporaries in your code, because their only purpose is to be added to the collection.

1
2
3
4
5
6
7
8

Container myobjects;
myobjects.add( Data(3, 4) );
myobjects.add( Data(7, 9) );

myobjects.get(0).y = 5;
myobjects.get(1).x = 10;

Last edited on
Yeah, it works very well. Thank you
Topic archived. No new replies allowed.