SeeSoftware SeeSoftware - 4 months ago 8
C++ Question

How to check if an index in a vector is already used

How do I check if an index in a vector is already used ?

I want something like this:

if(isUsed(vector,index))
do something
else
do something else


example:

std::vector<int> myVector;
myVector[0] = 5;
myVector[2] = 0;
myVector[3] = 1;

myVector.erase(3);

isUsed(myVector,3) = false
isUsed(myVector,1) = false
isUsed(myVector,2) = true
isUsed(myVector,5) = false
isUsed(myVector,0) = true


or:

std::map<int,std::string> myMap;
myMap[1] = "x";

myMap.count(1) > 0 = true
myMap.count(0) > 0 = false


I want this function to be fast because im working with a lot of indexes.

Answer

you may try an std::unordered_map, it works like a map, but is much faster for most operations

std::unordered_map<int,std::string> myMap;
myMap[1] = "w";

myMap.count(1) > 0 == true
myMap.count(0) > 0 == false