C++ Multidimensional Array

Hey, found this skeleton on arrays and tried to put some use to it. I'm having an error with the values though... can anyone help?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <vector>
using std::vector;

#define HEIGHT 5
#define WIDTH 3

int main() {
  vector<vector<double> > array2D;


  array2D.resize(HEIGHT);
  for (int i = 0; i < HEIGHT; ++i)
    array2D[i].resize(WIDTH);


  array2D [1] [1] [1] = 6.0;
  array2D [1] [1] [1] = 6.0;
  array2D [1] [1] [1] = 6.0;
  return 0;
}
Hint: array2D is 2 dimensional, so why are you trying to use 3 dimensions?
also, can one index std::vector using []? I also always thought one could, but then, it, for some reason, stopped working for me, so, I started using std::vector::at().

Just a pointer, but, might not be a problem for you after all.
also, can one index std::vector using []?


One can. Using [] is unchecked access. Using at is checked access.
Aha! Can you explain what that means. Do you mean unchecked, as you could also access information that is "out of bounds", so, it would just return "rubbish", I guess? Or, something else?

Thanks! :)
Checked verses unchecked means whether the index value is checked to be inbounds. One can use an out of bounds index with []. at() checks that index value is < size(). Slightly slower, but safer.
Do you mean unchecked, as you could also access information that is "out of bounds", so, it would just return "rubbish", I guess?

Unchecked as in it will assume you know what you're doing and let you shoot yourself in the foot. The usual term used to describe behavior for using out of bound indices is "undefined behavior."

If you're using VC++, even [] is checked in debug mode - using an invalid index will trigger a debug assertion. If I disable that and use the following code, with unchecked_out_of_bounds_access uncommented, the program will crash.


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
#include <iostream>
#include <vector>
#include <stdexcept>

int unchecked_out_of_bounds_access(const std::vector<int>& v)
{
    return v[v.size()] ;
}

int checked_out_of_bounds_access(const std::vector<int>& v)
{
    return v.at(v.size()) ;
}

int main()
{
    std::vector<int> vec(4) ;

    // unchecked_out_of_bounds_access(vec) ;

    try {
        checked_out_of_bounds_access(vec) ;
    }
    catch ( std::exception & ex )
    {
        std::cout << "ERROR: " << ex.what() << '\n' ;
    }
}
ERROR: invalid vector<T> subscript
Topic archived. No new replies allowed.