How to print every second element of a vector in C++

2 Answers

0 votes
#include <iostream>
#include <vector>
 
using std::vector;
using std::cout;
using std::endl;
 
int main()
{
    vector<int> vec{ 1, 3, 8, 23, 99, 12, 100, 7 };
     
    for (int i = 1; i < vec.size(); i += 2) {
        cout << vec.begin()[i] << ' ';
    }
    
    cout << endl;
}
 
 
/*
run:
 
3 23 12 7 
 
*/

 



answered Jan 19, 2018 by avibootz
edited Oct 7, 2024 by avibootz
0 votes
#include <iostream>
#include <vector>
 
using std::vector;
using std::cout;
using std::endl;
 
int main()
{
    vector<int> vec{ 1, 3, 8, 23, 99, 12, 100, 7 };
     
    vector<int>::iterator pos;
    for (pos = vec.begin() + 1; pos < vec.end(); pos += 2) {
        cout << *pos << ' ';
    }

    cout << endl;
}
 
 
/*
run:
 
3 23 12 7 
 
*/

 



answered Jan 19, 2018 by avibootz
edited Oct 7, 2024 by avibootz
...