【问题标题】:Something's wrong with the vector ? Memory?向量有问题吗?记忆?
【发布时间】:2026-02-12 15:45:01
【问题描述】:

我正在用 C++ 测试一些函数,但是当我使用这段代码时 它正在编译,但我的程序因错误而失败:std::bad_alloc 我认为是因为我没有足够的内存或向量太大

#include <iostream>
#include <vector>
#include <ctime>

using namespace std;

int main(void){

int temps = time(0);
vector<int> vec(temps, 20);
for(int i(0); i < vec.size() ;i++){
    cout << vec[i] << endl;
};
}

【问题讨论】:

  • 打印出temps的值。您可能会发现它出人意料地很大。
  • int i(0) 这似乎是错误的。
  • @AkshayArora,完全合法。 C'tor 语法对内置类型也有效..
  • 是吗?好吧,我今天学到了一些东西。谢谢。 @StoryTeller
  • 是的,现在我明白我的错误是矢量太大而且没用

标签: c++ vector


【解决方案1】:

time(nullptr) 返回自 1970 年 1 月 1 日以来的秒数。目前约为 1458495645。 因此,您当前正在初始化一个 std::vector ,其大小约为 20 英寸的 15 亿倍。我猜您的意图不同。

【讨论】:

  • 是的,我只是意识到它没用。感谢您的回答