C++ 我可以在初始化列表中用 10 个相同整数初始化 STL 向量吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10237751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I initialize an STL vector with 10 of the same integer in an initializer list?
提问by Xavier
Can I initialize an STL vector with 10 of the same integer in an initializer list? My attempts so far have failed me.
我可以在初始化列表中用 10 个相同整数初始化 STL 向量吗?到目前为止,我的尝试都失败了。
采纳答案by David Rodríguez - dribeas
I think you mean this:
我想你的意思是:
struct test {
std::vector<int> v;
test(int value) : v( 100, value ) {}
};
回答by Ed S.
Use the appropriate constructor, which takes a size and a default value.
使用适当的构造函数,它接受一个大小和一个默认值。
int number_of_elements = 10;
int default_value = 1;
std::vector<int> vec(number_of_elements, default_value);
回答by Agus
The initialization list for vector is supported from C++0x. If you compiled with C++98
C++0x 支持向量的初始化列表。如果你用 C++98 编译
int number_of_elements = 10;
int default_value = 1;
std::vector<int> vec(number_of_elements, default_value);
回答by Mahmoud Al-Qudsi
If you're using C++11 and on GCC, you could do this:
如果您使用的是 C++11 和 GCC,您可以这样做:
vector<int> myVec () {[0 ... 99] = 1};
It's called ranged initialization and is a GCC-only extension.
它被称为范围初始化,是一个仅限 GCC 的扩展。
回答by Rafa? Rawicki
You can do that with std::vector
constructor:
你可以用std::vector
构造函数做到这一点:
vector(size_type count,
const T& value,
const Allocator& alloc = Allocator());
Which takes count
and value
to be repeated.
这需要count
和value
重复。
If you want to use initializer lists you can write:
如果你想使用初始化列表,你可以写:
const int x = 5;
std::vector<int> vec {x, x, x, x, x, x, x, x, x, x};
回答by nate_weldon
can you post what you are doing
你能发布你在做什么吗
int i = 100;
vector<int> vInts2 (10, i);
vector<int>::iterator iter;
for(iter = vInts2.begin(); iter != vInts2.end(); ++iter)
{
cout << " i " << (*iter) << endl;
}