如何用std::copy_n打印出std::vector的内容?

How to print out the contents of a std::vector with std::copy_n?

我想在 C++ 中打印出 std::vector 的内容。

这是我的:

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

using namespace std;

int main()
{
  vector<int> v;
  copy_n(istream_iterator<int>(cin), 5, back_inserter(v));

  return 0;
}

我可以用同样的方法打印std::vector的内容吗?

是的。您需要遍历向量和 std::copy the contents to the output stream with the help of std::ostream_iterator.

std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));

See live

是的,您可以将 vectorstd::ostream_iterator 的迭代器和大小传递给 std::copy_n

std::copy_n(v.begin(), v.size(), std::ostream_iterator<int>(std::cout, " "));