How to use QVector at or operator [] to get a pointer to an element

I would like to get a pointer to a QVector element so that I can use this object elsewhere, but the at() method gives me the value of const T& , and operator[] gives me the value of T& .

I am confused about how to use them to get a pointer so that I use the same object instead of using the copy constructor.

+4
source share
2 answers

The value of A T& not a copy, it is a reference .

Links are very similar to pointers: they are lightweight and can be used to modify the underlying object. Only you use them with the same syntax as direct objects (with dots instead of arrows), and some other differences that you can check in the article.

To edit an object inside Vector, you can use, for example, vector[i].action(); . This will call the action () method from the object inside the vector, not from the copy. You can also pass a link to other functions (provided that they accept supporting arguments), and they will still point to the same object.

You can also get the address of an object from a link: Object* pObject = & vector[i]; and use it like any pointer.

If you really need pointers to objects, you can also use a vector of pointers: QVector<Object*> vector; However, this requires you to create / destroy processing, which you do not need with Vector objects.

Now, if you want a pointer to the vector itself, just do QVector<Object> *pVector = &vector;

+10
source

QVector::operator[] returns a reference to the element at the specified index. A link can be changed if it is not a constant reference, which is returned by QVector::at() .

You can simply change the element by assigning a new value or using the modifying element of the object, for example, in the following examples:

 // vector of primitive types: QVector<int> vector; vector.append(3); vector.append(5); vector.append(7); vector[0] = 2; // vector[0] is now 2 vector[1]++; // vector[1] is now 6 vector[2] -= 4; // vector[2] is now 3 // vector of objects: QVector<QString> strings; strings.append(QString("test")); strings[0].append("ing"); // strings[0] is now "testing" 

QMap and QHash support operator[] for non-existent keys, which makes the following possible:

 QMap<int, int> map; map[0] = 4; map[3] = 5; 

One of the drawbacks of operator[] is that the record is created if it did not exist before:

 // before: map contains entries with key 0 and 3 int myEntry = map[2]; // myEntry is now 0 // after: map contains entries with keys 0, 2 and 3 
+3
source

Source: https://habr.com/ru/post/1413303/


All Articles