How to fill a vector with non-trivial initial values?

后端 未结 6 1488
一向
一向 2021-02-05 12:38

I know how to fill an std::vector with non-trivial initial values, e.g. sequence numbers:

void IndexArray( unsigned int length, std::vector&a         


        
6条回答
  •  鱼传尺愫
    2021-02-05 13:32

    I know this has already been answered, but I prefer the "fill" function in the algorithm library, since it's seems more intuitive for me to read:

    // fill algorithm example
    #include 
    #include 
    #include 
    using namespace std;
    
    int main () {
      vector myvector (8);                       // myvector: 0 0 0 0 0 0 0 0
    
      fill (myvector.begin(),myvector.begin()+4,5);   // myvector: 5 5 5 5 0 0 0 0
      fill (myvector.begin()+3,myvector.end()-2,8);   // myvector: 5 5 5 8 8 8 0 0
    
      cout << "myvector contains:";
      for (vector::iterator it=myvector.begin(); it!=myvector.end(); ++it)
        cout << " " << *it;
    
      cout << endl;
    
      return 0;
    }
    

    This too was also shamelessly lifted from cplusplusreference.

提交回复
热议问题