c++set

Printing out a set with one element shows nothing


The problem came as I was trying to figure out why the solution I wrote to a leet code problem was not working.

#include <algorithm>
#include <iostream>
#include <set>

using namespace std;

int main() {

    string s = "au";     

    std::set < char > mems;
    int ans = 0;
    for (int i = 0; i <= s.length(); i++) {

        for (int j = i; j <= s.length(); j++) {
            if (mems.count(s[j]) == 1) {
                if (j - i > ans) { ans = j - i; }
                
                i = j - 1;
                j = s.length();

                mems.clear();
            }
            else {
                mems.insert(s[j]);
            }
        }
    }

    if (s.length() == mems.size()) { ans = s.length(); }

    for (auto item : mems)
        std::cout << item << endl;

    cout<<mems.size() << "";
}

The following code suggests that mems is of size 1, but at the same time, when I try to print out the items, it shows nothing.

How is that possible?

I checked online for minimum size of a set and I found it to be 0, so the issue is not related to that either.

Intended behaviour should be mems.size() == 2.


Solution

  • Your for loops are iterating from 0,1,2 (2 included), which you probably did not mean to do. Replace your <= check to strict < to avoid this. On the other hand, what happens here, is that you're accessing s string of size 2 at position 2, which returns a null character (0 or '\0') according to the standard.

    Do std::strings end in '\0' when initialized with a string literal?

    So at the end mems contains a single 0 character, and that does not do anything when you print it, it's just like printing an empty string. Reason for returning a null string at index 2 here is probably related to c strings, which are always terminated with a null, to make it easier to print them. for example:

    const char* str = "foo";
    printf("%s\n", str);
    

    This prints "foo", but printf does not really know the size of str, which is just a pointer, but when it encounters the 0, it stops. As an experiment you can replace str with

    const char* str = "f\0oo"; and then only the letter f is printed