【发布时间】:2017-07-25 18:40:43
【问题描述】:
我需要循环 vector of strings of strings 的方式与我在此示例中使用 integers 执行此操作的方式相同:
int main()
{
vector<vector<int>> stuff;
//fill the inner vector, then insert it into the outer vector
for (int i = 0; i < 999; i++)
{
vector<int>temp;
for (int j = 0; j < 9; j++)
{
temp.push_back(i);
++i;
}
stuff.push_back(temp);
}
//display all elements ...
for (int i = 0; i < stuff.size(); i++)
{
for (int j = 0; j < stuff[i].size(); j++) {
cout << stuff[i][j] << "\t";
}
cout << endl;
}
}
但字符串需要不同的方法,因为它们更复杂, 在这里,我正在迭代一维字符串:
vector<string> first_arr = {};
string line;
ifstream myfile("source.txt");
if (myfile.is_open())
{
while (getline(myfile, line))
{
first_arr.push_back(line); //READ from file
}
myfile.close();
}
else cout << "Unable to open file";
但我完全坚持进入内圈。 另外,我期待长度非常不同的字符串
我有一段时间没有使用 c++,所以如果我的问题对你来说太明显了,请原谅我的问题,
【问题讨论】:
-
您是否相信您拥有的用于在
ints 的二维向量上进行迭代的代码可以使用字符串向量(大部分未更改)?它至少应该按原样编译,只更改变量名称。虽然这不是一种特别有效的迭代方式,但在 C++ 中,它会起作用。 -
您的示例循环对内部元素类型所做的唯一事情就是打印它们——在这方面,
string的使用并不比int的使用复杂。虽然请注意,您的第二个代码块只是一个字符串向量,而不是字符串向量的向量。 -
我在这里迭代一维字符串向量 ...你没有迭代向量
first_arr。您正在遍历myfile的行并将这些行添加到向量first_arr。 -
顺便说一下,将问题分解成更小的部分。如果您在处理事物向量的向量时遇到问题,请编写一个函数来处理事物向量的每个元素,然后编写另一个函数来调用事物向量的该函数。
-
我想我离它不远了,但仍然缺少一些东西。我
ve spent few nights over this and finally, decided to ask for help; (Logically, String != int, its 比较复杂;你不能遍历字符串,因为它是整数)
标签: c++ string multidimensional-array vector iterator