【发布时间】:2014-11-02 16:45:55
【问题描述】:
我正在尝试制作一个矩阵程序,该程序使用整数向量的向量制作一个 n*m 整数矩阵。但是我在这样做时遇到了麻烦,因为我对 C++ 还很陌生。我已经开始实施我的程序,但是我遇到了一大堆我无法弄清楚原因的错误。另外,这是我第一次使用 .h 和向量,所以请保持温和 :)。
矩阵.h
#ifndef MATRIX_H
#define MATRIX_H
#include<vector>
using namespace std;
class Matrix{
public:
Matrix( );
Matrix(int r, int c);
void setRow(vector<int> row, int r);
void setColumn(vector<int> col, int c);
int getRow();
int getCol();
void output();
double average();
private:
int row, column;
vector< vector<int> > matrix;
};
#endif
矩阵.cpp
#include "Matrix.h"
#include<iostream>
#include<vector>
using namespace std;
int main(){
int row,column;
cout << "Enter number of rows: ";
cin >> row;
cout << "Enter number of column: ";
cin >> column;
Matrix matrix(row,column);
matrix.output();
}
Matrix::Matrix():row(3), column(3){
matrix = vector<vector<int> >(row);
for (int i = 0; i < row; i++){
matrix[i] = vector<int>(column);
}
}
Matrix::Matrix(int r, int c): row(r), column(c){
matrix = vector<vector<int> >(r);
for (int i = 0; i < r; i++){
matrix[i] = vector<int>(c);
}
}
void Matrix::setRow(vector<int> row, int r){
if (r <= row){
if (row.size <= column){
for (int i = 0; i < row.size; i++){
matrix[r][i] = row[i];
}
}
}
}
void Matrix::setColumn(vector<int> col, int c){
if (c <= column){
if (col.size <= row){
for (int i = 0; i < col.size; i++){
matrix[i][c] = col[i];
}
}
}
}
void Matrix::output(){
for (int i = 0; i < row; i++){
for (int j = 0; j < column; j++){
cout << matrix[i][j];
}
cout<< endl;
}
}
好的,以上是我之前代码的固定版本,但现在我收到了这个错误:
错误:
Matrix.cpp: In member function ‘void Matrix::setRow(std::vector<int, std::allocator<int> >, int)’:
Matrix.cpp:32: error: no match for ‘operator<=’ in ‘r <= row’
Matrix.cpp:33: error: invalid use of member (did you forget the ‘&’ ?)
Matrix.cpp:34: error: invalid use of member (did you forget the ‘&’ ?)
Matrix.cpp: In member function ‘void Matrix::setColumn(std::vector<int, std::allocator<int> >, int)’:
Matrix.cpp:43: error: invalid use of member (did you forget the ‘&’ ?)
Matrix.cpp:44: error: invalid use of member (did you forget the ‘&’ ?)
【问题讨论】:
-
您不需要在标头中包含
#include<iostream>,它会大大减慢您的编译时间,因为iostream是一个巨大的标头。 -
你不应该把
using namespace std;放在头文件的全局部分(最好不要放在其他任何地方)。 -
@Galik,所以我应该删除它,但我需要将它包含在 .h 文件的其他任何地方吗?
-
你可以把它放在你的类定义中,或者把你的类放在它自己的命名空间中并添加到那里。或者您可以使用
std::限定您的std::vector。
标签: c++