如何将N个整数读入向量? [英] How to read N integers into a vector?

查看:58
本文介绍了如何将N个整数读入向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想从标准输入到向量中读取所有个整数,我可以使用方便的方法:

If I want to read all integers from standard input to a vector, I can use the handy:

vector<int> v{istream_iterator<int>(cin), istream_iterator()};

但是假设我只想读取n整数.我所有的手环都是吗?

But let's assume I only want to read n integers. Is the hand-typed loop everything I got?

vector<int> v(n);
for(vector<int>::size_type i = 0; i < n; i++)
    cin >> v[i];

或者还有其他右手方法吗?

Or is there any more right-handed way to do this?

推荐答案

如注释中所述,copy_n对该作业不安全,但是您可以将copy_if与可变lambda一起使用:

As given in comments, copy_n is unsafe for this job, but you can use copy_if with mutable lambda:

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

int main(){
    const int N = 10;
    std::vector<int> v;
    //optionally v.reserve(N);
    std::copy_if(
        std::istream_iterator<int>(std::cin),
        std::istream_iterator<int>(), 
        std::back_inserter(v), 
        [count=N] (int)  mutable {
            return count && count--;
    });

    return 0;
}

在此答案中指出: std :: copy n个元素或到最后

这篇关于如何将N个整数读入向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆