So i am making a custom edit control. In order to keep track of the contents of the edit control, I’m using a dynamically allocated char array.
- Now, I know that I need to insert in the middle of the array in
certain situations, such as when the user clicks on a particular
point. So, I was thinking, instead of a character array, I may use
std::vector, so i would be able to use the .insert function, and also
wouldn’t have to care much about the memory management. - I was also thinking maybe to directly store the input stream into an
array/vector of words(Without keeping a continuous buffer), since my
whole purpose with this is to implement syntax highlighting.
Which would be a better approach to go about things? And why?
For a text buffer with today computers you can indeed just use a single contiguous buffer (e.g. a vector) because CPUs are fast enough to make insertion time (an
o(n)operation with this naive approach) still a viable option.In the past when computers were thousands times slower a common simple approach was instead to keep the text in a buffer but with an “hole” corresponding to the cursor position, to make insertion an
o(1)operation and moving chars from one side of the hole to the other when cursor was moving in the text (basically making cursor movement ano(k)operation wherekis the number of skipped chars).For an editor designed for programmers the text is going to be subdivided in logical lines and therefore using an approach based on an array of pointers to lines seems appropriate. Even if this will make some cross-line operation somewhat annoying some of line-based operations will become easier… line numbering in display becomes a trivial problem, especially if you don’t need to implement line wrap (horrible with code anyway) by going for truncation and horizontal scrolling instead.