How to fill part of a vector with value in C++

1 Answer

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

// fill_n(OutputIterator first, Size n, const T& val);

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

int main () 
{
    std::vector<int> vec(10, -1);        
    
    printVector(vec);
    std::cout << "\n";

    std::fill_n (vec.begin(), 4, 3);     

    printVector(vec);
}




/*
run:

-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 
3 3 3 3 -1 -1 -1 -1 -1 -1 

*/

 



answered Nov 21, 2022 by avibootz

Related questions

2 answers 223 views
3 answers 338 views
338 views asked Nov 20, 2022 by avibootz
1 answer 355 views
2 answers 314 views
1 answer 245 views
1 answer 288 views
1 answer 301 views
...