c++ print vector without loop
To print a vector in C++ without using a loop, you can utilize the std::for_each
algorithm from the <algorithm>
header along with a lambda function. Here are the steps to achieve this:
- Include the necessary header files:
#include <iostream>
#include <vector>
#include <algorithm>
- Create a function or lambda that will print each element of the vector. In this case, we will use a lambda function:
auto printElement = [](const int& element) {
std::cout << element << " ";
};
- Create a vector and populate it with some values:
std::vector<int> myVector = {1, 2, 3, 4, 5};
- Use the
std::for_each
algorithm to apply the lambda function to each element of the vector:
std::for_each(myVector.begin(), myVector.end(), printElement);
- Finally, add a newline after printing all the elements:
std::cout << std::endl;
The complete code would look like this:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
auto printElement = [](const int& element) {
std::cout << element << " ";
};
std::vector<int> myVector = {1, 2, 3, 4, 5};
std::for_each(myVector.begin(), myVector.end(), printElement);
std::cout << std::endl;
return 0;
}
When run, this code will print the elements of the vector without using a loop. The lambda function printElement
is applied to each element of the vector using std::for_each
, and the elements are printed with a space delimiter. The newline at the end ensures that the output is properly formatted.