Search code examples
c++vectormultidimensional-arraysizerandom-walk

Using a `.size()` as an array index


Say I have a some code like:

typedef std::vector<std::vector<std::vector<long int> > > posHistory;
posHistory pHist (1, vector<vector<long int>>(1, vector<long int>(1,0)));

that kept track of, for example:

  • The number of dogs.
  • The number of times takes a step.
  • The position of each step. (step length of unity (1))

How could I add a position for each defecation? I have:

direction = some random number between -dimensions and dimensions (say -2,2 for 2d) tdof = translational degrees of freedom, essentially each axis.

for (unsigned int tdof = 0; tdof < dimensions; tdof++)
{
    if (fabs(direction) < tdof)
    {
        walkHist[(int) walkHist.back()][(int) walkHist[walkHist.back()].size()][tdof] = (long int) copysign(1, direction);
    }
}

The part that is giving me trouble is:

walkHist[walkHist.size()-1][walkHist[walkHist.size()-1].size()][ (long int) copysign(1, direction)];

And later in the code I have:

walkHist[(walkHist.size()-1)].push_back();
walkHist.push_back(); 

I'm fairly sure it's the conversion between size_type to an index that is the problem, but how could I rectify that?

I've tried casting, but that doesn't seem to work, although I may have just done it wrong. In short, help?

Edit 1

The first push back gives me an error:

saw.cpp:62:50: error: no matching function for call to ‘std::vector<std::vector<long int> >::push_back()’

Edit 2

Hmm, it seems that walkHist.at(walkHist.back()).size() gives me:

saw.cpp:49:52: error: no matching function for call to ‘std::vector<std::vector<std::vector<long int> > >::at(__gnu_cxx::__alloc_traits<std::allocator<std::vector<std::vector<long int> > > >::value_type&)’

Solution

  • Using foo[foo.size()] for a std::vector<T> foo accesses an element of foo just outside the range of foo: arrays in C and C++ are zero-based, i.e., you can access indices 0, ..., size()-1. Accessing an element outside this range is undefined behavior.