galois
galois

Reputation: 857

Setting an old vector equal to a new vector

Say I'm making a class:

#import <vector>

class Example {
    std::vector<float> v;

    public:
        Example(std::vector<float>);
};

How do I set the existing vector v equal to the vector passed through the constructor? Is there some "accepted" way of doing that?

I've thought about looping through, and just adding them.. but it seems "forced".

#import "Example.h"

Example::Example(std::vector<float> u) {
    //or however a vector iterates! :-)
    for (int i = 0; i < u.size; ++i)
        this->v.push_back(u.at(i));
}

Is there a better way to do this?

Upvotes: 0

Views: 2424

Answers (2)

Jonathan Mee
Jonathan Mee

Reputation: 38949

C++11 provides the best way to do this if you want to use the std::vector you're passing into Example, as in you don't want to allocate and copy to a new std::vector. This is called a move constructor:

class Example {
    std::vector<float> _v;
public:
    Example(std::vector<float>&& v) : _v(std::move(v)) {}
};

In your code you can force this to be called like this:

std::vector<float> foo{4.0, 8.0, 15.0, 16.0, 23.0, 42.0};
Example bar = std::move(foo);

A copy constructor is used when you want to make a copy of the argument:

class Example {
    std::vector<float> _v;
public:
    Example(const std::vector<float>& v) : _v(v) {}
};

And can be used like:

std::vector<float> foo{4.0, 8.0, 15.0, 16.0, 23.0, 42.0};
Example bar = foo;

Upvotes: 1

Barry
Barry

Reputation: 303711

Just use the copy constructor:

Example::Example(const std::vector<float>& u) 
: v(u)
{ }

Note that I'm taking by u by reference to const, not by value.

If you were to insist on not just copying the vector, which is definitely the most efficient way, then vector also has an insert method which takes a range (the 4th overload):

Example::Example(const std::vector<float>& u) 
{
    v.insert(v.end(), u.begin(), u.end());
}    

Upvotes: 0

Related Questions