OnTheFly
OnTheFly

Reputation: 2101

Setter for class vectors in C++

void setVector(vector<string> aStringVec)
{

    for(std::vector<string>:: iterator s = str1.vec.begin(); s != str1.vec.end(); ++s)
    {
        classVector.pushback(*s);
    }

}

If I do classVector = aStringVec, classVector will point to the pointer to the first element of aStringVec, since vectors are considered to be arrays, and may disappear, because it's on the stack, right?

So is this the right way to write a setter for a class vector, and can I call it anywhere?

Upvotes: 1

Views: 445

Answers (2)

Praetorian
Praetorian

Reputation: 109189

You don't need a loop at all for appending elements to an existing vector. Use vector::insert.

void setVector(vector<string> const& aStringVec)
{
  classVector.insert(classVector.end(), aStringVec.begin(), aStringVec.end());
}

I changed the function argument to a const&. const because you're not going to modify the input vector within your function, and you should pass by reference instead of by value to avoid unnecessary copying.

Instead if you want to replace the contents of classVector with that of the input argument's, then your function should be

void setVector(vector<string> aStringVec)
{
  classVector = std::move(aStringVec);
}

In this case you should pass the argument by value because you're going to move from it within the function.

Upvotes: 1

juanchopanza
juanchopanza

Reputation: 227468

If you really want to set the thing, the best option would be something like

void setVector(vector<string> aStringVec)
{
  classVector.swap(aStringVec);
}

This ensures that classVector holds a copy of the contents of the function argument.

What you are trying to do in your code is append elements to classVector, while incurring an unnecessary copy of the whole input vector.

Upvotes: 2

Related Questions