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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/641864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:26:39  来源:igfitidea点击:

Returning a pointer to a vector element in c++

c++pointerscontainersiterator

提问by Krakkos

I have a vector of myObjects in global scope. I have a method which uses a std::vector<myObject>::const_iteratorto 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).

我在全局范围内有一个 myObjects 向量。我有一个方法,它使用 astd::vector<myObject>::const_iterator来遍历向量,并进行一些比较以找到特定元素。找到所需元素后,我希望能够返回指向它的指针(向量存在于全局范围内)。

If I return &iterator, am I returning the address of the iterator or the address of what the iterator is pointing to?

如果我返回&iterator,我是返回迭代器的地址还是迭代器指向的地址?

Do I need to cast the const_iteratorback to a myObject, then return the address of that?

我是否需要将const_iterator返回转换为 myObject,然后返回它的地址?

回答by

Return the address of the thing pointed to by the iterator:

返回迭代器指向的事物的地址:

&(*iterator)

Edit: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
}

No need for vectors of pointers or dynamic allocation.

不需要指针向量或动态分配。

回答by David Rodríguez - dribeas

Returning &iterator will return the address of the iterator. If you want to return a way of referring to the element return the iterator itself.

返回 &iterator 将返回迭代器的地址。如果要返回引用元素的方式,请返回迭代器本身。

Beware that you do not need the vector to be a global in order to return the iterator/pointer, but that operations in the vector can invalidate the iterator. Adding elements to the vector, for example, can move the vector elements to a different position if the new size() is greater than the reserved memory. Deletion of an element before the given item from the vector will make the iterator refer to a different element.

请注意,为了返回迭代器/指针,您不需要向量是全局的,但是向量中的操作会使迭代器无效。例如,如果新的 size() 大于保留的内存,则向向量添加元素可以将向量元素移动到不同的位置。从向量中删除给定项之前的元素将使迭代器引用不同的元素。

In both cases, depending on the STL implementation it can be hard to debug with just random errors happening each so often.

在这两种情况下,根据 STL 实现,可能很难调试,只是经常发生随机错误。

EDIT after comment: 'yes, I didn't want to return the iterator a) because its const, and b) surely it is only a local, temporary iterator? – Krakkos'

评论后编辑:'是的,我不想返回迭代器 a) 因为它是常量,并且 b) 它肯定只是一个本地的临时迭代器?– 克拉科斯

Iterators are not more or less local or temporary than any other variable and they are copyable. You can return it and the compiler will make the copy for you as it will with the pointer.

迭代器并不比任何其他变量更多或更少的局部或临时性,并且它们是可复制的。您可以返回它,编译器将为您制作副本,就像使用指针一样。

Now with the const-ness. If the caller wants to perform modifications through the returned element (whether pointer or iterator) then you should use a non-const iterator. (Just remove the 'const_' from the definition of the iterator).

现在有了常量。如果调用者想通过返回的元素(无论是指针还是迭代器)执行修改,那么你应该使用非常量迭代器。(只需从迭代器的定义中删除“const_”)。

回答by aJ.

It is not a good idea to return iterators. Iterators become invalid when modifications to the vector (inversion\deletion ) happens. Also, the iterator is a local object created on stack and hence returning the address of the same is not at all safe. I'd suggest you to work with myObject rather than vector iterators.

返回迭代器不是一个好主意。当对向量 (inversion\deletion) 进行修改时,迭代器将失效。此外,迭代器是在堆栈上创建的本地对象,因此返回相同的地址根本不安全。我建议你使用 myObject 而不是向量迭代器。

EDIT:If the object is lightweight then its better you return the object itself. Otheriwise return pointers to myObject stored in the vector.

编辑:如果对象是轻量级的,那么最好返回对象本身。否则返回指向存储在向量中的 myObject 的指针。

回答by Aaron Saarela

As long as your vector remains in global scope you can return:

只要您的向量保持在全局范围内,您就可以返回:

&(*iterator)

I'll caution you that this is pretty dangerous in general. If your vector is ever moved out of global scope and is destructed, any pointers to myObject become invalid. If you're writing these functions as part of a larger project, returning a non-const pointer could lead someone to delete the return value. This will have undefined, and catastrophic, effects on the application.

我会提醒你,这通常是非常危险的。如果您的向量被移出全局范围并被破坏,则指向 myObject 的任何指针都将无效。如果您将这些函数作为较大项目的一部分编写,则返回非常量指针可能会导致某人删除返回值。这将对应用程序产生不确定的和灾难性的影响。

I'd rewrite this as:

我将其重写为:

myObject myFunction(const vector<myObject>& objects)
{
    // find the object in question and return a copy
    return *iterator;
}

If you need to modify the returned myObject, store your values as pointers and allocate them on the heap:

如果您需要修改返回的 myObject,请将您的值存储为指针并在堆上分配它们:

myObject* myFunction(const vector<myObject*>& objects)
{
    return *iterator;
}

That way you have control over when they're destructed.

这样你就可以控制它们何时被破坏。

Something like this will break your app:

像这样的事情会破坏你的应用程序:

g_vector<tmpClass> myVector;

    tmpClass t;
    t.i = 30;
    myVector.push_back(t);

    // my function returns a pointer to a value in myVector
    std::auto_ptr<tmpClass> t2(myFunction());

回答by Aaron Saarela

You can use the datafunction of the vector:

您可以使用向量的数据函数:

Returns a pointer to the first element in the vector.

返回指向向量中第一个元素的指针。

If don't want the pointer to the first element, but by index, then you can try, for example:

如果不想要指向第一个元素的指针,而是通过索引,那么您可以尝试,例如:

//the index to the element that you want to receive its pointer:
int i = n; //(n is whatever integer you want)

std::vector<myObject> vec;
myObject* ptr_to_first = vec.data();

//or

std::vector<myObject>* vec;
myObject* ptr_to_first = vec->data();

//then

myObject element = ptr_to_first[i]; //element at index i
myObject* ptr_to_element = &element;

回答by Aaron Saarela

Refer to dirkgently's and anon's answers, you can call the frontfunction instead of beginfunction, so you do nothave to write the *, but only the &.

请参阅dirkgently是和匿名的回答,您可以调用的功能,而不是开始功能,这样你就不能有写*,但只&

Code Example:

代码示例:

vector<myObject> vec; //You have a vector of your objects
myObject first = vec.front(); //returns reference, not iterator, to the first object in the vector so you had only to write the data type in the generic of your vector, i.e. myObject, and not all the iterator stuff and the vector again and :: of course
myObject* pointer_to_first_object = &first; //* between & and first is not there anymore, first is already the first object, not iterator to it.

回答by arviman

I'm not sure if returning the address of the thing pointed by the iterator is needed. All you need is the pointer itself. You will see STL's iterator class itself implementing the use of _Ptr for this purpose. So, just do:

我不确定是否需要返回迭代器指向的事物的地址。您所需要的只是指针本身。您将看到 STL 的迭代器类本身为此目的实现了 _Ptr 的使用。所以,只要这样做:

return iterator._Ptr;

回答by dirkgently

Say, you have the following:

说,你有以下几点:

std::vector<myObject>::const_iterator first = vObj.begin();

Then the first object in the vector is: *first. To get the address, use: &(*first).

那么向量中的第一个对象是:*first。要获取地址,请使用:&(*first)

However, in keeping with the STL design, I'd suggest return an iterator instead if you plan to pass it around later on to STL algorithms.

但是,为了与 STL 设计保持一致,如果您打算稍后将迭代器传递给 STL 算法,我建议您返回一个迭代器。

回答by Naveen

You are storing the copies of the myObject in the vector. So I believe the copying the instance of myObject is not a costly operation. Then I think the safest would be return a copy of the myObject from your function.

您将 myObject 的副本存储在向量中。所以我相信复制 myObject 的实例并不是一个代价高昂的操作。然后我认为最安全的方法是从您的函数中返回 myObject 的副本。