Modify elements of vector (by value, by reference) Function C++

Hani Goc picture Hani Goc · Oct 30, 2013 · Viewed 36.7k times · Source

I have a function where I have to modifiy the values of a vector. is it a good practice in C++ to return the vector?

Function 1:

vector<string> RemoveSpecialCharacters(vector<string> words)
{
    for (vector<string>::iterator it=words.begin(); it!=words.end(); )
    {
        if(CheckLength(*it) == false)
        {
            it = words.erase(it);
        }
        else{
            ++it;
        }
    }//end for

    return words;
}

Function 2:

void RemoveSpecialCharacters(vector<string> & words)
{
    for (vector<string>::iterator it=words.begin(); it!=words.end(); )
    {
        if(CheckLength(*it) == false)
        {
            it = words.erase(it);
        }
        else{
            ++it;
        }
    }//end for
}

Answer

billz picture billz · Oct 30, 2013

Your two functions serve for two different purposes.

  • Function 1: works as remove_copy. It will not modify the existing container; it makes a copy and modifies that instead.

  • Function 2: works as remove. It will modify the existing container.