Multidimensional Vectors

m trying to get data to store in multidimensional vectors. While executing m getting Error : "vector subscript out of range".
I think the way i am trying to store the values in the vector is causing the issue.

using namespace std;

int main()
{
char n1[30];
string noun,line,con;
size_t pos, len,i,j;
vector <vector <string> > c;

ifstream datafile;
datafile.open("COOCS.txt");

if (datafile.is_open())
{
for (i = 0; i <= 6; i++)
{
cout << "enter the Noun:";
cin.getline(n1, sizeof(n1));
string n1_1(n1);


while (noun != n1_1)
{
getline(datafile, line);
size_t length = line.size();
size_t start = line.find('\t');
noun = line.substr(pos = 0, len = start);
c[i].push_back(noun);
size_t n_len = noun.size();
line = line.substr(pos = n_len + 1, len = length);
}

size_t start1 = line.find('\t');

while (line != "/0")
{
con = line.substr(pos = 0, len = start1);
c1.push_back(con);
size_t con_len = con.find('-#-');
con = con.substr(pos = 0, len = con_len);

for (j = 0 ; ; j++)
{
c[j].push_back(con);
}
line = line.substr(start1 + 1);
}

datafile.clear();
datafile.seekg(0, ios::beg);
}
}


return 0;
}
There is no conditional in your for-loop so it will never end and j will go past the end of the vector.
1
2
3
4
for (j = 0 ; /* Check if j is a valid subscript */  ; j++)
{
c[j].push_back(con);
}


You could use vector.size() function to get the number of elements currently in the vector, or keep track of how many you add independently.
The problem is execution is not even reaching there, it gives error in the line

c[i].push_back(noun);



its the first value i am trying to insert into the vector
Last edited on
Well, what's the length of the c vector when you try to do that?

c may have a length of 0, so c[0] doesn't contain a string vector yet, so it's out of bounds. You need to push a vector into c[0] (or c[i] for that matter) before you push strings into that inner vector.
i guess what you are saying makes sense but can please help how to push a vector at the initial location.
Here's an example

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


int main()
{
  std::vector<std::vector<std::string>> D2Vector;
  
  std::vector<std::string> innerVector;
  innerVector.push_back("Some String");
  innerVector.push_back("Some OtherString");
  
  D2Vector.push_back(innerVector);
  
  std::vector<std::string> otherVector;
  otherVector.push_back("1st String in otherVector");
  
  D2Vector.push_back(otherVector);
  
  for (auto & vec : D2Vector)
  {
      std::cout << "Beginning to print vector" << std::endl;
      for (auto & str : vec)
      {
          std::cout << '\t' << str << std::endl;
      }
  }
    
 return 0;   
}


Produces:
Beginning to print vector
	Some String
	Some OtherString
Beginning to print vector
	1st String in otherVector
That works. Thanks!!
Topic archived. No new replies allowed.