简体   繁体   中英

what's the difference between "vector<int>& a " and "vector<int> a"?

I'm the beginner in C++. I try to write a program to rotate a vector one by one

ie, {1,2,3,4,5} --> {2,3,4,5,1} --> {3,4,5,1,2}

vector<vector<int>> allrot(const vector<int>& a)
{  
   vector<vector<int>> result;
   for (int i = 0; i < a.size(); i ++ ){
      rotate(a.begin(), a.begin() + 1, a.end());
      result.push_back(a);
   }
   return result;
}

This doesn't work, and I have several questions.

  1. Why should I use vector<int>& a rather than vector<int> a ?
  2. What's wrong with my code ?

Thank you for your help

When you pass vector<int> then function gets a copy of that vector. You can do anything you want with it in the function and your original data would not change.

When you pass vector<int>& then function gets the reference which means that any changes in the function would modify the original data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM