Returning a pointer to a vector element in 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 ++中返回指向向量元素的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在c ++中返回指向向量元素的指针


- 将函数的返回值分配给引用 C++? 2022-01-01
- OpenGL 对象的 RAII 包装器 2021-01-01
- 哪个更快:if (bool) 或 if(int)? 2022-01-01
- DoEvents 等效于 C++? 2021-01-01
- GDB 不显示函数名 2022-01-01
- 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01
- 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01
- XML Schema 到 C++ 类 2022-01-01
- 将 hdc 内容复制到位图 2022-09-04
- 如何提取 __VA_ARGS__? 2022-01-01