首先,阅读其他的答案,然后也许重读在一个良好的C++的书指针章。现在,除非你需要极高的速度,否则使用vector
的vector
的double
。用C++ 11(较新的C++标准),这是非常好的,可读的,所以我张贴第一:
#include <iostream>
#include <vector>
void printArray(std::vector< std::vector<double> > & v) {
for (const auto & row : v){
for (const auto & value : row){
std::cout << value << " ";
}
std::cout << std::endl;
}
}
int main() {
int n;
std::cout<<"Please enter the length of your matrix : "<<std::endl;
std::cin>>n;
std::vector<std::vector<double>> y(n,std::vector<double>(n,0));
for (auto & row : y){
std::cout<<"Insert the elements of row :";
for (auto & value : row){
std::cin >> value;
}
}
printArray(y);
}
对于较旧的C++是这样的:
void printArray(std::vector< std::vector<double> > & v) {
for (std::vector<std::vector<double> >::const_iterator it = v.begin(); it != v.end();it++){
for (std::vector<double>::const_iterator it2 = it->begin(); it2!= it->end();it2++) {
std::cout << (*it2) << " ";
}
std::cout << std::endl;
}
}
int main() {
int n;
std::cout<<"Please enter the length of your matrix : "<<std::endl;
std::cin>>n;
std::vector<std::vector<double> > y(n,std::vector<double>(n,0));
for (std::vector<std::vector<double> >::iterator it = y.begin(); it!= y.end();it++){
std::cout<<"Insert the elements of row :";
for (std::vector<double>::iterator it2 = it->begin(); it2!= it->end();it2++) {
std::cin >> (*it2);
}
}
printArray(y);
}
注意y(n,std::vector<double>(n,0))
手段,使n
载体,每个载体有n
零。您也可以使用y[1][2]
来获取和设置值。如果您使用y.at(1).at(2),则可以进行适当的检查,以便在读取或写入界限时收到异常。
@RyanGray如果数组不是固定大小(不是),那么它必须是新的。当然,应该真正使用诸如'std :: vector'之类的结构。 – juanchopanza 2012-07-30 16:46:44
@RyanGray:使用'new []'是创建一个数组的合法方式,它与'new'不一样。 – Rook 2012-07-30 16:46:50
你需要使用双指针,你的数组需要被声明为int ** y = new int * [n] – user1084113 2012-07-30 16:47:25