将输入直接输入到 C++ 中的向量中
考虑以下代码片段:
...
int N,var;
vector<int> nums;
cin >> N;
while (N--)
{
cin >> var;
nums.push_back(var);
}
...
是否可以在不使用辅助变量(在本例中为 var
)的情况下执行此操作?
Consider the following code piece:
...
int N,var;
vector<int> nums;
cin >> N;
while (N--)
{
cin >> var;
nums.push_back(var);
}
...
Is it possible to do this without using an auxillary variable, in this case var
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
假设您已经阅读了最初的
N
,那么使用istream_iterator
有一个不错的技巧:back_inserter
对象将自身转变为一个迭代器,将元素添加到最后的向量。迭代器流可以通过读取元素的类型进行参数化,如果没有给出参数,则表示输入结束。Assuming you have already read the initial
N
, there is a nice trick usingistream_iterator
: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.如果您的工具箱中还没有
copy_n()
,那么您应该这样做。非常有用。使用这个实用程序,可以方便而优雅地将 n 个元素复制到向量中:
If you don't have already
copy_n()
in your toolbelt then you should. Very useful.With this utility it's convenient and elegant to copy n elements into a vector:
在一般情况下,这实际上效率更高。在没有初始
reserve
的情况下重复调用std::vector::push_back()
将导致大量重新分配。In the general case, this is actually more efficient. Calling
std::vector::push_back()
repeatedly without an initialreserve
will lead to lots of reallocations.迭戈·塞维利亚的回答暗示了这一点。
使用范围构造函数
Hinted from Diego Sevilla answer.
Use a range constructor
无需分配向量然后调整其大小。
迭代器比索引使用更可取。
No need to allocate the vector and then resize it.
Iterators are preferable to index usage.