简体   繁体   中英

Difference between reverse algorithm and list::reverse

std::list<int> l{1,2,3};
std::reverse(l.begin(), l.end());  // 1
l.reverse(); // 2

I guess I should prefer list::reverse() . Just wondering if there is any difference between 1 and 2 in above code? eg performance?

The difference is that list::reverse can rearrange the list by changing the internal pointers between the nodes. std::reverse from <algorithm> will move the values (which works even if the sequence is not a standard container).

In your specific case, using an int data type, it isn't that obvious if it is a win to move two pointers instead of swapping two int s. You might want to run some benchmarks if it is important.

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