📅  最后修改于: 2023-12-03 14:59:45.213000             🧑  作者: Mango
If you want to print the contents of a vector in C++ without using a loop, you can use the std::copy
algorithm together with the std::ostream_iterator
.
Here's an example code snippet:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
int main() {
std::vector<int> vec{1, 2, 3, 4, 5};
// Print the vector to stdout
std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, " "));
return 0;
}
In this code, we create a vector vec
with some integer values. The std::copy
algorithm takes the iterators (pointing to the beginning and end of the vector), and streams each integer value to the std::cout
object using the std::ostream_iterator
with a delimiter of a space character.
The output of this program will be:
1 2 3 4 5
Using std::copy
and std::ostream_iterator
allows us to write concise and expressive code without resorting to loops.