Things to note when using the STLS algorithm

Question: Can a sorting algorithm such as std::transform() be used for associative containers (such as std::set)?
Answer: Even if it can, it should not be done. The content of associative containers should be regarded as constants. This is because associative containers are sorted when inserting elements. Therefore, the relative position of elements is not only important for functions such as find( ), but also for the efficiency of the container. Therefore, changing order algorithms such as std::transform() should not be used for STL set.
Question: To set each element of the sequence container to a specific value, can you use std::transform( )? Answer: Although you can use std::transform( ), it is more appropriate to use fill() or fill_n( ).
Question: Does copy_backward() reverse the order of the elements in the target container?
Answer: No. The STL algorithm copy_backward() copies the elements in reverse order, but does not change the order of the elements, that is, it copies from the end of the range to the beginning. If you want to reverse the order of the elements in the set, you should use std::reverse( ).
Q: Should I use std::sort() for list?
Answer: std::sort() can be used for lists, and the usage is the same as for other sequential containers. However, the list needs to maintain a special feature: operations on the list will not cause the existing iterator to fail, and std::sort() cannot guarantee that this feature will be maintained. Therefore, STL list provides the sort algorithm through the member function list::sort( ). This function should be used because it ensures that the iterator to the elements in the list will not fail, even if the relative positions of the elements have changed.
Question: Why is it important to use functions such as lower_bound() or upper_bound() when inserting elements into an ordered range?
Answer: These two functions respectively provide the first position and the last position in the ordered set. Inserting elements into these positions will not destroy the ordered state of the set.

Guess you like

Origin blog.csdn.net/weixin_45590473/article/details/108031901