如何在for循环中创建具有不同名称的向量

时间:2015-11-16 21:03:12

标签: c++ for-loop vector

我试图用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,因为我不知道&#39; n&#39; n&#39; n&#39; n&#39;将是,因为它将在程序开始时由用户输入。最简单的方法是什么?

3 个答案:

答案 0 :(得分:2)

使用矢量矢量。

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

   // Fill up xi
   // ...

   xArray.push_back(xi);    
}

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

根据您尝试的操作,使用类似std::map<std::string, std::vector<int>>的内容可能有意义。

你可以这样做:

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. 
相关问题