There is a link to the vector

vector<CCMD> &commands = *new vector<CCMD>(); 

How to move an element in the original vector through it?

swap somehow works incomprehensibly with links, it swaps elements in the link, but not in the original .. I myself did not understand anything.

 swap(commands[i], commands[i + 1]); 

UPD

Code:

 commands = bots[0]->command.commandListChat; ... cout << "copy - " << commands[i].instance->triggerS << endl; cout << "orig - " << bots[0]->command.commandListChat[i].instance->triggerS << endl; swap(commands[i], commands[i + 1]); cout << "copy - " << commands[i].instance->triggerS << endl; cout << "orig - " << bots[0]->command.commandListChat[i].instance->triggerS << endl; 

Conclusion:

 copy - 2 orig - 2 copy - 1 orig - 2 

UPD2

I understood. The link cannot be changed. Very interesting. I will go to redo everything.

  • maybe there is still copying? or COW? - KoVadim
  • vector<CCMD> &commands = *new vector<CCMD>(); - and then how to release the memory? delete &commands; ? Not the best method - for a number of reasons ... - Harry
  • you can't write like that, it's UB - KoVadim

2 answers 2

A link is an exact alias, so you cannot "change in the link" without changing the original. In fact, no matter how you work with the link, you work with the original. This is not a copy!

Everything works well:

 int main() { vector<int> a = { 0, 1, 2, 3, 4 }; vector<int> &c = a; for(auto i: a) cout << i << " "; cout << endl; swap(c[2],c[3]); for(auto i: a) cout << i << " "; cout << endl; } 
  • Completed the question. I myself am at a loss, but the original does not change. If instead of a link to write the path to the original - everything works - Vitaly
 commands = bots[0]->command.commandListChat; 

Not in the references, you just made a copy of the vector here. In more detail code please.

  • What is more? I have 3 vectors. Depending on the situation, I need to change the reference to one of the vectors, but this cannot be done, as I wrote at the end. - Vitali