二维矢量打印 [英] Two-dimensional vector printing

查看:179
本文介绍了二维矢量打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二维字符串向量,我需要打印出来。整个程序应该从一个txt文件中读取一行,存储每个单词作为一个不同的元素,然后将单词向量推入一个包含例如100行的向量。我有一切都去,但问题出来时,我必须打印向量。每行可以有不同的字数,例如:

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。

所以我不能使用:

for (int i = 0; i < 2; i++)
{
    for (int j = 0; j < 3; j++)
    {
        cout << vec[i][j];
    }
}

,因为第二行不包含3个元素程序关闭。

任何想法怎么做?注意:我的讲师不接受C ++ 11,所以基于C ++ 98的解决方案将不胜感激。这是我的函数:

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


推荐答案

可以通过其大小轻松循环向量,只需使用 size()成员函数:

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

这篇关于二维矢量打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆