c++ - 如何迭代字符串 vector 的 vector ? (c++)

标签 c++ string multidimensional-array vector iterator

我需要循环vector of vector of strings,就像我在这个例子中用整数做的一样:

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++,所以如果您觉得这个问题太明显,请原谅我的问题,

最佳答案

这是一个示例,其中包含大小为 510string 的三个 vector >15。此示例使用 C++11range-based for loop打印 vector

代码:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

int main()
{
    using SList = std::vector< std::string >;
    using VList = std::vector< SList >;

    VList vlist;

    for ( int i = 5; i <= 15; i += 5 )
    {
        SList slist { i };
        std::fill( slist.begin(), slist.end(), "Test" );
        vlist.push_back( slist );
    }

    for ( const auto& v : vlist )
    {
        std::cout << "{ ";
        for ( const auto& s : v )
        {
            std::cout << s << ' ';
        }
        std::cout << "}\n";
    }

    return 0;
}

输出:

{ Test Test Test Test Test }
{ Test Test Test Test Test Test Test Test Test Test }
{ Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test }

这是 Ideone 上的实例:http://ideone.com/PyYD5p

关于c++ - 如何迭代字符串 vector 的 vector ? (c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42616399/

相关文章:

php - 从 MySQL 查询中获取行数组?

c++ - 在嵌套的 C++ 类中复制 typedef

c++ - 如何从 Objective C 调用我的 Qt/C++ Dylib?

c - 在 C 中提取格式化数据的有效方法

c++ - string_algo 的 boost to_upper 函数没有考虑语言环境

C++正则表达式提取子字符串

c++ - 从中序遍历打印所有二叉树

c++ - 是结构的默认构造函数,就像 C++ 中的类一样调用

c++ - Noobish 阵列问题 : Run-Time Check Failure #2 - Stack around the variable 'arr' was corrupted

PHP判断数组是否存在于数组中的方法