2014-08-31 4 views
0

주소를 알면 구성원을 색인에서 가져올 수 있습니까? 원하는 것을 설명하는 코드는 다음과 같습니다.주소에서 구성원 색인 얻기

#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; 
} 

답변

2

당신은 메모리 연속 용기 (표준 라이브러리에서 std::basic_string<>, std::vector<>std::array<>이있는 경우), 예, 참조 또는 포인터가있는 경우 요소 색인을 가져올 수 있으며 컨테이너의 첫 번째 요소에 대한 참조 또는 포인터도 얻을 수 있습니다.

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

그렇지 않으면 컨테이너가 인접하지 않거나 컨테이너의 첫 번째 요소에 액세스 할 수없는 경우 아니요, 그렇지 않을 수 없습니다.

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

배열이 메모리 위치 x에서 시작하면, 다음과 같이 인덱스를 얻을 수 있습니다 : &(t.p[i]) - x)

1

vector은 내부적으로 배열이므로 사용할 수 있습니다.

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