The garbage value is printed in std :: set

advertisements

I wrote the simple program below to find out the single character that is different between the two input strings s and t:

class Solution {
public:
    char findTheDifference(string s, string t) {
        std::set<char> set1;
        std::set<char> set2;
        int i=0;

        while(s[i]!='\0') {
            set1.insert(s[i]);
            i++;
        }

        i=0;
        while(t[i]!='\0') {
            set2.insert(t[i]);
            i++;
        }

        std::set<char>::iterator it;
        for(it=set1.begin(); it!=set1.end(); it++)
            cout<<*it;
        cout<<"\n";
        for(it=set2.begin(); it!=set2.end(); it++)
            cout<<*it;
        cout<<"\n";

        std::set<char> v;
        std::set_difference(set1.begin(), set1.end(), set2.begin(), set2.end(), std::inserter(v, v.end()));
        cout<<*(v.begin());

        return *(v.begin());
    }
};

While I have apparently done everything alright, I get the output as below:

abcd
abcde
\x00

And the char value returned by the function is \x00. My question is, from where is this garbage value (\x00) getting printed and returned?

Thank you for your help!


Your program invokes UB because all elements from set2 are present in set1 and there are no elements in v after the std::set_difference call.

From the cpp.reference std::set_difference page:

template< class InputIt1, class InputIt2, class OutputIt >
OutputIt set_difference(InputIt1 first1, InputIt1 last1,
                        InputIt2 first2, InputIt2 last2,
                        OutputIt d_first);

Copies the elements from the sorted range [first1, last1) which are not found in the sorted range [first2, last2) to the range beginning at d_first.


There are some other tips:

1) It is better to make the arguments const references.

2) You can construct sets from strings directly using range constructor.

3) You might print sets without cycles using copy and ostream_iterators.