【问题标题】:How do you create vectors with different names in a for loop如何在 for 循环中创建具有不同名称的向量
【发布时间】: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?无论如何,变量的范围仅限于循环,因此您可以重用名称。
  • 变量只在它们被声明的范围内持续存在,所以即使你这样做了它也不会很有用。

标签: c++ for-loop vector


【解决方案1】:

使用向量的向量。

std::vector<std::vector<double>> xArray;
for (int i=0; i<n; ++i)
{
   vector<double> xi(size);

   // Fill up xi
   // ...

   xArray.push_back(xi);    
}

【讨论】:

    【解决方案2】:

    你不能在 C++ 中做你所要求的。但是,您可以将创建的向量存储在另一个向量向量中,因此,您可以通过它们在包含它们的向量中的索引来引用它们:

    std::vector<std::vector<double>> myvecs;
    for(int i(0); i < n; ++i) {
      std::vector<double> xi(size);
      //...
      myvecs.push_back(xi);
    }
    

    【讨论】:

      【解决方案3】:

      根据您要执行的操作,使用std::map&lt;std::string, std::vector&lt;int&gt;&gt; 之类的内容可能有意义。

      你可以这样做:

      std::map<std::string, std::vector<int>> myMap;
      
      for (int i=0; i<n; ++i) {
               vector<double> xi(size);
               string name;
               // Make a name with stringstream ... 
               myMap[name] = xi;
      }
      

      然后如果需要,您可以使用`name 搜索向量,例如:

      cout << "Name of your vector: "
      cin << name;
      cout << "Here is your vector"
      std::vector<int> &myVect = myMap[name];
      // Do some printing. 
      

      【讨论】:

        最近更新 更多