Can I use C++11 list-initializer syntax for vectors with variables?

118 views Asked by At

I have some double variables: a, b,c... I want to construct a vector v such as v[0]=a, v[1]=b etc Can I do this with C++11 list initializer ? i.e this syntax :

std::vector<double> v{a,b,c};

If no, is there a way to do this directly, without multiple pushback() ?

2

There are 2 answers

0
Chris Guzak On

You can answer questions like this easily using this online C++ compiler: http://webcompiler.cloudapp.net/

I tried this and it worked:

#include <vector>
int main()
{
    double a{}, b{}, c{};
    std::vector<double> v{a,b,c};
}
0
Vlad from Moscow On

A parody on the post of @Chris Guzak:)

I tried this and it worked:

#include <iostream>
#include <functional>
#include <vector>


int main() 
{
    double a = 1.1, b = 2.2, c = 3.3;

    std::vector<double> v { std::cref( a ), std::cref( b ), std::cref( c ) };

    for ( double x : v ) std::cout << x << ' ';
    std::cout << std::endl;
}

One more parody.

Wow! I tried this and it worked:

#include <iostream>
#include <vector>

int main() 
{
    double a = 1.1, b = 2.2, c = 3.3;

    std::vector<double> v;
    v.reserve( 3 );

    for ( auto x : { a, b, c } ) v.push_back( x );

    for ( double x : v ) std::cout << x << ' ';
    std::cout << std::endl;
}

And one more

I tried this and it worked:

#include <iostream>
#include <vector>

int main() 
{
    double a = 1.1, b = 2.2, c = 3.3;

    std::vector<double> v;

    v.insert( v.end(), { a, b, c } );

    for ( double x : v ) std::cout << x << ' ';
    std::cout << std::endl;
}

Oh, and I tried this and it also worked:

#include <iostream>
#include <vector>

int main() 
{
    double a = 1.1, b = 2.2, c = 3.3;

    std::vector<double> v;

    v.assign( { a, b, c } );

    for ( double x : v ) std::cout << x << ' ';
    std::cout << std::endl;
}

What else I did not try?:)