Two-dimensional vector printing

依然范特西╮ 提交于 2019-12-01 00:56:49

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];
    }
}

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;
}
JPLemelin

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;
}

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];
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!