0

I have following requirement which is to be read in to program.

The first line contains two space-separated integers denoting the respective values of p (the number of variable-length arrays) and q(the number of queries). Each line of the subsequent lines contains a space-separated sequence for each element in to array .

Each of the subsequent lines contains two space-separated integers describing the respective values of i (an index in array ) and j (an index in the array referenced by ) for a query.

2 2
3 1 5 4
5 1 2 8 9 3
0 1
1 3

In example above i have 2 arrays and 2 queries. First array is 3,3,5, 4 and second array 5 1 2 8 9 3.

My question is how can I read this data in my container. Note: I cannot enter input from console, here some test program provides input.

I have written as below

int iNoOfVectors = 0;
    int iNoOfQueries = 0;
    cin >> iNoOfVectors >> iNoOfQueries;
    cout << iNoOfVectors ; 
    vector<vector<int>> container;
    container.reserve(iNoOfVectors);
    for(int i = 0; i < iNoOfVectors; i++ ) {
        int temp;
        std::string line;
        while (std::getline(std::cin, line))
        {
            std::cout << line << std::endl;
        }
    }

output of above

2
3 1 5 4
5 1 2 8 9 3
0 1
1 3

How can I get variable length array elements in to my container.

Thanks

2

1 Answer 1

3

If you want to read similar data from a string into a vector, you need to do the following 2 steps:

  • Put the contents of the string into a std::istringstream
  • Iterate over the elements in the istringstream with the std::istream_iterator

Example:

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

int main() {

    // The source string
    std::string stringWithIntegers{ "5 1 2 8 9 3" };

    // Build an istringstream with the above string as data source
    std::istringstream iss{ stringWithIntegers };

    // Define variable 'data'. Use range constructor and stream iterator    
    std::vector<int> data{std::istream_iterator<int>(iss), std::istream_iterator<int>()};

    // Display result
    std::copy(data.begin(), data.end(), std::ostream_iterator<int>(std::cout, "\n"));

    return 0;
}

Also copying the data is possible:

    std::vector<int> data{};

    std::copy(
        std::istream_iterator<int>(iss),
        std::istream_iterator<int>(),
        std::back_inserter(data)
    );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.