【发布时间】:2026-01-13 14:45:01
【问题描述】:
我正在尝试在 C++ 中创建一堆向量,每个向量都有不同的名称。我在这个网站上环顾四周,并没有找到任何“简单”的信息,因为我对 c++ 很陌生。我想在不导入我以前从未使用过的库的情况下做到这一点。 例如:
#include <iostream>
#include <cmath>
#include <stdlib.h>
#include <vector>
using namespace std;
int main(int argc, char* argv[])
{
int n = 2;
int m = 4;
double size = pow(m,n);
for (int i=0; i<n; ++i)
{
vector<double> xi(size);
// where xi would vary with the iteration through n
// i.e. I would have vectors x1, x2 in the case of n=2
}
return 0;
}
这不是简单的情况,我可以在开始时自己创建 x1 和 x2,因为我不知道“n”会是什么,因为它将由用户在开始时输入程序。这样做最简单的方法是什么?
【问题讨论】:
-
简单回答:not really
-
为什么不能每次都使用
x?无论如何,变量的范围仅限于循环,因此您可以重用名称。 -
变量只在它们被声明的范围内持续存在,所以即使你这样做了它也不会很有用。