2012-08-15 5 views
0

나는이 같은 일부 코드가?표준 :: 벡터와 생성자

A::A(): mat(10(10)),a(0){}; 

하지만 나에게 또 하나의 문제가 있습니다. "행"의 수를 알지 못합니다. (vector<vector<int> >에는 n 개의 요소가 있어야하고 vector<int>에는 4 개의 요소가 있어야 함) 또한 vector<vector<int> >의 요소에 액세스하는 데 문제가 있습니다. 그럼 어떻게 할 수 있니? 감사합니다. :)

답변

5

당신은 물론, 변수를 전달할 수 있습니다 (2)

A::A() : mat(10, std::vector<int>(10)), a(0) { } 

this reference page:에 아래의 생성자를 사용합니다. 예를 들어 :

std::cout << mat[1][1]; // will print 0, as vector's elements are default initialized 

먼저 호출이 vector<int>에 대한 참조를 반환, 두 번째 int에 대한 참조 :

A::A(size_t n_rows, size_t n_cols) : mat(n_rows, std::vector<int>(n_cols)), a(0) {} 

요소에 액세스하려면, 당신은 operator[] 두 succesive 전화를 사용합니다.

+0

고마워요. :) 그리고 매트를 초기화해야합니까? 아니면 그만 둘 수 있습니까? 뭐가 더 나은가요? – scarably

+0

요소는 생성자에서 0으로 초기화됩니다. 그것이 프로그램에서 의미가있는 것이 확실하다. – jrok

1

당신은 행의 수를 사용하는 생성자 추가 할 수있는 요소에 액세스하기위한

A(unsigned int rows): mat(rows, std::vector<int>(4)), a(0) {}; 

을, 당신은 몇 가지 액세스 연산자 또는 메서드를 추가 할 수 있습니다.

class A{ 

public: 
public: 
A(unsigned int rows): mat(rows, std::vector<int>(4)), a(0) {}; 
const int& operator()(unsigned int row, unsigned int col) const { 
    return mat[row][col]; 
} 
private: 
vector<vector<int> > mat; 
int a; 

}; 

예를

를 들어 다음

A a; 
int i = a(3,4); 

당신은 액세스 운영자에게 확인 어떤 범위를 추가 할 수 있습니다.