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 ++中返回指向向量元素的指针
基础教程推荐
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- c++ STL设置差异 2022-01-01
