Re: assigning vector with predefined values
On Apr 27, 5:30 am, meisterbartsch <Bluesman.Patr...@gmx.de> wrote:
I want to assign predefined vallues to a vector, like:
std::vector<double> tr;
tr={3.36,2.09,1.47,1.1,0.87,0.72};
how do i do this? Am I able to assign values without
using .push_back(); ?
You can use a helper class with method chaining (http://
www.parashift.com/c++-faq-lite/references.html#faq-8.4) like this (not
tested):
#include <vector>
using namespace std;
template<typename T>
class Initializer
{
vector<T> v_;
public:
Initializer( const size_t capacity=0 )
{
v_.reserve( capacity );
}
Initializer& Add( const T& t )
{
v_.push_back( t );
return *this;
}
operator vector<T>() const
{
return v_;
}
};
int main()
{
const vector<double> v = Initializer<double>( 4 )
.Add(1.0)
.Add(2.0)
.Add(3.0)
.Add(4.0);
}
There's a vector copy in there, but any modern compiler will use the
return value optimization to get rid of it.
Cheers! --M