返回一个指向c ++中的向量元素的指针 [英] Returning a pointer to a vector element in 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)
/ strong>清除一些混乱:
To clear up some confusion:
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
}
不需要指针向量或动态
这篇关于返回一个指向c ++中的向量元素的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!