why is there vector? any other thing?

Dear Friends,
The code below is to solve the convection equation. Would you please tell me what is the role of vector here? if some one did not want to use vector what could he use instead?
would you please explain line below to me?

void saveArray(vector< vector<double> > &u, int nx, int nt, double dx, double dt, int c);


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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
  /*
 * Solves 1D convection equation, also known as the one-way wave equation.
 */
 
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
 
void saveArray(vector< vector<double> > &u, int nx, int nt, double dx, double dt, int c);
 
int main()
{
 
  int nx = 20;
  int nt = 50;
  double dx = double(2)/(nx-1);
  double dt = 0.01;
  int c = 5;
 
  vector< vector<double> > u(nx,vector<double> (nt));
  vector< vector<double> > un(nx,vector<double> (nt));
 
  // Initial condition:
  for (int i=0; i <= nx-1; i++)
    {
      if (i*dx >= 0.5 && i*dx <= 1)
    {
      u[i][0] = 2;
    }
      else
    {
      u[i][0] = 1;
    }
    }
 
  // Finite-difference loop:
  for (int it=1; it<=nt-1; it++)
    {
      for (int k=0; k<=nx-1; k++)
    {
      un[k][it-1] = u[k][it-1];
    }
      for (int i=1; i<=nx-1; i++)
    {
      u[0][it] = un[1][it-1];
      u[i][it] = un[i][it-1] - c*dt/dx*(un[i][it-1]-un[i-1][it-1]);
    }
    }
 
  saveArray(u, nx, nt, dx, dt, c);
 
  return 0;
}
 
// Save array to file:
void saveArray(vector< vector<double> > &u, int nx, int nt, double dx, double dt, int c)
{
  ofstream myfile;
  myfile.open("1d_convection02.dat");
  myfile << "%\t" << "nx = "  << nx  << "\tnt = " << nt <<
    "\tdt = " << dt << "\tc = " << c << endl;
 
  for (int i=0; i<=nx-1; i++)
    {
      myfile << i*dx << "\t\t";
      for (int j=0; j<=nt-1; j++)
    {
      myfile << u[i][j] << "\t\t";
    }
      myfile << endl;
    }
}
Last edited on
You would use a vector if you needed an array that had to dynamically change its size throughout the life of the program. It seems the program pasted above actually does not do that, but appears to be a stylistic choice of the programmer (i.e. opting to use a vector instead of the C++ new operator).

As far as the line you posted, the first parameter of vector< vector<double> > &u is saying pass a multidimensional vector array by reference so that the function can modify its values (which is does not actually).
Topic archived. No new replies allowed.