Hello everyone! I'm Gabriel! When we use vector to solve algorithm problems, we often need to traverse the output. For this, I have the following 5 methods:
- Use a range-based for loop to access elements from the vector container one by one and output them:
std::vector<int> vec = { 1, 2, 3, 4, 5 }; for (auto element : vec) { std::cout << element << " "; }
- Use an iterator to traverse the entire vector container and output the value of each element
std::vector<int> vec = { 1, 2, 3, 4, 5 }; for (auto it = vec.begin(); it != vec.end(); ++it) { std::cout << *it << " "; }
- Use the standard library algorithm
std::for_each()
to traverse the entire vector container and output the value of each element:std::vector<int> vec = { 1, 2, 3, 4, 5 }; std::for_each(vec.begin(), vec.end(), [](int element){ std::cout << element << " "; });
- Use the initial statement in the for loop introduced by C++11 to declare a counter variable, and then use
at()
the function of the vector container and the counter variable to output the value of each element:std::vector<int> vec = { 1, 2, 3, 4, 5 }; for (size_t i = 0; auto element = vec.at(i); ++i) { std::cout << element << " "; }
std::copy()
Copies all elements in the vector container to the output stream using standard library algorithms :std::vector<int> vec = { 1, 2, 3, 4, 5 }; std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, " "));
Note: The above examples all assume that the vector container contains integer types. If other types of elements are stored in the container, the code needs to be changed accordingly.
If you think my writing is not bad, please bookmark it and read it slowly