【问题标题】:How to add elements to a vector of pairs every 3rd line?如何将元素添加到每 3 行的对向量中?
【发布时间】:2021-12-01 06:29:04
【问题描述】:

我正在尝试从看起来像这样的文本中创建一个对向量:

line1
line2
line3

向量将包含一对line1line2

另一个向量将包含line1line3

通常我会向这样的向量添加线条

    vector<string> vector_of_text;
    string line_of_text;

    ifstream test_file("test.txt");

    if(test_file.is_open()){
        while(getline(test_file, line_of_text)){
            vector_of_text.push_back(line_of_text)
        }

        test_file.close();
    }

但我不知道是否可以使用getline 命令访问下一行文本。

例如,在一个数组中,我会为下一个或第三个元素执行i+1i+2。 我想知道getline 是否有办法做到这一点。

【问题讨论】:

  • 第四行会去哪里,那一行会包含什么?你想拥有多少vector&lt;pair&lt;string,string&gt;&gt;?请再提供几行输入和预期输出,以便为我们提供更多背景信息。
  • @TedLyngmo 所以我想要两个向量对,一个包含一对 line1 和 line2,第二个向量包含 line1 和 line3,然后是第 4、第 5 和第 6 行和每隔 3 将是第一个向量中的 line4 和 line5,第二个向量中的 line4 和 line6 以及文本的其余部分。我希望能解决这个问题。

标签: c++ vector fstream getline std-pair


【解决方案1】:

如果我对问题的理解正确,您需要两个vector&lt;pair&lt;string, string&gt;&gt;

这可能是一种方式:

// an array of two vectors of pairs of strings
std::array<std::vector<std::pair<std::string, std::string>>, 2> tw;

unsigned idx = 0;

std::string one, two, three;

// read three lines
while(std::getline(file, one) && 
      std::getline(file, two) &&
      std::getline(file, three))
{
    // put them in the vector pointed out by `idx`
    tw[idx].emplace_back(one, two);
    tw[idx].emplace_back(one, three);

    // idx will go 0, 1, 0, 1, 0, 1 ... until you can't read three lines anymore
    idx = (idx + 1) % 2;
}

Demo

【讨论】:

  • 非常感谢您的回复,帮助很大:)
  • @rrekaF 不客气!很高兴它有帮助!
  • 谢谢@TedLyngmo。与往常一样,您的回答很有帮助。它也帮助了我
  • @Pat.ANDRIA 哦,谢谢!很高兴它有帮助!
猜你喜欢
  • 2021-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-26
  • 2012-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多