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

2022-01-10 00:00:00 pointers containers iterator 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.

相关文章