How to pad a vector to a specified length with a given value in C++

1 Answer

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

std::vector<int> vectorPad(const std::vector<int>& arr, int size, int value) {
    std::vector<int> paddedArray = arr;
    
    if (size > paddedArray.size()) {
        paddedArray.resize(size, value);
    }
    
    return paddedArray;
}

int main() {
    std::vector<int> arr = {1, 2, 3};
    std::vector<int> paddedVec = vectorPad(arr, 5, 0);

    for (int num : paddedVec) {
        std::cout << num << " ";
    }
}



/*
run:

1 2 3 0 0 

*/

 



answered Feb 4 by avibootz
...