Two-dimensional vector printing
Solution 1
You can easily loop through the vector by its size, just use the size()
member function:
for (int i = 0; i < vec.size(); i++)
{
for (int j = 0; j < vec[i].size(); j++)
{
cout << vec[i][j];
}
}
Solution 2
If you have a vector of vectors then you can print it the following way using the range based for statement
std::vector<std::vector<std::string>> v;
//...
for ( const auto &row : v )
{
for ( const auto &s : row ) std::cout << s << ' ';
std::cout << std::endl;
}
If you need a solution based on C++ 2003 then the code could look like
for ( size_t i = 0; i < v.size(); i++ )
{
for ( size_t j = 0; j < v[i].size(); j++ ) std::cout << v[i][j] << ' ';
std::cout << std::endl;
}
Solution 3
Use function size()
to get the number of elements.
std::vector< std::vector<std::string> > vec;
for (unsigned int i = 0; i < vec.size(); ++i)
{
for (unsigned int j = 0; j < vec[i].size(); ++j)
{
cout << vec[i][j];
}
cout << std::endl;
}
Solution 4
I would change it to the following:
for (int i = 0; i < vec.size(); i++)
{
for (int j = 0; j < vec[i].size(); j++)
{
cout << vec[i][j];
}
}
eilchner
Updated on July 05, 2022Comments
-
eilchner almost 2 years
I've got a two-dimension string vector that I need to print out. The whole program should read a line from a txt file, store each word from it as a different element and then push the "word vector" into a vector that contains for example 100 lines. I've got everything going, but the problem comes out when I have to print the vector. Every line can have a different number of words, ex:
I like cake
a lot.
So I can't use:
for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { cout << vec[i][j]; } }
because the second line doesn't contain 3 elements and the program closes.
Any idea how to do it? Note: my lecturer doesn't accept C++11, so a solution based on C++98 would be appreciated. This is my function:void readline(vector<vector<string> >& lines, int size) { vector<string> row; string line, word; fstream file; istringstream iss; int i; file.open("ticvol1.txt", ios::in); for (i = 0; i < size; i++) { getline(file, line); iss.str(line); while (iss >> word) row.push_back(word); lines.push_back(row); } }
-
eilchner over 9 yearsI was thinking about using vector.size(), but didn't know how to use it with a 2d vector. Thanks a lot
-
Jarod42 over 9 yearsYou need a space between
>>
in pre-C++11. -
JobHunter69 over 5 yearsIt's missing endline.
-
Romero Azzalini over 3 yearswhy aren't you the best answer?!