C++:动态创建以for循环迭代器命名的数组

标签 c++ arrays variables naming

嘿,所以我想创建大小为 x(也基于用户输入)的 n 数组(基于用户输入)。我当时考虑的方法是让 for 循环执行 n 迭代,并在循环内要求用户输入 x。问题是我不确定如何使用变量 n 命名数组,我在想类似的东西:

cout << "Enter n: ";
cin >> n

for (i = 0; i < n; i++)
{
    cout << "Enter x: ";
    cin >> x;

    double*array+i;
    array+i = new double[x]
}

总而言之,我的问题是:您可以在 C++ 中使用变量创建/命名数组吗?

最佳答案

不幸的是,您不能在 C++ 中执行此操作。尝试这样的事情......

std::cout << "Enter n: ";
std::cin >> n

std::vector<std::vector<double> > arrays(n);

for (std::size_t i = 0; i < n; i++)
{
    std::cout << "Enter x: ";
    std::cin >> x;

    arrays[i].reserve(x);
}

reserve只分配,不构造std::vector中的对象;如果您也想构建它们,请使用 resize

PS 永远不要使用 using namespace std;它使您的代码更难阅读和调试。

关于C++:动态创建以for循环迭代器命名的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15178132/

相关文章:

javascript - 我可以以某种方式在 switch 中使用 if 语句来添加更多案例吗?

c++ - ‘virtual char std::ctype<wchar_t>::do_narrow(wchar_t, char) const’ protected

c++ - 用tellg()判断文件长度,最终结果为-1

c++ - 当 B 继承自 A 时,std::function< void ( const A & )> 无法转换为 std::function< void ( const B & ) >

javascript - 从输入创建 JSON

ruby - 单个哈希的多变量赋值

c++ - 如何使 Visual Studio 2013 显示未处理的异常消息?

javascript - 使用 `for` 与 `slice` : why are the returns of these two functions different? 的数组展平递归中的空值

c - 从内部结构到相同类型的其他结构的指针数组

java - 布局更改时字符串值不会更改