的陣列我想要做的事,如下面的例子: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
感謝您的幫助。
像編譯器說,你必須給第二維數組邊界:使用
std::string
的。關於文字大小不用擔心容易得多。所有字符串*發生*具有相同長度的事實是不夠的。修復後,for循環應該工作。 –這是一個例子。事實上,我會爲每個值設定不同的尺寸...... – Mendes