在c ++中返回指向向量元素的指针

Returning a pointer to a vector element in c++(在c ++中返回指向向量元素的指针)
本文介绍了在c ++中返回指向向量元素的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在全局范围内有一个 myObjects 向量.我有一个方法,它使用 std::vector<myObject>::const_iterator 来遍历向量,并进行一些比较以找到特定元素.找到所需元素后,我希望能够返回指向它的指针(该向量存在于全局范围内).

I have a vector of myObjects in global scope. I have a method which uses a std::vector<myObject>::const_iterator to traverse the vector, and doing some comparisons to find a specific element. Once I have found the required element, I want to be able to return a pointer to it (the vector exists in global scope).

如果我返回&iterator,我是返回迭代器的地址还是迭代器指向的地址?

If I return &iterator, am I returning the address of the iterator or the address of what the iterator is pointing to?

我是否需要将 const_iterator 转换回一个 myObject,然后返回它的地址?

Do I need to cast the const_iterator back to a myObject, then return the address of that?

推荐答案

返回迭代器指向的东西的地址:

Return the address of the thing pointed to by the iterator:

&(*iterator)

澄清一些困惑:

vector <int> vec;          // a global vector of ints

void f() {
   vec.push_back( 1 );    // add to the global vector
   vector <int>::iterator it = vec.begin();
   * it = 2;              // change what was 1 to 2
   int * p = &(*it);      // get pointer to first element
   * p = 3;               // change what was 2 to 3
}

不需要指针向量或动态分配.

No need for vectors of pointers or dynamic allocation.

这篇关于在c ++中返回指向向量元素的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)