gpt4 book ai didi

c++ - 将输入流中固定数量的元素复制到 vector 中

转载 作者:太空狗 更新时间:2023-10-29 21:47:45 26 4
gpt4 key购买 nike

给定以下程序:

#include <vector>
#include <iostream>

using namespace std;

int main()
{
unsigned n;
vector<double> xvec;

cin >> n;
while (xvec.size() < n)
{
double x;
cin >> x;
xvec.push_back(x);
}

return 0;
}

有没有一种方法,使用 STL,在没有显式 while 循环的情况下编写它(例如,使用 copy() 算法和插入器?)。

我还没有找到在运行时读取元素数量时执行此操作的方法(如此处的变量“n”)。

最佳答案

这是将 n double 复制到 vector 中的一种方法:

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

int main()
{
unsigned n;
std::vector<double> xvec;

std::cin >> n;
xvec.reserve(n);
std:generate_n(std::back_inserter(xvec), n,
[]() { double d; std::cin >> d; return d; });

std::copy(xvec.begin(), xvec.end(),
std::ostream_iterator<double>(std::cout, " "));

std::cout << "\n";

return 0;
}

注意:使用 std::copy_n 的替代方法将不起作用:

std::copy_n(std::istream_iterator<double>(std::cin),
n,
std::back_inserter(xvec));

这实际上读取了 n+1 个元素,但只复制了 n 个元素(至少在 g++ 4.6.3 上是这样)。


注意 2:将答案限制为 C++98,这是一种可能的解决方案:

double GetD() { double d; std::cin >> d; return d; }
...
std:generate_n(std::back_inserter(xvec), n, GetD);

关于c++ - 将输入流中固定数量的元素复制到 vector 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12516303/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com