std::set<int> tmp_{30, 40};
int i=0;
while(tmp_[i]==40)
{
i++;
}
tmp_erase(i);
How do I remove an element at position i?I cannot use erase because i
is not std::set::iteretor
std::set<int> tmp_{30, 40};
int i=0;
while(tmp_[i]==40)
{
i++;
}
tmp_erase(i);
How do I remove an element at position i?I cannot use erase because i
is not std::set::iteretor
[]
operator is not defined for std::set
, thus you cannot erase element at a specified position. You can use std::find
to find a specified element by value
std::set<int> tmp_{30, 40};
auto i = std::find(tmp_.begin(), tmp_.end(), 40);
tmp_.erase(i);
erase
also have an overload for const key_type& key
, so you can simply use erase(40)
You have to use std::advance to move an iterator to the position you want and then std::set::erase() on that iterator to remove the item it points to and rebalance the tree:
std::set<int> tmp_{30, 40, 35, 50};
// remove the second element, 35, since set is ordered
auto it = tmp_.begin();
std::advance(it, 1); // to remove 40, advance 2, to remove 50... 3
tmp_.erase(it);
... it's quite common to do this kind of operations on associative containers, mostly when they are linked to widgets or other external, linear objects, but you may also want to consider the use of std::unordered_set if the automatic reordering is not a desired behaviour or std::vector.
std::set is an Associative Containers and they are internally implemented by balanced binary trees.
[] operator is not applicable for sets.
You have to search for the element in the std::set using iterators or use find() function to find element in set and then erase it.