Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to insert an empty into another set?

Tags:

c++

Sorry for naive questions, is it OK to insert an empty set to another set using range function or it is an undefied behavior ?

Test run in https://ideone.com/RNGIFT seems fine, checking the reference saying If the container is empty, the returned iterator will be equal to end().

#include <iostream>
#include <set>
using namespace std;


int main() {
    std::set<string> to_be_inserted;
    std::set<string> res;
    cout << "check everything is fine" << endl;
    res.insert(to_be_inserted.begin(), to_be_inserted.end());
    cout << "how about now ?" << endl;
    return 0;
}
like image 667
sthbuilder Avatar asked Jun 05 '19 01:06

sthbuilder


1 Answers

Yes, most things in C++ relating to iterators will work this way in edge cases such as empty containers so that algorithms relying on the begin and end member functions on containers do not require special code in such circumstances.

Since begin will return the end iterator in the case of the set being empty as you showed, it will effectively make a range of [end, end), which has a length of 0 (as can be checked by functions like std::distance) thus preforming no insertion operations (while also being defined behavior).

This can be seen in practice in a standard library implementation, such as libc++ here where that specific overload of insert walks down the range with a for loop which has an exit condition of the two iterators (first and last) being equal, inserting elements as it goes. In the case of passing an empty range like that to it where the first and last are equal, it'll not even enter the loop.

like image 200
Lemon Drop Avatar answered Nov 16 '22 04:11

Lemon Drop