Question

Just a random question i came across.

If I call myQVector[121] but that QVector has no item in it, does it create 121 space in that QVector or it only create the space named 121 in it?

I want to know because i'm creating a library for my cd(needed a project to learn) and i want to make the vector possible for multi-cd album.

What i mean

QVector myQVector;

myQVector[121] = "song number 1 on cd 1";
myQVector[122] = "song number 2 on cd 1";
myQVector[211] = "song number 1 on cd 2";
myQVector[322] = "song number 22 on cd 3";
Was it helpful?

Solution

From the QVector documentation:

QVector myQVector;

The default constructor constructs an empty QVector.

myQVector[121] = ....

operator[](int(i) has condition

i must be a valid index position in the vector (i.e., 0 <= i < size()).

So calling myQVector[121] does not satisfy the conditions.

You may want to have a look at QMap, std::map or std::unordered_map.

OTHER TIPS

No, it does not automatically increase the size (number of items) of the QVector. Instead, your application will crash, because you try to access an invalid index.

But a list/vector does not seem to be right data structure here. I believe, what you really want is a QMap, where you can assign a value to a key:

myMap[songId] = "song number 1 on cd 1";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top