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

后端 未结 6 1554
一向
一向 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:26

    You can use the generate algorithm, for a more general way of filling up containers:

    #include 
    #include 
    #include 
    
    struct c_unique {
       int current;
       c_unique() {current=0;}
       int operator()() {return ++current;}
    } UniqueNumber;
    
    
    int main () {
      vector myvector (8);
      generate (myvector.begin(), myvector.end(), UniqueNumber);
    
      cout << "\nmyvector contains:";
      for (vector::iterator it=myvector.begin(); it!=myvector.end(); ++it)
        cout << " " << *it;
    
      cout << endl;
    
      return 0;
    }
    

    This was shamelessly lifted and edited from cplusplusreference.

提交回复
热议问题