c++ - Fill edges and center of array/vector with different values -


i create function initializes vector or array of size width * height, creates border around these values.

the values around outside need initialized different value ones in center.

the objects storing not have default constructor, cannot rely on initialization.

this code have far, feels there should simpler or more idiomatic way of doing this.

i can use features , including c++1z.

#include <iostream> #include <vector>  void fill_values(const unsigned width, const unsigned height, std::vector<int> &values) {     for(unsigned y=0; y<height+2; ++y) {         for(unsigned x=0; x<width+2; ++x) {             if(x==0 || x==width+1 || y==0 || y==height+1) {                 values.push_back(1);             } else {                 values.push_back(0);             }         }     } }  int main(int argc, char *argv[]) {     const unsigned width = 4;     const unsigned height = 3;     std::vector<int> values;      fill_values(width, height, values);      for(unsigned y=0; y<height+2; ++y) {         for(unsigned x=0; x<width+2; ++x) {             std::cout << values[y * (width+2) + x];         }         std::cout << '\n';     }      return 0; } 

output : -

111111 100001 100001 100001 111111 

honestly, code fine. pretty understood does.

but in spirit of proposing alternate complex implementations, i'd propose following. different way fill matrix add full row of 1s, height rows of 1000...001, full row of 1s. can make bit more explicit. also, suggest returning vector instead of filling it:

std::vector<int> fill_values(const unsigned width, const unsigned height) {     std::vector<int> m;     m.reserve((width + 2) * (height + 2));      // add row of 1s     m.insert(m.end(), width + 2, 1);      // add height middle rows     (int = 0; < height; ++i) {         m.push_back(1);         m.insert(m.end(), width, 0);         m.push_back(1);     }      // , final row of 1s     m.insert(m.end(), width + 2, 1);      return m; } 

Comments