2011-04-27 74 views
1

#include <iostream> 
#include <vector> 
#include <iomanip> 

using namespace std; 

static int c; 

class DAI //DynamicArrayInput 
{ 
public : 
    void getCountry() 
    { 
    cout << "Country : "; 
    cin >> Country; 
    } 

    void putCountry() 
    { 
    cout << Country << endl; 
    } 
    static int putCount() 
    { 
    return count; 
    } 
private : 
    static int count; 
    char Country[30]; 
}; 



int main() 
{ 
vector<DAI> A; 
DAI B[3]; 
//DAI * B; 

cout << "Enter name of countries\n"; 
    for(int i=0; i < 3; i++) 
    { 
     //THIS DOESN'T WORK 
    /* 
    c++; //c is a static variable declared at top 
    B = new DAI[sizeof(DAI) * c/sizeof(DAI)]; 
    GIVES WRONG OUTPUT : 
    Enter name of countries 
    Country : a 
    Country : b 
    Country : c 
    Printing name of countries 


    c 
    size of vector A is 3 
    vector after initialisation: 

    */ 
    A.push_back(B[i]); 
    B[i].getCountry(); 
    } 
    cout << "Printing name of countries\n"; 
    for(int i=0; i < 3; i++) 
    { 
    B[i].putCountry(); 
    } 

cout << "size of vector A is " << A.size() << "\ 
    \nvector after initialisation:" << endl; 

return 0; 
} 


**/* 
CORRECT OUTPUT WITH LIMITED ARRAY SIZE = 3: 
*Enter name of countries 
Country : a 
Country : b 
Country : c 
Printing name of countries 
a 
b 
c 
size of vector A is 3 
vector after initialisation:* 
*/** 

我刚学,这是不是我的功课, 我不提到它希望被局限于任何数组的大小,如上述,但是当我尝试使用staements在第一个for循环不行 我的意思是,这并不适用动态添加对象?

c++; //c is a static variable declared at top 
B = new DAI[sizeof(DAI) * c/sizeof(DAI)]; //B is a pointer of type class DAI 

我的目标是使用对象我喜欢动态数组,这样我可以输入任意数量的国家,我不希望使用类似B [3]已知的数组大小,但我无法做到。

请指导我,帮帮我。

+2

使用一个'std :: vector'或'std :: deque',它们是自动调整大小的容器。我看到你正在向量中存放数组 - 你可能已经有了'std :: vector >'。 – birryree 2011-04-27 15:27:36

+0

嗯,我已经在程序中使用它,但无法继续它看到主要的第一行 – mukesh 2011-04-27 15:33:45

+0

你不会初始化c任何地方。 – 2011-04-27 15:37:10

回答

2

C++; // c是顶部声明的静态变量
B =新的DAI [sizeof(DAI)* c/sizeof(DAI)];

在这里你很困惑newmalloc。要分配型DAI的Ç元素,只是做

B = new DAI[c]; 

然而,最好的办法是留的std ::载体,它处理的规模和能力本身。

for (int i = 0; i != 10; ++i) 
    A.push_back(DAI()); 

增加了10个讲台的载体A.

编辑
您也可以从一开始就一些傣族的创建载体:

std::vector<DAI> A(10); 

这也创造了一个与10个元素的矢量,一次全部。不同于B[3],它总是包含3个元素,矢量可以根据需要增长或缩小,而无需处理分配。

+0

很好!谢谢,博我会尝试B =新的DAI [E]我没有得到第二个DAI() – mukesh 2011-04-27 15:53:05

+0

是的,你的第二个想法工作......非常感谢,但什么DAI()是一个构造函数调用如何工作 – mukesh 2011-04-27 16:01:38

+0

是的,它是一个构造函数,用于创建新的DAI以添加到向量中。我还添加了一个新的例子来说明如何使用元素**创建向量**,而不使用循环。 – 2011-04-27 16:17:47

0

您的阵列是静态的DAI[3] v(v在进程'堆栈中)。为了能够动态添加元素,您需要使用DAI[INITIAL_SZ] v = new DAI[INITIAL_SZ](现在v位于堆中)对其进行更改,以便现在可以在添加/删除元素时重新分配它。

+0

谢谢,这对我来说是新的,我会研究它 – mukesh 2011-04-27 15:54:44