Two-dimensional vector printing

后端 未结 4 1055
野性不改
野性不改 2020-12-18 11:36

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 th

相关标签:
4条回答
  • 2020-12-18 11:42

    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];
        }
    }
    
    0 讨论(0)
  • 2020-12-18 11:51

    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;
    }
    
    0 讨论(0)
  • 2020-12-18 11:52

    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];
        }
    }
    
    0 讨论(0)
  • 2020-12-18 11:55

    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;
    }
    
    0 讨论(0)
提交回复
热议问题