当我声明一个 vector 时,它默认填充为零。作为模拟的一部分,我希望它在循环中初始化每个迭代。什么是正确有效的方法?
我想解决两种情况:
我希望它归零为一个已知值,即 nSteps
#include <iostream> #include <vector> using namespace std; const int nSteps = 10000; const int nReal = 10; int main() { for (unsigned int i = 0 ; i<nRealization; i++) { vector<double> v(nSteps); for (unsigned int j = 0 ; j<nSteps ; j++) { //stuff going on with v } } }
长度未定义(它由使用
push_back
的函数给出)#include <iostream> #include <vector> using namespace std; const int nSteps = 10000; const int nReal = 10; int main() { for (unsigned int i = 0 ; i<nRealization; i++) { vector<double> v; // some function that uses push_back gives v its length for (unsigned int j = 0 ; j<nSteps ; j++) { //stuff going on with v } } }
最佳答案
文档是您的 friend 。每当您想做某事时,只需通读标准库实用程序列表,直到找到 the one you want。 !
std::fill(v.begin(), v.end(), 0);
这本质上等同于老式的 memset
,但增加了类型安全性。
关于c++ - 每次循环初始化一个 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32762112/