QCustomPlot Discussion and Comments

problem with add dataReturn to overview

Hi every one, i'm using this code to reserve100 data point to my graph:

QVector<QCPGraphData> my_new_data(100);
//set value to new points

it runs every 40 ms that i receive new data from USB.
the problem is: it add data before the previous data(100 points with zero value added before my already existed data). why? i checked the alreadystored true. it would not check the data to resort it.
how i can add the new data to end of previous data? or better way to reserve memory without removing previous data?

See the documentation of the add method, especially what alreadysorted does, and what happens when you modify the keys of data points after having them added to the graph:

QCPDataContainer<DataType>::add documentation

QCPDataContainer<DataType> general documentation

especially this part:
The data can be accessed with the provided const iterators (constBegin, constEnd). If it is necessary to alter existing data in-place, the non-const iterators can be used (begin, end). Changing data members that are not the sort key (for most data types called key) is safe from the container's perspective.

Great care must be taken however if the sort key is modified through the non-const iterators. For performance reasons, the iterators don't automatically cause a re-sorting upon their manipulation. It is thus the responsibility of the user to leave the container in a sorted state when finished with the data manipulation, before calling any other methods on the container. A complete re-sort (e.g. after finishing all sort key manipulation) can be done by calling sort. Failing to do so can not be detected by the container efficiently and will cause both rendering artifacts and potential data loss.

Your new data points are all (0, 0) when you add them to the graph. If you modify the points (especially the keys) after that, you would need to manually sort them correctly or call a whole sorting run. This is not a good way to do it. It's better to set the keys and values of the new points in my_new_data and then add them to the graph.
Also in this case, If you set alreadysorted to true, you must be 100% sure that the keys are sorted ascending. Since you're only adding 100 points I recommend just leaving it off for safety (you might not have full control over what comes via USB). At 100 points you won't feel any speed benefit, and doing the check on an already sorted vector is very fast anyhow.

thanks DerManu. the post is helpful. 100 point is for example. data transfer rate is about 20MByte/s. so for speed benefit, i decide to allocate memory before transfer start. some time the user stop the transfer and some of allocated memory sells would have 0 value and the problem occurs. how can i de-allocate the excess memory sells?