如果我想从标准输入读取所有个整数到 vector ,我可以使用方便:
vector<int> v{istream_iterator<int>(cin), istream_iterator()};
但假设我只想读取 n
整数。手写循环是我得到的一切吗?
vector<int> v(n);
for(vector<int>::size_type i = 0; i < n; i++)
cin >> v[i];
或者有没有更多的右手方法可以做到这一点?
最佳答案
您通常不应该对 std::copy_n
这样做。 ,它假定提供的迭代器在增加 n 次时仍然有效:
Copies exactly
count
values from the range beginning atfirst
to the range beginning atresult
. Formally, for each non-negative integeri < n
, performs*(result + i) = *(first + i)
.
如果你能保证,那就没问题,但一般用std::cin
那是不可能的。你可以很容易地让它解除对无效迭代器的引用:
The default-constructed
std::istream_iterator
is known as the end-of-stream iterator. When a validstd::istream_iterator
reaches the end of the underlying stream, it becomes equal to the end-of-stream iterator. Dereferencing or incrementing it further invokes undefined behavior.
你的循环已经差不多了,尽管我可能会使用更强的终止条件来避免从“死”流中进行过多读取:
vector<int> v(n);
for(vector<int>::size_type i = 0; i < n; i++)
if (!cin >> v[i])
break;
实际上我很想把它包装成类似 std::copy_n
的东西。 , 但接受一个完整的“范围”,除了从 0 到 N 的计数之外,还可以验证其边界。
实现可能如下所示:
template<class InputIt, class Size, class OutputIt>
OutputIt copy_atmost_n(InputIt first, InputIt last, Size count, OutputIt result)
{
for (Size i = 0; i < count && first != last; ++i)
*result++ = *first++;
return result;
}
你会这样使用它:
copy_atmost_n(
std::istream_iterator<int>(std::cin),
std::istream_iterator<int>(),
N,
std::back_inserter(v)
);
现在你得到 M 个元素,其中 M 是提供的输入数量或 N,以较小者为准。
( live demo )
关于c++ - 如何将 N 个整数读入 vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54254075/