PtK
PtK

Reputation: 79

Manipulate members of vector in class

I am getting started on writing classes and have the following question. Suppose I have the following class:

class foo
{
private:
    int bar;
public:
    foo(int bar): bar(bar){}
    void set_bar(int ubar){bar=ubar;}
    int get_bar(){return bar;}
};

Now I want to write a class that contains instances of foo.

class foo_cont
{
private:
    vector<foo> foo_vec;
public:
    foo_cont(){}
    void add_element(foo f1){foo_vec.push_back(f1);}
};

Lets say I make an instace of foo_cont f1; and fill foo_vecit with instances of foo. How do I modify the elements of foo_vec with set_bar()?

Edit: Since I am quite new to stack overflow this might be a really stupid question but why am I getting downvotes?

Upvotes: 0

Views: 85

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311068

You could define operator [] for class foo_cont. For example

class foo_cont
{
private:
vector<bar> foo_vec;
public:
    // ...
    bar & operator []( size_t i )
    {
        return foo_vec[i];
    }   
    const bar & operator []( size_t i ) const
    {
        return foo_vec[i];
    }   
};

For example

for_cont[i].set_bar( 10 );

In any case you need to provide accessors for the elements of the vector if you are going to change them outside the class scope.

Upvotes: 2

R Sahu
R Sahu

Reputation: 206697

How do I modify the elements of foo_vec with set_bar()?

Inside the class foo_cont

If you want to call set_bar() on the first element of the vector in foo_cont, you use:

foo_vec[0].set_bar(10);

If you want to call set_bar() on the n-th (by index) element of the vector in foo_cont, you use:

foo_vec[n].set_bar(10);

By users of the class

You can provide access to the n-th element of foo_vec through operator functions or by providing an accessor function to the vector itself.

bar& operator[]( size_t i )
{
    return foo_vec[i];
}   
bar const& operator[]( size_t i ) const
{
    return foo_vec[i];
}   

and use it as:

foo_cont f1;
f1.add_element(10);
int a = f1[0].get_bar();

or

std::vector<foo>& get_foo_vector()
{
   return foo_vec;
}

std::vector<foo> const& get_foo_vector() const
{
   return foo_vec;
}

and use it as:

foo_cont f1;
f1.add_element(10);
int a = f1.get_foo_vector()[0].get_bar();

Upvotes: 0

Related Questions