[Gabriel] 5 ways to output (traverse) elements in vector containers in C++

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: 

  1. 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 << " ";
    }
    

     

  2. 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 << " ";
    }
    

     

  3. 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 << " ";
    });
    

     

  4. 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 << " ";
    }
    

     

  5. 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 

 

Guess you like

Origin blog.csdn.net/weixin_74802373/article/details/130043838