【问题标题】:Pointer to nth element in a vector of list指向列表向量中第 n 个元素的指针
【发布时间】:2018-04-01 01:19:01
【问题描述】:

我需要返回一个指向列表中某个值的指针

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

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

【问题讨论】:

  • 你知道&amp;,也就是地址操作符吗?
  • 我想可能是XY problem。为什么要返回指向列表向量元素的指针?为什么不使用迭代器而只增加begin()
  • 顺便说一下,列表没有快速随机访问。这意味着访问一些随机元素需要线性时间。
  • &amp;(*(std::next(lists.at.(i).begin(), 1)))* 将迭代器转换为引用,&amp; 获取引用所指的地址。
  • 为什么需要指针而不是迭代器?

标签: c++ list pointers vector


【解决方案1】:

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

std::next 返回一个迭代器。您可以使用间接运算符来获取指向的对象。您可以使用 addressof 运算符来获取该对象的内存地址(即指针)。所以:

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

int 无关,但在极少数情况下,您可能需要使用std::addressof,以防类型具有重载的addressof 运算符。

另外,我建议考虑返回指针而不是迭代器本身是否有意义。

【讨论】:

  • 为什么是std::next?为什么不只是data_type* ptr = &amp;lists.at(i).front()
  • @zindarod 返回指向第一个元素的指针。约翰说他想要指向[一个对象,我假设]第一个值之后。 std::next 可用于获取第一个之后的元素。
  • ptr++ 会给他下一个值,不是吗?
  • @zindarod 不,不会。 std::list 不是数组。 (对不起,我先说是,因为我误读了你的问题)
  • @zindarod 没错。这就是为什么我建议 john 考虑返回迭代器是否更有意义的原因之一(它可能确实如此)。
【解决方案2】:

我想到了这样一个函数:

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();
}

【讨论】:

    【解决方案3】:

    迭代器只是“更好”的指针。也就是说,您可以将它们用作指针(通过解除引用来访问值)

    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&lt;int&gt;::iterator,你可以取消引用并再次获得引用

    return &(*it);
    

    有关迭代器的更多信息,您可以查看here。可以看到迭代器有很多种类型,但都可以像指针一样解引用。

    std::list:iterator 是双向迭代器(它们没有随机访问,但你可以一次移动一个元素,向前或向后)

    【讨论】:

    • std::list 迭代器不仅是一个前向迭代器,更具体地说是一个双向迭代器。
    • 好点,谢谢。甚至不知道列表是双向链接的
    猜你喜欢
    • 1970-01-01
    • 2011-03-12
    • 1970-01-01
    • 2015-12-06
    • 2022-01-21
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    相关资源
    最近更新 更多