C/C++雜記


使用二維向量 (2D vector)的範例:

// A small program to demostrate how to declare a 2-D vector.
// Dykstra@fg.tp.edu.tw, 2004-10-11
#include <iostream.h>
#include <stdlib.h>
#include <vector>
#include <iomanip>

using namespace std;

int main(int argc, char *argv[])
{
    // 注意兩個 '>' 符號不要連接在一起!
    vector<vector<int> > a(5, vector<int>(10));
   
    int k = 1;   
    for (int i = 0 ; i < 5 ; i++)
        for (int j = 0 ; j < 10 ; j++)
            a[i][j] = k++;
        
    for (int i = 0 ; i < 5 ; i++)
    {
        for (int j = 0 ; j < 10 ; j++)
            cout << setw(3) << a[i][j];
        cout << endl;
    }
        
    system("PAUSE");	
    return 0;
} 

output:
  1  2  3  4  5  6  7  8  9 10
 11 12 13 14 15 16 17 18 19 20
 21 22 23 24 25 26 27 28 29 30
 31 32 33 34 35 36 37 38 39 40
 41 42 43 44 45 46 47 48 49 50

使用三維向量 (3D vector)的範例:

#define CLASS_NO (36)
#define TRANS_STEP (5)

// Declare a three-dimensional array using vector
vector<vector<vector<float> > >
    alpha(TRANS_STEP, vector<vector<float> >(CLASS_NO, vector<float>(CLASS_NO)));

Last update : 2004-10-12