Reputation: 6149
There is an iterator to a vector. I want to know which index does iterator pointing to. So I made following but I am not sure.
int temp = -1;
std::vector <int> ::iterator f;
for (f=eFace[e].begin(); f!=eFace[e].end(); ++f)
{
if (*f == face)
{
switch (f-eFace[e].begin())
{
case 0:
temp = 5;
break;
case 1:
temp = 3;
break;
case 2:
temp = 4;
break;
case 3:
temp = 1;
break;
case 4:
temp = 2;
break;
case 5:
temp = 0;
break;
default:
throw;
}
break;
}
}
Upvotes: 2
Views: 198
Reputation: 299820
Getting clearer code would be much easier.
First, finding a value in a vector:
// Returns the index of `face` in `vec`.
// If `face` is not present in `vec`, returns `vec.size()`.
size_t findFaceIndex(int const face, std::vector<int> const& vec) {
std::vector<int>::const_iterator const it =
std::find(vec.begin(), vec.end(), face);
return it - vec.begin();
}
And now mapping:
static int const FaceMap[] = { 5, 3, 4, 1, 2, 0 };
static size_t const FaceMapSize = sizeof(FaceMap)/sizeof(int);
// Translate face index into ...
int faceIndexToX(size_t const index) {
if (index >= FaceMapSize) { throw std::runtime_error("out of bounds"); }
return FaceMap[index];
}
Upvotes: 2
Reputation: 61910
std::vector<int>::size_type index = std::distance (eFace [e].begin(), f);
Note that this can be slow if you execute it every loop though. Another option for vectors would be:
std::vector<int>::size_type index = f - eFace [e].begin();
This works because vectors use a random-access iterator, which is required to have subtraction defined, as pointed out by Steve Jessop below.
Upvotes: 4
Reputation: 22820
Why not something like this :
std::vector <int> ::iterator f;
int index = 0;
for (f=eFace[e].begin(); f!=eFace[e].end(); ++f)
{
// do sth
index++;
}
Upvotes: 2
Reputation: 10497
I wonder why you need the index of an array when you have the iterator anyway? Provided the iterator is random access you can subtract it from begin()
, but if the index is so important I wonder if you're better off just using that rather than an iterator - of course it depends on whether you have access to the code to refactor it.
I'm not sure quite what you're trying to achieve with your switch but if it's to map values then presumably a sparse vector would be far more appropriate?
Upvotes: 0
Reputation: 95
For your question "I want to know which index does iterator pointing to." by saying std::vector<int>::iterator f = eFace.begin();
you are creating an interator that would be similar to the index approach by saying std::vector<int>::size_type i = 0;
.
With iterators you use eFace.begin()
and != eFace.end()
the same way you would use i = 0
and != eFace.size()
when walking through a vector with a for
loop.
At least I think that's what your original question was.
Upvotes: 0