简体   繁体   English

C ++初始化变量并使用std :: cin进行赋值

[英]C++ initializing a variable and assigning with std::cin

This might be a bit stupid question, but I have failed to find any kind of answer for it anywhere else. 这可能是一个有点愚蠢的问题,但我没有在其他任何地方找到任何答案。 I am writing codes in C++ (atleast 11 I think) and have to use: 我用C ++编写代码(我认为至少11)并且必须使用:

int N;
cin >> N;  

My question is if there is an elegant way to write it as a one line of command? 我的问题是,是否有一种优雅的方式将其写为一行命令? I already know that I can just remove the linebreaks and just put them on one line, but that wouldn't let me use it in a oneliner loop: 我已经知道我可以删除换行符并将它们放在一行上,但这不会让我在oneliner循环中使用它:

for(int i=0; i<10; i++) myVector.push_back();

Apart from writing a function, you can put initialization and reading into the header of the for loop: 除了编写函数之外,您还可以将初始化和读取放入for循环的标题中:

for (int i = 0, n ; i != 5 && cin >> n ; i++)
    x.push_back(n);

This also addresses the problem of having to check the return value of cin >> n to ensure that a value has been read properly. 这也解决了必须检查cin >> n的返回值以确保已正确读取值的问题。

Demo. 演示。

An other alternative using algorithms and iterators: 另一种使用算法和迭代器的替代方法:

std::copy_n(std::istream_iterator<int>{std::cin}
           ,10
           ,std::back_insert_iterator<std::vector<int>>{myVector});

I don't think that your approach is the "best" one, you're pushing back positions (that's so expensive) on a vector and you already know the positions the vector have. 我不认为你的方法是“最好的”,你在向量上推回位置(这是如此昂贵),你已经知道了向量的位置。 Why don't you just do this: 你为什么不这样做:

myVector.resize(10);
for (int i = 0; i < 10; i++) cin >> myVector [i];

But, if you can't because you want to use push_back() , why don't you just open the braces and write the code inside? 但是,如果你不能因为你想使用push_back() ,你为什么不打开大括号并在里面编写代码呢? What's the matter with that? 那有什么关系?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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