我希望能够在main之前初始化一个大小为'SIZE'的向量。通常情况下,我会做在C++的main()之前初始化一个向量
static vector<int> myVector(4,100);
int main() {
// Here I have a vector of size 4 with all the entries equal to 100
}
但问题是,我想初始化向量的第一个项目是有一定价值,以及其他为其他值。
有没有简单的方法来做到这一点?
我希望能够在main之前初始化一个大小为'SIZE'的向量。通常情况下,我会做在C++的main()之前初始化一个向量
static vector<int> myVector(4,100);
int main() {
// Here I have a vector of size 4 with all the entries equal to 100
}
但问题是,我想初始化向量的第一个项目是有一定价值,以及其他为其他值。
有没有简单的方法来做到这一点?
这里的替代解决方案:
#include <vector>
static std::vector<int> myVector(4,100);
bool init()
{
myVector[0] = 42;
return true;
}
bool initresult = init();
int main()
{
;
}
试试这个:
static int init[] = { 1, 2, 3 };
static vector<int> vi(init, init + sizeof init/sizeof init[ 0 ]);
而且,看std::generate
(如果你想在一个函数中初始化)。
这不仅是最明显的方式,也是最快最清晰的方式。 +1(至少如果其他物品都为零) – 2009-04-25 13:28:18
否,这会给出一个3物品矢量(没有额外的元素),但为此,它非常整齐。 – Macke 2009-04-27 20:11:17
有点hackish的,但你可以这样做:
struct MyInitializer {
MyInitializer() {
myVector[0]=100;
//...
}
} myInitializer; // This object gets constructed before main()
hackish,有点危险,因为你不能在主要之前捕捉异常,但也正是我在这些情况下所做的。 – 2009-04-25 11:22:47
或者只是创建一个函数和调用:
std::vector<int> init()
{
...
}
static std::vector<int> myvec = init()
有点低效也许,但现在也许不事给你,并与的C++ 0x和移动它会非常快。
如果要避免复制(用于C++ 03和更早的版本),使用智能指针:
std::vector<int>* init() {
return new std::vector<int>(42);
}
static boost::scoped_ptr<std::vector<int>> myvec(init());
一类把它包:
class SpecialVector
{
public:
SpecialVector()
{
myVector[0] = 1;
myVector[1] = 4;
// etc.
}
const vector<int> & GetVector() const
{
return myVector;
}
private:
vector<int> myVector;
};
static SpecialVector SpVec;
int main() {
}
的C++ 0x将允许标准集装箱初始化列表,就像聚集:
std::vector<int> bottles_of_beer_on_the_wall = {100, 99, 98, 97};
显然不是标准,但它据称是从GCC 4.4支持。我无法在MSVC中找到它的文档,但Herb Sutter一直说他们的C++ 0x支持在委员会之前...
而不是使用全局,我建议最好使用本地静态。由于向量的初始化发生在main输入之前,所以抛出的异常将不会被main捕获。例如说,你有哪些时,它的构造可能会抛出异常的类型:
class A {
public:
A() {
// ... code that might throw an exception
}
};
对于下面的初始化,的try/catch主的身体不会赶上由构造函数抛出的异常,所以你的程序会立即死亡,你可能甚至无法使用调试器来查找原因!
std::Vector<A> v(5, A()); // May throw an exception here not caught by main
int main() {
try {
// Exception for 'v' not handled here.
}
catch (...) {
}
}
另一种方法,将捕获从构造一个例外是使用本地静态 - 这是使用该answer提出的技术初始化。
std::Vector<A> init(); // Returns a vector appropriately initialized
std::vector<A> & getV() {
static std::vector<A> cache = init();
return cache;
}
int main() {
try {
getV().at[0]; // First call to getV - so initialization occurs here!
}
catch (...) {
}
}
这个怎么样:标准::矢量一个(3,100),&A_INIT((A [0] = 98,[1] = 99,));它会使等于“98,99,100”:) –
2009-04-25 14:53:13
只是出于好奇,为什么你需要它? – 2009-04-26 15:37:36