D
D
Dmitry Ivanov2018-03-12 16:05:07
C++ / C#
Dmitry Ivanov, 2018-03-12 16:05:07

How to return a reference/pointer to an element of a vector?

We have a class (simplified):

class CUnit
{
public:
    bool FindElement(const string& search, CElement& result);
private:
    vector<CElement> mElements;
};

The FindElement function looks something like this:
bool CUnit::FindElement(const string & search, CElement& result)
{
    vector<CElement>::iterator it;

    for (it = mElements.begin(); it != mElements.end(); it++)
    {
        if ( <тут проверка соответствие критерию> )
        {
            result = *it;
            return true;
        }
    }
    return false;
}

With this approach, a copy of the element will be returned from the function.
But how to return a link/pointer to a vector element so that you can change the vector element itself (and not its copy)?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mercury13, 2018-03-12
@IDma88

one.

bool FindElement(const string& search, CElement*& result);

2.CElement* FindElement(const string& search);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question