By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,799 Members | 1,376 Online
Bytes IT Community
+ Ask a Question
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.


using namespace std;

void PRINT(const vector< vector<string> > &M) {
for (unsigned int r=0; r<M.size(); r++) {
for (unsigned int c=0; c<M[r].size(); c++)
cout << "\t" << M[r][c]<<endl;
cout << endl;

int main()
unsigned int rows , cols;
rows = 1;

string line;
string token;
ifstream file;"mytext.txt");

vector< vector<string> > v1(rows);
vector<string> v2;

v2. push_back(line);}

for(unsigned int i = 0 ; i < rows ; i++){

v1[i] = v2;



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
Share this Question
Share on Google+
6 Replies

Expert Mod 5K+
P: 9,197
Your 2D vector is v1.

That means you have to push_back a vector<string> into v1 for each row.

So, you create a vector<string> and and push_back the strings for row 0.

Then push_back this vector into v1.

Then erase the vector<string> and re-use it to push_back the strings for row 1.


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)

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
  1. vector< vector<string> > v;
  2.    vector<string> v1;
  4.    string data("Hello");
  5.    v1.push_back(data);
  6.    string data1("world!");
  7.    v1.push_back(data1);
  8.    v.push_back(v1);
  9.    v1.erase(v1.begin(), v1.end());
  10.    string data2("from a");
  11.    v1.push_back(data2);
  12.    string data3("2D vector");
  13.    v1.push_back(data3);
  14.    v.push_back(v1);
  15.    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

Post your reply

Sign in to post your reply or Sign up for a free account.