Xav*_*ier 42 c++ constructor stl initializer-list
我可以在初始化列表中使用10个相同的整数初始化STL向量吗?到目前为止,我的尝试都让我失望.
Ed *_* S. 120
使用适当的构造函数,该构造函数采用大小和默认值.
int number_of_elements = 10;
int default_value = 1;
std::vector<int> vec(number_of_elements, default_value);
Run Code Online (Sandbox Code Playgroud)
Dav*_*eas 33
我想你的意思是:
struct test {
std::vector<int> v;
test(int value) : v( 100, value ) {}
};
Run Code Online (Sandbox Code Playgroud)
如果你正在使用C++ 11和GCC,你可以这样做:
vector<int> myVec () {[0 ... 99] = 1};
Run Code Online (Sandbox Code Playgroud)
它被称为范围初始化,是一个仅限GCC的扩展.
从C ++ 0x支持vector的初始化列表。如果您使用C ++ 98编译
int number_of_elements = 10;
int default_value = 1;
std::vector<int> vec(number_of_elements, default_value);
Run Code Online (Sandbox Code Playgroud)
你可以用std::vector
构造函数做到这一点:
vector(size_type count,
const T& value,
const Allocator& alloc = Allocator());
Run Code Online (Sandbox Code Playgroud)
这需要count
和value
重复.
如果要使用初始化列表,可以编写:
const int x = 5;
std::vector<int> vec {x, x, x, x, x, x, x, x, x, x};
Run Code Online (Sandbox Code Playgroud)