Shibli
Shibli

Reputation: 6139

Obtaining the index of a member from its address

Is it possible to get the index of a member in a container by knowing its address? A code which describes what is wanted is below.

#include <iostream>
#include <vector>
#include <functional>
using namespace std;

struct Point {};

struct Triangle
{
    vector<reference_wrapper<Point>> p;
};

int main()
{
    vector<Point> p (3);    

    Triangle t;
    t.p.push_back (ref(p[0]));
    t.p.push_back (ref(p[1]));
    t.p.push_back (ref(p[2]));
    // push_back order may be random

    for (unsigned int i=0; i<t.p.size(); ++i)
    {
        // print index of t.p.get() in vector<Point>p
    }

    return 0;
}

Upvotes: 0

Views: 60

Answers (4)

Piotr Siupa
Piotr Siupa

Reputation: 4838

vector is internally an array, so you can use it.

int index = &t.p.get() - &p[0];

Upvotes: 1

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

If you have a memory contiguous container (std::basic_string<>, std::vector<> and std::array<> in the standard library), then yes, you can get an element's index if you have a reference or a pointer to it, as well as a reference or pointer to the first element of the container.

std::vector<X> v;
...
X* xp = &v[100];
auto index = xp - &v[0]; // index == 100

Otherwise, if the container is not contiguous, or you don't have access to the first element of the container, then no, you can't.

Upvotes: 2

Alex Kleiman
Alex Kleiman

Reputation: 709

If the array starts at memory location x, then you can obtain the index like so: &(t.p[i]) - x)

Upvotes: 0

user2030677
user2030677

Reputation: 3526

for (unsigned int i = 0; i < t.p.size(); ++i)
{
    std::cout << "Index = " << &t[t.size()] - &t.at(i) << std::endl;
}

Upvotes: 0

Related Questions