Reputation: 41
I have 3 iterators which belong to 3 vectors A, B and C. A function minn
is called with these 3 iterators which returns the iterator with minimum value. Now how can i know which vector does the returned iterator minit
belongs to?
code -
vector<int>::iterator a = A.begin(), b = B.begin(), c = C.begin();
auto minit = minn(a,b,c);
Upvotes: 3
Views: 488
Reputation: 62719
The easiest option would be to not pass these iterators by value, so when you modify minit
, whichever of a
, b
or c
was chosen also changes.
bool itLess(std::vector<int>::iterator& l, std::vector<int>::iterator& r)
{
return *l < *r;
}
for (
auto a = A.begin(), b = B.begin(), c = C.begin();
a != A.end() && b != B.end() && c != C.end();
)
{
auto [minit, maxit] = std::minmax({std::ref(a), std::ref(b), std::ref(c)}, itLess);
// use minit.get() and maxit.get()
}
Upvotes: 1
Reputation: 4838
We can take advantage of the fact that vector stores its elements in a single continuous array. We can check if the element pointed by the iterator is located in memory between the beginning and the end of that array.
template<typename T>
bool isFromVector(const typename std::vector<T>::const_iterator &i, const std::vector<T> &v)
{
const T *const dataBeginning = v.data();
const T *const dataEnd = v.data() + v.size();
const T *const element = &*i;
return std::less_equal<const T*>()(dataBeginning, element) && std::greater<const T*>()(dataEnd, element);
}
Upvotes: 0