Bug 163738 - Use insert() to add multiple values in containers instead of a loop
Summary: Use insert() to add multiple values in containers instead of a loop
Status: NEW
Alias: None
Product: LibreOffice
Classification: Unclassified
Component: LibreOffice (show other bugs)
Version:
(earliest affected)
unspecified
Hardware: All All
: medium normal
Assignee: Not Assigned
URL:
Whiteboard: target:25.2.0
Keywords: difficultyBeginner, easyHack, skillCpp, topicCleanup
Depends on:
Blocks: Dev-related
  Show dependency treegraph
 
Reported: 2024-11-02 16:26 UTC by Hossein
Modified: 2024-11-02 21:33 UTC (History)
3 users (show)

See Also:
Crash report or crash signature:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Hossein 2024-11-02 16:26:27 UTC
Description:
In several places in the code, you may see the use of for loops to insert values from a container to another.

It is more efficient and better readable if insert function is used instead of a loop.

For example, consider vector. One may use insert function. The insert function is improved in C++20 which is now the baseline for LibreOffice code:

std::vector<T,Allocator>::insert
https://en.cppreference.com/w/cpp/container/vector/insert

As an example, consider this code:

std::vector<int> v {1, 2, 3}, to_insert {4, 5};

for ( size_t i = 0; i < to_insert.size(); ++i ) {
    v.push_back(to_insert[i]);
}

The loop can be written as simple as:

v.insert(v.end(), to_insert.begin(), to_insert.end());

Finding Candidates:
You can try finding "for" loops which consider the size or length of a container with: 

$ git grep -E "for ?\(" | grep -iF "size()"
$ git grep -E "for ?\(" | grep -iF "length()"

Note all of the found instances are suitable for the current issue. Some of them can be improved with a range-based for loop:

tdf#145538 Use range based for loops
https://bugs.documentfoundation.org/show_bug.cgi?id=145538

One trick to find some of the more relevant instances is searching for push_back in the next line:

$ git grep -A 1 -E "for ?\(" *.cxx|grep push_back
Comment 1 Commit Notification 2024-11-02 21:33:21 UTC
Chris Gill committed a patch related to this issue.
It has been pushed to "master":

https://git.libreoffice.org/core/commit/594554e07a952c1aaee9b96d4259bc8418b46ee9

tdf#163738 use insert function instead of for loop

It will be available in 25.2.0.

The patch should be included in the daily builds available at
https://dev-builds.libreoffice.org/daily/ in the next 24-48 hours. More
information about daily builds can be found at:
https://wiki.documentfoundation.org/Testing_Daily_Builds

Affected users are encouraged to test the fix and report feedback.