2010-04-19 35 views

Trả lời

24

Đối số thứ hai cho that constructor là giá trị để khởi tạo. Ngay bây giờ bạn đang nhận được 4 vectơ được xây dựng mặc định. Để làm rõ với một ví dụ 1D đơn giản:

// 4 ints initialized to 0 
vector<int> v1(4); 

// *exactly* the same as above, this is what the compiler ends up generating 
vector<int> v2(4, 0); 

// 4 ints initialized to 10 
vector<int> v3(4, 10); 

Vì vậy, bạn muốn:

vector< vector<int> > bar(4, vector<int>(4)); 
//    this many^ of these^

Điều này tạo ra một vector của vector ints, khởi tạo để chứa 4 vectơ được khởi tạo để chứa 4 ints, khởi tạo 0. (Bạn có thể chỉ định giá trị mặc định cho int, nếu muốn.)

Miệng đầy nhưng không quá cứng. :)


Đối với một cặp:

typedef std::pair<int, int> pair_type; // be liberal in your use of typedef 
typedef std::vector<pair_type> inner_vec; 
typedef std::vector<inner_vec> outer_vec; 

outer_vec v(5, inner_vec(5, pair_type(1, 1)); // 5x5 of pairs equal to (1, 1) 
//    this many^of these^
//this many^ of these^
+0

Các ưu non trong tôi hét lên khi nhìn thấy dòng cuối cùng này của mã ... – sbk

+0

gì nếu thay vì int, tôi muốn làm một đôi . Có cách nào tôi có thể khởi tạo tất cả các cặp chứa 0,0? – zebraman

+0

@zebra: Các cặp sẽ tự khởi chạy ints thành 0. Nhưng để hoàn thành, tôi đã chỉnh sửa bài đăng của mình. – GManNickG

1

Ngoài ra để một std::vector bạn có thể sử dụng boost::multi_array. Từ the documentation:

#include "boost/multi_array.hpp" 
#include <cassert> 

int 
main() { 
    // Create a 3D array that is 3 x 4 x 2 
    typedef boost::multi_array<double, 3> array_type; 
    typedef array_type::index index; 
    array_type A(boost::extents[3][4][2]); 

    // Assign values to the elements 
    int values = 0; 
    for(index i = 0; i != 3; ++i) 
    for(index j = 0; j != 4; ++j) 
     for(index k = 0; k != 2; ++k) 
     A[i][j][k] = values++; 

    // Verify values 
    int verify = 0; 
    for(index i = 0; i != 3; ++i) 
    for(index j = 0; j != 4; ++j) 
     for(index k = 0; k != 2; ++k) 
     assert(A[i][j][k] == verify++); 

    return 0; 
} 
Các vấn đề liên quan