R S*_*R S 7 c++ static stl vector
我希望能够在main之前初始化一个大小为'SIZE'的向量.通常我会这样做
static vector<int> myVector(4,100);
int main() {
// Here I have a vector of size 4 with all the entries equal to 100
}
Run Code Online (Sandbox Code Playgroud)
但问题是我想将向量的第一项初始化为某个值,将另一个初始化为另一个值.
是否有捷径可寻?
dir*_*tly 20
试试这个:
static int init[] = { 1, 2, 3 };
static vector<int> vi(init, init + sizeof init / sizeof init[ 0 ]);
Run Code Online (Sandbox Code Playgroud)
另外,请参阅std::generate(如果要在函数内初始化).
Mac*_*cke 10
或者只是创建一个函数并调用:
std::vector<int> init()
{
...
}
static std::vector<int> myvec = init()
Run Code Online (Sandbox Code Playgroud)
也许效率有点低,但现在对你来说可能并不重要,而且使用C++ 0x并移动它会非常快.
如果要避免复制(对于C++ 03及更早版本),请使用智能指针:
std::vector<int>* init() {
return new std::vector<int>(42);
}
static boost::scoped_ptr<std::vector<int>> myvec(init());
Run Code Online (Sandbox Code Playgroud)
C++ 0x将允许标准容器的初始化列表,就像聚合一样:
std::vector<int> bottles_of_beer_on_the_wall = {100, 99, 98, 97};
Run Code Online (Sandbox Code Playgroud)
显然还不标准,但它据称得到了GCC 4.4的支持.我在MSVC中找不到它的文档,但是Herb Sutter一直在说他们的c ++ 0x支持领先于委员会......
有点hackish,但你可以做到这一点:
struct MyInitializer {
MyInitializer() {
myVector[0]=100;
//...
}
} myInitializer; // This object gets constructed before main()
Run Code Online (Sandbox Code Playgroud)
这是另一种解决方案:
#include <vector>
static std::vector<int> myVector(4,100);
bool init()
{
myVector[0] = 42;
return true;
}
bool initresult = init();
int main()
{
;
}
Run Code Online (Sandbox Code Playgroud)