Constant-sized vector

2019-03-11 14:50发布

Does someone know the way to define constant-sized vector?

For example, instead of defining

std::vector<int>

it will be

std::vector<10, int>

It should be completely cross-platformed. Maybe an open source class?

标签: c++ stl vector
7条回答
走好不送
2楼-- · 2019-03-11 15:07

The std::vector can always grow dynamically, but there are two ways you can allocate an initial size:

This allocates initial size and fills the elements with zeroes:

std::vector<int> v(10);
v.size(); //returns 10

This allocates an initial size but does not populate the array with zeroes:

std::vector<int> v;
v.reserve(10);
v.size(); //returns 0
查看更多
叼着烟拽天下
3楼-- · 2019-03-11 15:08

This ----> std::vector<10, int> is invalid and causes error. But the new C++ standard has introduced a new class; the std::array. You can declare an array like this:

std::array<int, 5> arr; // declares a new array that holds 5 ints
std::array<int, 5> arr2(arr); // arr2 is equal to arr
std::array<int, 5> arr3 = {1, 2, 3, 4, 5}; // arr3 holds 1, 2, 3, 4, 5

The std::array has constant size and supports iterator/const_iterator/reverse_iterator/const_reverse_iterator. You can find more about this class at http://cplusplus.com/reference/stl/array/.

查看更多
ゆ 、 Hurt°
4楼-- · 2019-03-11 15:09

A std::vector is a dynamic container, there is no mechanism to restrict its growth. To allocate an initial size:

std::vector<int> v(10);

C++11 has a std::array that would be more appropriate:

std::array<int, 10> my_array;

If your compiler does not support C++11 consider using boost::array:

boost::array<int, 10> my_array;
查看更多
▲ chillily
5楼-- · 2019-03-11 15:12

There is no way to define a constant size vector. If you know the size at compile time, you could use C++11's std::array aggregate.

#include <array>

std::array<int, 10> a;

If you don't have the relevant C++11 support, you could use the TR1 version:

#include <tr1/array>

std::tr1::array<int, 10> a;

or boost::array, as has been suggested in other answers.

查看更多
Deceive 欺骗
6楼-- · 2019-03-11 15:19

This is an old question but if someone just needs constant-size indexed container with size defined at runtime, I like to use unique_ptr:

auto constantContainer = std::make_unique<YourType []> ( yourSize );

// Access
constantContainer[ i ]

P.s. This is C++14.

查看更多
我想做一个坏孩纸
7楼-- · 2019-03-11 15:22

Use std::array

For better readability you can make typedef:

typedef std::array<int, 10> MyIntArray;
查看更多
登录 后发表回答