What is the most efficient way of adding non-repeated elements into STL container and what kind of container is the fastest? I have a large amount of data and I’m afraid each time I try to check if it is a new element or not, it takes a lot of time. I hope map be very fast.
// 1- Map
map<int, int> Map;
...
if(Map.find(Element)!=Map.end()) Map[Element]=ID;
// 2-Vector
vector<int> Vec;
...
if(find(Vec.begin(), Vec.end(), Element)!=Vec.end()) Vec.push_back(Element);
// 3-Set
// Edit: I made a mistake: set::find is O(LogN) not O(N)
Both
setandmaphasO(log(N))performance for looking up keys.vectorhasO(N).The difference between
setandmap, as far as you should be concerned, is whether you need to associate a key with a value, or just store a value directly. If you need the former, use amap, if you need the latter, use aset.In both cases, you should just use
insert()instead of doing afind().The reason is
insert()will insert the value into the container if and only if the container does not already contain that value (in the case ofmap, if the container does not contain that key). This might look likefor a map or
for a set.
You can consult the return value to determine whether or not an insertion was actually performed.
If you’re using C++11, you have two more choices, which are
std::unordered_mapandstd::unordered_set. These both have amortizedO(1)performance for insertions and lookups. However, they also require that the key (or value, in the case of set) be hashable, which means you’ll need to specializestd::hash<>for your key. Conversely,std::mapandstd::setrequire that your key (or value, in the case of set) respond tooperator<().