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 ++中返回指向向量元素的指针


基础教程推荐
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01