简体   繁体   中英

How to construct a vector from a line of an unknown number of int // c++

Usually the number of inputs is given and i can do it with a for loop but not there: https://codeforces.com/contest/469/problem/A

I am trying desesperately to construct a vector from a line of ints, but i just know than the number of ints cannot be higher than 100. There s 2 lines of inputs.

If i make an infinite loop of Cin, how can i break it when it reaches an end of line or the end of the inputs?

You might consider reading in the entire line as a string first:

std::string line;
std::getline (istream,name);

then splitting that string into your vector (boost example):

std::vector<int> split(std::string const& str)
{
    using namespace std;
    using namespace boost;
    std::vector<int> results;
    tokenizer<> tok(str);
    for(tokenizer<>::iterator beg=tok.begin(); beg!=tok.end();++beg){
       results.emplace_back(std::stoi(*beg));
    }
    return results;
}

Actually, if you read the question carefully, the number of integers on each line is given.

The next line contains an integer p (0 ≤ p ≤ n) at first, then follows p distinct integers a 1, a 2, ..., ap (1 ≤ ai ≤ n). These integers denote the indices of levels Little X can pass. The next line contains the levels Little Y can pass in the same format. It's assumed that levels are numbered from 1 to n.

p = Number of integers on each line.

Have a look at the following code which has Accepted code verdict on Codeforces:

#include<iostream> 
#include<set> 
#include<iterator> 


int main(){

    int N;
    std::cin>>N;

    std::set<int> uniqueNumbers;

    int t1, t2;
    int x;

    std::cin>>t1;
    for(int i=0;i<t1;i++){
        std::cin>>x;
        uniqueNumbers.insert(x);
    }
    
    std::cin>>t2;
    for(int i=0;i<t2;i++){
        std::cin>>x;
        uniqueNumbers.insert(x);
    }

    std::cout<< ((uniqueNumbers.size()==N) ? "I become the guy." : "Oh, my keyboard!");

    return 0;
}

Verdict:

在此处输入图像描述

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