简体   繁体   中英

How to make an array/vector of pairs of 2 corresponding integers from 2 different user input lines in C++?

How to pair up corresponding elements from two different input lines, to form one array of pairs in C++ ?

Eg. input :

0 1 2 3 4
5 6 7 8 9

output = [{0,5} {1,6} {2,7} {3,8} {4,9}]

Edit : Input is given by the user through stdin and not in the form of 2 different arrays. I want to store this input directly in the form of an array of pairs without first creating 2 arrays then making pairs.

Edit 2: I'm just looking avoid use of any additional space for intermediate steps. I tried the following, but it doesn't give me the correct output.

vector<pair<int, int>> pairs;
for (int i = 0; i < n; i++) {
        cin >> k;
        pairs.push_back({k, 0});
    }
for (int i = 0; i < n; i++) {
        cin >> k;
        pairs[i] = {pairs[i].first, k};
    }

TIA.

This is a revised answer since the question has changed a lot.

If the size is known, create the resulting vector<pair<int, int>> with the correct size from the start, then use two range based for-loops with structured bindings to fill it.

std::vector<std::pair<int, int>> res(number_of_pairs);

for(auto&[a, b] : res) if(!(std::cin >> a)) return 1;
for(auto&[a, b] : res) if(!(std::cin >> b)) return 1;

Revising your attempt, you should update the pair in the second loop rather than replacing it.

vector<pair<int, int>> pairs;
for (int i = 0; i < n; i++) {
    cin >> k;
    pairs.emplace_back(k, 0);
}
for (int i = 0; i < n; i++) {
    cin >> pairs[i].second;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM