C++ 二维矢量打印
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26937550/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Two-dimensional vector printing
提问by eilchner
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:
我有一个需要打印的二维字符串向量。整个程序应该从 txt 文件中读取一行,将其中的每个单词存储为不同的元素,然后将“单词向量”推入包含例如 100 行的向量中。我已经一切顺利,但是当我必须打印矢量时问题就出现了。每行可以有不同数量的单词,例如:
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:
因为第二行不包含 3 个元素并且程序关闭。
知道怎么做吗?注意:我的讲师不接受 C++11,因此基于 C++98 的解决方案将不胜感激。这是我的功能:
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);
}
}
回答by 0x499602D2
You can easily loop through the vector by its size, just use the size()
member function:
您可以通过向量的大小轻松循环,只需使用size()
成员函数:
for (int i = 0; i < vec.size(); i++)
{
for (int j = 0; j < vec[i].size(); j++)
{
cout << vec[i][j];
}
}
回答by Vlad from Moscow
If you have a vector of vectors then you can print it the following way using the range based for statement
如果您有一个向量向量,则可以使用基于范围的 for 语句按以下方式打印它
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
如果您需要基于 C++ 2003 的解决方案,则代码可能如下所示
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;
}
回答by JPLemelin
Use function size()
to get the number of elements.
使用函数size()
来获取元素的数量。
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;
}
回答by Jonathan
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];
}
}