在 C++ 中的 main() 之前初始化向量

发布于 2024-07-17 12:57:50 字数 271 浏览 5 评论 0原文

我希望能够在 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

}

但问题是我想将向量的第一项初始化为某个值,将另一个项初始化为另一个值。

是否有捷径可寻?

I want to be able to initialize a vector of a size 'SIZE' before main. Normally I would do

static vector<int> myVector(4,100);

int main() {

    // Here I have a vector of size 4 with all the entries equal to 100

}

But the problem is that I would like to initialize the first item of the vector to be of a certain value, and the other to another value.

Is there an easy way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

望她远 2024-07-24 12:57:51

试试这个:

static int init[] = { 1, 2, 3 };
static vector<int> vi(init, init + sizeof init / sizeof init[ 0 ]);

另请参阅 std::generate(如果您想在函数内初始化)。

Try this:

static int init[] = { 1, 2, 3 };
static vector<int> vi(init, init + sizeof init / sizeof init[ 0 ]);

Also, see std::generate (if you want to initialize within a function).

何止钟意 2024-07-24 12:57:51

或者只是创建一个函数并调用它:

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());

Or just create a function and call that:

std::vector<int> init()
{
  ...
}

static std::vector<int> myvec = init()

A bit inefficient perhaps, but that might not matter to you now, and with C++0x and move it will be very fast.

If you want to avoid the copy (for C++03 and earlier), use a smart-pointer:

std::vector<int>* init() { 
    return new std::vector<int>(42);
}

static boost::scoped_ptr<std::vector<int>> myvec(init());
活泼老夫 2024-07-24 12:57:51

C++0x 将允许标准容器的初始值设定项列表,就像聚合一样:

std::vector<int> bottles_of_beer_on_the_wall = {100, 99, 98, 97};

显然还不是标准,但据称从 GCC 4.4 开始支持它。 我在 MSVC 中找不到它的文档,但 Herb Sutter 一直说他们的 c++0x 支持领先于委员会......

C++0x will allow initializer lists for standard containers, just like aggregates:

std::vector<int> bottles_of_beer_on_the_wall = {100, 99, 98, 97};

Obviously not standard yet, but it's allegedly supported from GCC 4.4. I can't find documentation for it in MSVC, but Herb Sutter has been saying their c++0x support is ahead of the committee...

当梦初醒 2024-07-24 12:57:51

有点黑客,但你可以这样做:

struct MyInitializer {
   MyInitializer() {
       myVector[0]=100;
       //...
   }
} myInitializer;  // This object gets constructed before main()

A bit hackish, but you could do this:

struct MyInitializer {
   MyInitializer() {
       myVector[0]=100;
       //...
   }
} myInitializer;  // This object gets constructed before main()
迷迭香的记忆 2024-07-24 12:57:51

这是替代解决方案:

#include <vector>                  
static std::vector<int> myVector(4,100);

bool init()
{
    myVector[0] = 42;      
    return true;
}

bool initresult = init();

int main()                  
{
    ;
}

Here's alternative solution:

#include <vector>                  
static std::vector<int> myVector(4,100);

bool init()
{
    myVector[0] = 42;      
    return true;
}

bool initresult = init();

int main()                  
{
    ;
}
九八野马 2024-07-24 12:57:51

我建议最好使用本地静态,而不是使用全局。 由于向量的初始化发生在进入 main 之前,因此抛出的任何异常都不会被 main 捕获。 举例来说,你有一个类型,在构造它时可能会抛出异常:

class A {
public:
  A() { 
    // ... code that might throw an exception
  }
};

对于以下初始化,main 主体中的 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 (...) {
  }
}

从构造函数捕获异常的另一种方法是使用本地静态 - 它是使用此 答案

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 (...) {
  }
}

Rather than use a global, I'd suggest it's better to use a local static. As the initialization of your vector takes place before main is entered any exceptions thrown there will not be caught by main. Say for example you have a type which when it's constructed may throw an exception:

class A {
public:
  A() { 
    // ... code that might throw an exception
  }
};

For the following initialization, the try/catch in the body of main will not catch the exception thrown by the constructor, and so your program will simply die immediately and you probably won't even be able to use a debugger to find the cause!

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 (...) {
  }
}

An alternative approach that will catch an exception from the constructor is to use a local static - which is initialized using the technique suggested by this 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 (...) {
  }
}
兔小萌 2024-07-24 12:57:51

用一个类包装它:

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() {
 }

Wrap it by a class:

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() {
 }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文