views:

130

answers:

4

I have a class that has a vector of objects. What do I need to do to return one of this objects and change it outside the class, keeping the changings? Is it possible to do with regular pointers? Is there a standard procedure? (And yes, my background is in Java.)

+1  A: 

If the vector holds pointers to objects any change to one of the objects returned from the vector (or more accurately the object pointed) will affect the instance inside the vector as well.

Dror Helper
+4  A: 

Your question is a bit vague, but here's an example:

class foo
{
public:
    foo()
    {
        vec.resize(100);
    }

    // normally would be operator[]
    int& get(size_t pIndex)
    { // the return type is a reference. think of it as an alias
        return vec[pIndex]; // now the return value is an alias to this value
    }

private:
    std::vector<int> vec;
};

foo f;
f.get(10) = 5;
// f.get(10) returned an alias to f.vec[10], so this is equivalent to
// f.vec[10] = 5

The FAQ has a nice section on references.

Also, if you're new to C++ don't try learn with online resources. If you haven't got a book, you should, they're really the only good way to learn the language.

GMan
+1, but you might want to show the declaration of vec for added clarity.
Cam
@incrediman: It's in the private section of the class, unless I'm misunderstanding.
GMan
You should emphasize the detail about returning a reference. For someone new to the language, it may not obvious that's the "magic" here.
R Samuel Klatchko
@GMan: Haha - not sure how I missed that :)
Cam
A: 

If you have std::vector where A is your class, you could return a std::vector::iterator.

class A {
  public: int a;
};

std::vector<A> v = ...;
std::vector<A>::iterator it = v.begin(); // access to the first element
it = v.begin() + 5; // access to the 5-th element (vector can do random access)
// 'it' can now be used elsewhere
it->a = 0; // changes are reflected in the object inside the vector
*it = A(); // changes the object hold by the vector

Beware, that iterators may be invalidated, if the vector changes!

Danvil
A: 

You need to return either a reference or a pointer to the object.

type &getref();   // "type &" is a reference
type *getptr();   // "type *" is a pointer

The caller will then have access to the underlying object.

But you then need to make sure the object does not move (which can have if a vector has to grow). You may want to think about using a std::list instead.

R Samuel Klatchko