Ad
  • Custom User Avatar

    It is faster , but less space efficient .

    The thing is - you cannot determine even an approximate size of the resulting vector beforehand .

    Sure , the input {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16} requires the output vector to have a size equal to 16 elements .

    And input {1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8} requires the output vector to have a size equal to 8 elements .

    While input {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1} requires the output vector to have a size equal to just only 1 element .

    Favoring speed over space is generally a good idea , but i think it is also worth knowing when "reserve" can be used with/without drawbacks .

  • Custom User Avatar

    :-) note the fmt::join up there is IMHO canonical in the 21rst century..
    Know your STL and get rid of those for loops.

  • Custom User Avatar

    YEEEAAHHHHHH this one is excellent!!!
    For F... Sake YOU SURE KNOW YOUR STL!!

    As for me... I'm tired of typing "fmt/ranges" as well as "rangeV3/anyalgo" ... when using format or ranges or views... Keep to C++17
    We need a C++20 compilant compiler there !!

  • Custom User Avatar

    Finally, the universal C++ solution after 16 months of the original kumite. (15 months since my C++ translation.)

  • Default User Avatar

    When the algorithm does not need the i index value, I prefer to use range based for loop, it makes the code more readable.

  • Custom User Avatar
  • Custom User Avatar
  • Custom User Avatar

    The big thing I had in mind was to do an else-if on the second conditional since it will only be valid if the first one fails. Also, prefix increment/decrement is a tiny bit more efficient.

  • Custom User Avatar

    Ideally, you would want to minimize memory allocations and temporary strings. The previous version would make a new string and do a string concatenation on each loop iteration. There's definitely extra work there that could be removed.

    This version reserves memory ahead of time so there's never more than one memory allocation as the string grows. It also eliminates temporary string objects. Each call to push_back() is only copying a char. Also note the single quotes on the second push_back(). That indicates it's a single char ' ' instead of char array { ' ', '\0' }.

    I also added a reference for the input parameter. You don't need a deep copy of the input and it's generally inadvisable to pass in containers by value since a deep copy could be expensive.

  • Custom User Avatar

    This comment is hidden because it contains spoiler information about the solution

  • Custom User Avatar

    You could also call the member function "reserve" on the result vector before doing the unique_copy algorithm. This would mean one heap allocation instead of an unknown number of allocations as the vector grows in size.