将输入直接输入C ++中的向量 [英] Getting input directly into a vector in C++

查看:119
本文介绍了将输入直接输入C ++中的向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码段:

...
int N,var;
vector<int> nums;
cin >> N;
while (N--)
{
   cin >> var;
   nums.push_back(var);
}
...

是否可以在不使用辅助变量的情况下执行此操作,在这种情况下为var?

Is it possible to do this without using an auxillary variable, in this case var?

推荐答案

假定您已经阅读了初始的N,使用istream_iterator有一个不错的技巧:

Assuming you have already read the initial N, there is a nice trick using istream_iterator:

std::vector<int> nums;
nums.reserve(N);
std::copy(std::istream_iterator<int>(std::cin), 
          std::istream_iterator<int>(),
          std::back_inserter(nums));

back_inserter对象将自身变成一个迭代器,该迭代器最后将元素添加到向量中.可以通过读取的元素的类型来对迭代器流进行参数化,如果没有给出参数,则表示输入结束.

The back_inserter object turns itself into an iterator that adds elements to the vector at the end. Iterator streams can be parameterized by the type of the elements read, and, if no parameter given, signals the end of input.

这篇关于将输入直接输入C ++中的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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