What is the easiest way to initialize a std::vecto

2018-12-31 08:11发布

I can create an array and initialize it like this:

int a[] = {10, 20, 30};

How do I create a std::vector and initialize it similarly elegant?

The best way I know is:

std::vector<int> ints;

ints.push_back(10);
ints.push_back(20);
ints.push_back(30);

Is there a better way?

25条回答
冷夜・残月
2楼-- · 2018-12-31 08:18

Just thought I'd toss in my $0.02. I tend to declare this:

template< typename T, size_t N >
std::vector<T> makeVector( const T (&data)[N] )
{
    return std::vector<T>(data, data+N);
}

in a utility header somewhere and then all that's required is:

const double values[] = { 2.0, 1.0, 42.0, -7 };
std::vector<double> array = makeVector(values);

But I can't wait for C++0x. I'm stuck because my code must also compile in Visual Studio. Boo.

查看更多
只若初见
3楼-- · 2018-12-31 08:18

If you want something on the same general order as Boost::assign without creating a dependency on Boost, the following is at least vaguely similar:

template<class T>
class make_vector {
    std::vector<T> data;
public:
    make_vector(T const &val) { 
        data.push_back(val);
    }

    make_vector<T> &operator,(T const &t) {
        data.push_back(t);
        return *this;
    }

    operator std::vector<T>() { return data; }
};

template<class T> 
make_vector<T> makeVect(T const &t) { 
    return make_vector<T>(t);
}

While I wish the syntax for using it was cleaner, it's still not particularly awful:

std::vector<int> x = (makeVect(1), 2, 3, 4);
查看更多
怪性笑人.
4楼-- · 2018-12-31 08:19

The easiest way to do it is:

vector<int> ints = {10, 20, 30};
查看更多
只若初见
5楼-- · 2018-12-31 08:19

In C++11:

static const int a[] = {10, 20, 30};
vector<int> vec (begin(a), end(a));
查看更多
不再属于我。
6楼-- · 2018-12-31 08:21

Below methods can be used to initialize the vector in c++.

  1. int arr[] = {1, 3, 5, 6}; vector<int> v(arr, arr + sizeof(arr)/sizeof(arr[0]));

  2. vector<int>v; v.push_back(1); v.push_back(2); v.push_back(3); and so on

  3. vector<int>v = {1, 3, 5, 7};

The third one is allowed only in C++11 onwards.

查看更多
只靠听说
7楼-- · 2018-12-31 08:21

"How do I create an STL vector and initialize it like the above? What is the best way to do so with the minimum typing effort?"

The easiest way to initialize a vector as you've initialized your built-in array is using an initializer list which was introduced in C++11.

// Initializing a vector that holds 2 elements of type int.
Initializing:
std::vector<int> ivec = {10, 20};


// The push_back function is more of a form of assignment with the exception of course
//that it doesn't obliterate the value of the object it's being called on.
Assigning
ivec.push_back(30);

ivec is 3 elements in size after Assigning (labeled statement) is executed.

查看更多
登录 后发表回答