-2

I keep getting an out of range error when I try to populate a 2d vector in c++. Where am I going wrong? Posted below is a shortened version of my problem that I believe generates the same problem.

#include <vector>
#include <stdio.h>
#include <cstdlib>
#include <iostream>

typedef std::vector<double> NA;
typedef std::vector<NA> NB;

NA NI;
NB NO;

long i=0,j=0;
int N = 10;
double R;

int main(){

    for(i=0;i!=N;i++){

       NO.push_back(NI);
        for(j=i+1;j<N;j++){

            R = rand();


            NO.at(i).push_back(j);
            NO.at(i).at(j) = R;
        }
    }
}
2
  • 3
    There are no 2D vectors in your code. Also when you get "an error" its always useful to post the actual error message. (P.S: NI, NO, i, j, N, R are not very good variable names, consider using descriptive ones)
    – Borgleader
    Feb 24, 2017 at 19:59
  • This: NO.at(i).at(j) = R; shouldn't compile? In fact it doesn't: ideone.com/ukPags Feb 24, 2017 at 20:04

1 Answer 1

2
  1. Your typedefs are wrong. You mean:

    typedef std::vector<double> NA;
    typedef std::vector<NA> NB;
    //                  ^^
    
  2. Your loop indexes are wrong. You mean j++.

  3. The inner index must be offset: at(j - i - 1).

  4. The outer container update, NO.push_back(NI);, needs to move into the outer loop.

3
  • 1
    I don't get how the out of range error even came up. The code provided doesn't even compile? ideone.com/ukPags Feb 24, 2017 at 20:05
  • Full demo
    – Kerrek SB
    Feb 24, 2017 at 20:08
  • Sorry I wrote this on my phone as I don't have internet, let me correct these issues. Apologies.
    – RedPen
    Feb 24, 2017 at 20:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.