Passing to a Reference Argument by Value

前端 未结 7 1053
名媛妹妹
名媛妹妹 2021-01-17 14:40

Consider this simple program:

vector foo = {0, 42, 0, 42, 0, 42};
replace(begin(foo), end(foo), foo.front(), 13);

for(const auto& i : foo) co         


        
7条回答
  •  庸人自扰
    2021-01-17 15:31

    In this particular case (when the old value is the first of the vector), you can reverse the order of substitution with rbegin() and rend().

    In general, I don't know if it's possible, in a simple way, without make a copy.

    int main ()
     {
       std::vector foo = {0, 42, 0, 42, 0, 42};
       std::replace(foo.rbegin(), foo.rend(), foo.front(), 13);
    
       for(const auto & i : foo)
          std::cout << i << '\t';
    
       std::cout << std::endl;
    
       return 0;
     }
    

    p.s.: sorry for my bad English.

提交回复
热议问题