448,799 Members | 1,376 Online
Need help? Post your question and get tips & solutions from a community of 448,799 IT Pros & Developers. It's quick & easy.

# doubt in using 2D vectors

 P: 6 I have a written the following code. #include #include #include #include using namespace std; void PRINT(const vector< vector > &M) { for (unsigned int r=0; r > v1(rows); vector v2; while(getline(file,line)){ v2. push_back(line);} for(unsigned int i = 0 ; i < rows ; i++){ v1[i] = v2; } PRINT(v1); file.close(); system("PAUSE"); return 0; } What i want to do is read the document in a vector, then sort each line row by row. Lets say for example, i want to put line 1 in 1st row, line 2 in second row..and so on. But this code isnt doing that. Its just taking whole document and pushes into one row. How do i solve my problem? I am just using vectors. i dont want to use algorithms or maps. JUST VECTORS. Thanks in advance. Mar 2 '08 #1
6 Replies

 Expert Mod 5K+ P: 9,197 Your 2D vector is v1. That means you have to push_back a vector into v1 for each row. So, you create a vector and and push_back the strings for row 0. Then push_back this vector into v1. Then erase the vector and re-use it to push_back the strings for row 1. ertc... Then you can access a particular string using v1[row][col]. Mar 2 '08 #2

 P: 6 So, if i create a for loop, say for(int row = 0 ; row < v1.size() ; ++row) { v1.push_back(vector()); } is tat goin to work? Mar 2 '08 #3

 P: 6 How will i generate a loop like tat? Mar 3 '08 #4

 Expert Mod 5K+ P: 9,197 Somethuing like this: Expand|Select|Wrap|Line Numbers vector< vector > v;    vector v1;      string data("Hello");    v1.push_back(data);    string data1("world!");    v1.push_back(data1);    v.push_back(v1);    v1.erase(v1.begin(), v1.end());    string data2("from a");    v1.push_back(data2);    string data3("2D vector");    v1.push_back(data3);    v.push_back(v1);    cout << v[0][0] << v[0][1] << v[1][0] << v[1][1] << endl;   Mar 3 '08 #5

 P: 6 But thats for individual strings. What if i am reading it from file? Mar 4 '08 #6

 Expert Mod 5K+ P: 9,197 What's a file got to do with it? Just read your file data into striong objects and push_back the string objects. The only difference is I hard-coded "Hello" where you would have read it from the disc. And that has nothing whatsoever to do with string objects in a vector. You might consider a new thread about how to read a disc file into a string object. Mar 4 '08 #7