2010-04-08 80 views
0

我对C++非常陌生,我意识到以下内容不一定像我想要的那么容易,但是我非常感谢更专业的意见。C++数组可变大小的数组

我基本上试图实现一个动态迭代变量大小数组的变量大小数组类似于以下。

String *2d_array[][] = {{"A1","A2"},{"B1","B2","B3"},{"C1"}}; 

for (int i=0; i<2d_array.length; i++) { 
    for (int j=0; j<2d_array[i].length; j++) { 
     print(2d_array[i][j]); 
    } 
} 

有没有合理的方法来做到这一点?也许通过使用矢量或其他结构?

谢谢:)

+2

的std ::矢量肯定会是一个合理的方式。 – 2010-04-08 08:42:01

+0

你不能用数字启动变量... – 2010-04-08 08:51:47

+0

我正在为bada学习C++。原来,不能使用Std :: - 所以我使用ArrayList的ArrayList来代替。 – adam 2010-04-08 13:07:38

回答

2

您正在使用C++字符串对象的纯C数组。在C中没有可变大小的数组。除此之外,该代码不会编译,在这样的构造中,编译器将生成一个声明最大长度的数组数组。在样本的情况下,这将是

String *2d_array[3][3] 

如果你想可变大小的数组,你必须使用C++ STL(标准模板库)作为载体或列表-containers例如:

#include <string> 
#include <vector> 

void f() 

{ 
    typedef std::vector<std::string> CStringVector; 
    typedef std::vector<CStringVector> C2DArrayType; 
    C2DArrayType theArray; 

    CStringVector tmp; 
    tmp.push_back("A1"); 
    tmp.push_back("A2"); 
    theArray.push_back(tmp); 

    tmp.clear(); 
    tmp.push_back("B1"); 
    tmp.push_back("B2"); 
    tmp.push_back("B3"); 
    theArray.push_back(tmp); 

    tmp.clear(); 
    tmp.push_back("C1"); 
    theArray.push_back(tmp); 

    for(C2DArrayType::iterator it1 = theArray.begin(); it1 != theArray.end(); it1++) 
     for(CStringVector::iterator it2 = it1->begin(); it2 != it1->end(); it2++) 
     { 
      std::string &s = *it2; 
     } 
} 
+1

不幸的是,在今天的C++版本中,代码大小增加了一个数量级。我期待着我们可以像数组一样初始化矢量的那一天。 C++ 0X,请继续前进。 – daramarak 2010-04-08 09:47:44