How to swap elements in a vector with C++

1 Answer

0 votes
#include <iostream>
#include <vector>    

void printVector(std::vector<int> const &v) {
    for (auto const &n: v) {
        std::cout << n << " ";
    }
}

int main () {
    std::vector<int> vec {1, 2, 3, 100, 5, 6}; 
    
    printVector(vec);
    std::cout << '\n';

    std::iter_swap(vec.begin() + 1, vec.begin() + 3); 
    
    printVector(vec);                                           
}



/*
run:

1 2 3 100 5 6 
1 100 3 2 5 6 

*/

 



answered Nov 22, 2022 by avibootz

Related questions

1 answer 110 views
1 answer 168 views
1 answer 182 views
1 answer 91 views
1 answer 175 views
1 answer 239 views
239 views asked Aug 1, 2020 by avibootz
...