Search code examples
c++vectorfstreamgetlinestd-pair

How to add elements to a vector of pairs every 3rd line?


I'm trying to make a vector of pairs from a text that looks something like that:

line1
line2
line3

And the vector would contain a pair of line1 and line2.

And another vector would contain line1 and line3

Normally I would add lines to a vector like this

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

but I don't know if it is possible to access the next line of text with the getline command.

For example, in an array, I would do i+1 or i+2 for the next or 3rd element. I was wondering if there was a way to do that with getline.


Solution

  • If I understand the question correctly, you want two vector<pair<string, string>>.

    This could be one way:

    // 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