2013-10-06 30 views
2
 list<CPoint> l; 

     l.push_back(CPoint(1,2)); 
     l.push_back(CPoint(30,40)); 
     l.push_back(CPoint(4,6)); 
     l.push_back(CPoint(70,80)); 

     CPoint * point = 0; 

     for (list<CPoint>::iterator iter = l.begin(); 
       iter != l.end(); 
       iter++) 
     { 
      cout << iter->x << " , " << iter->y << endl; 

      // compilation error, I can't typcast it like below? 
      point = (CPoint *) iter; 
     } 

問題上面就是如何在循環中iter typcast的實際數據結構的指針?這樣我就可以編寫像point.xpoint.y這樣的代碼。如何typcast一個迭代器到原來的結構

以上是我編寫的演示代碼,但實際上我在搜索功能中使用了此代碼。如果在列表中找到一個項目,它將返回指向該項目的指針,否則返回NULL。爲了得到這個指針,我需要將迭代器解引用回底層的數據結構指針,但是怎麼做呢?謝謝。

回答

3

要解決你的語法錯誤,你需要提領迭代器,然後從下面對象取地址:

point = &*iter; 

你最好只使用std::find/std::find_if和存儲是從的std ::列表返回的迭代器。

auto it = std::find_if(l.begin(), l.end(), 
         [](const CPoint& cp) { return cp.x == 1 && cp.y == 2; }); 

if (it != l.end()) // test iterator to see is desired CPoint is found 
{ 
    std::cout << (*it).x << " " << (*it).y << std::endl; 
}