2015-11-27 21 views
-1

的陣列我想要做的事,如下面的例子:C++數組的初始化和互爲作用

#include <iostream> 

#include <memory> 

using namespace std; 

int main() 
{ 

    char *data [][] = { 
     { "11", "12", "13", "14" }, 
     { "21", "22", "23", "24" }, 
     { "31", "32", "33", "34" }, 
     { "41", "42", "43", "44" }, 
    }; 

    for (auto &item : data) 
    { 
     for (auto &var : item) 
      std::cout << var << " - "; 
    } 


    return 0; 
} 

這並不編譯:

$ g++ -std=c++11 -o main *.cpp                          
main.cpp: In function 'int main()':                          
main.cpp:10:17: error: declaration of 'data' as multidimensional array must have bounds for all dimensions except the first    
    char *data [][] = {                             
       ^                              
main.cpp:17:22: error: 'data' was not declared in this scope                    
    for (auto &item : data)                            
        ^                            
main.cpp:19:25: error: unable to deduce 'auto&&' from 'item'                    
     for (auto &var : item) 
        ^ 

所以:

A)作用似乎是我不能在不設置其大小的情況下聲明多維數組。那是對的嗎 ?

b)我不能使用迭代器遍歷基本類型(如char * []),只能在向量上使用。那是對的嗎 ?

c)如何修復該代碼以使其工作。我不想使用std::vector

感謝您的幫助。

+0

像編譯器說,你必須給第二維數組邊界:使用std::string的。關於文字大小不用擔心容易得多。所有字符串*發生*具有相同長度的事實是不夠的。修復後,for循環應該工作。 –

+0

這是一個例子。事實上,我會爲每個值設定不同的尺寸...... – Mendes

回答

1

最終解決方案。

#include <iostream> 

#include <memory> 
#include <vector> 

using namespace std; 

int main() 
{ 

    std::vector<std::vector<std::string>> data = { 
     { "11", "12", "13", "14" }, 
     { "21", "22", "23", "24" }, 
     { "31", "32", "33", "34" }, 
     { "41", "42", "43", "44" }, 
    }; 

    for (auto &item : data) 
    { 
     for (auto &var : item) 
      std::cout << var << " - "; 

     std::cout << std::endl; 
    } 


    return 0; 
} 
2

A)你需要聲明的所有多維數組的大小,除了第一的錯誤狀態的大小:「的‘數據’作爲多維數組必須爲所有的維界,除了第一次申報」

char *data [][4] = { 

B)有問題修正這個錯誤應該消失,因爲正確定義了數據。