What’s the benefit of std::back_inserter over std::inserter?

Iterator types std::back_inserter returns std::back_insert_iterator that uses Container::push_back(). std::inserter returns std::insert_iterator that uses Container::insert(). std::list For lists std::list::push_back is almost the same as std::list::insert. The only difference is that insert returns iterator to inserted element. bits/stl_list.h void push_back(const value_type& __x) { this->_M_insert(end(), __x); } void _M_insert(iterator __position, const value_type& __x) { _Node* __tmp = _M_create_node(__x); … Read more

Does moving a vector invalidate iterators?

While it might be reasonable to assume that iterators are still valid after a move, I don’t think the Standard actually guarantees this. Therefore, the iterators are in an undefined state after the move. There is no reference I can find in the Standard which specifically states that iterators that existed before a move are … Read more

How to use an iterator?

That your code compiles at all is probably because you have a using namespace std somewhere. (Otherwise vector would have to be std::vector.) That’s something I would advise against and you have just provided a good case why: By accident, your call picks up std::distance(), which takes two iterators and calculates the distance between them. … Read more

How do I create a Vec from a range and shuffle it?

Rand v0.6.0 The Rng::shuffle method is now deprecated; rand::seq::SliceRandom trait should be used. It provides the shuffle() method on all slices, which accepts an Rng instance: // Rust edition 2018 no longer needs extern crate use rand::thread_rng; use rand::seq::SliceRandom; fn main() { let mut vec: Vec<u32> = (0..10).collect(); vec.shuffle(&mut thread_rng()); println!(“{:?}”, vec); } See it … Read more