簡體   English   中英

指向列表向量中的第n個元素的指針

[英]Pointer to nth element in a vector of list

我需要返回指向列表中某個值的指針

std::vector<std::list<int>> lists;
...
if(lists.at(i).front()==val){
   //return a pointer after the first value
   return ptr;
}

我能想到的最好方法是使用std::next ,但是我不知道如何使它返回指針

我能想到的最好方法是使用std::next ,但是我不知道如何使它返回指針

std::next返回一個迭代器。 您可以使用間接運算符獲取指向的對象。 您可以使用addressof運算符獲取該對象的內存地址(即指針)。 所以:

auto it = whatever; // iterator to the object whose pointer you want
return &*it;        // return the pointer

int不相關,但在某些極少數情況下,如果類型具有重載的addressof運算符,則可能需要使用std::addressof

另外,我建議考慮返回指針而不是迭代器本身是否有意義。

迭代器只是“更好”的指針。 也就是說,您可以將它們用作指針(通過取消引用它們來訪問值)

auto it = lists.at(i).begin() // returns iterator to first element in i-th list in vector
...
*it // you can access value as if "it" was pointer
it++; // iterators can be "moved", that is, they will point to next element than before

如果您確實希望返回指針類型*int ,而不是std::list<int>::iterator ,請取消引用它並再次獲得引用

return &(*it);

有關迭代器的更多信息,可以在這里查看 您可以看到有很多類型的迭代器,但是所有迭代器都可以取消引用,就像它們是指針一樣。

std :: list <>:iterator是雙向迭代器(它們沒有隨機訪問權,但是可以一次或向前或向后移動一個元素)

我想到這樣的功能:

std::list<int>::iterator get(std::vector<std::list<int>>& lists, int i,int val)
{
   assert(i<lists.size());

   if(lists.at(i).front()==val)
    {
       //return a pointer after the first value
       std::list<int>::iterator it = lists.at(i).begin();
      return it++;
   } 
    return lists.at(i).end();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM