簡體   English   中英

多維數組(C ++)

[英]Multi-Dimensional Array ( C++ )

我正在嘗試將指針存儲在數組中。

我的指針是類對象:

classType **ClassObject;

所以我知道我可以通過使用new運算符來分配它:

ClassObject = new *classType[ 100 ] = {};

我正在閱讀帶有標點符號的文本文件,這是我到目前為止的內容:

// included libraries
// main function
// defined varaibles

classType **ClassObject; // global object
const int NELEMENTS = 100; // global index


wrdCount = 1;  // start this at 1 for the 1st word
while ( !inFile.eof() )  
{
   getline( inFile, str, '\n' );  // read all data into a string varaible
   str = removePunct(str);  // User Defined Function to remove all punctuation.
   for ( unsigned x = 0; x < str.length(); x++ )
   {
       if ( str[x] == ' ' ) 
       {
          wrdCount++;  // Incrementing at each space
          ClassObject[x] = new *classType[x];
       // What i want to do here is allocate space for each word read from the file.

       }
   }
}
// this function just replaces all punctionation with a space
string removePunct(string &str) 
{ 
    for ( unsigned x = 0; x < str.length(); x++ )
        if ( ispunct( str[x] ) )
            str[x] = ' ';
  return str;
}

// Thats about it.

我想我的問題是:

  • 我是否為文件中的每個單詞分配了空間?
  • 我如何在while / for循環內的ClassObject數組中存儲指針?

如果您使用的是C ++,請使用Boost多維數組庫

嗯,我不確定您要做什么(尤其是新的* classType [x]甚至可以編譯嗎?)

如果您希望每個單詞都使用一個新的classType,那么您可以

ClassObject[x] = new classType; //create a _single_ classType
ClassObject[x]->doSomething();

只要ClassObject已初始化(如您所說)。

您說您想要一個2D數組-如果您想要這樣做,則語法為:

ClassObject[x] = new classType[y]; //create an array of classType of size y
ClassObject[0][0].doSomething(); //note that [] dereferences automatically

但是,我也不確定new * classType [100] = {};的含義。 -花括號在那里做什么? 似乎應該

classType** classObject = new classType*[100];

我強烈建議您使用其他方法,因為這確實很討厭(而且您必須小心刪除... ugh)

使用vector <> s或如上述建議那樣使用boost庫。

您的代碼非常好,只需要一行: ClassObject[x] = new *classType[x]; 星號*需要消失,您可能想說的是您希望ClassObject被索引為字數而不是x。

將該行替換為: ClassObject[wrdCount] = new classType[x];

希望有幫助,比利3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM