skip to Main Content

I am trying to use std::partition to partition a vector into multiple part based on whitespace.

void solution2()
{
    std::vector<string> v{ "10","20","","30","40","50","","60","70" };
    auto i = begin(v);
    while (i != end(v)-1)
    {
        auto it = std::partition(i, end(v)-1, [](auto empty) {return empty != ""; });
        std::copy(i, it, std::ostream_iterator<int>(std::cout, " "));
        i = it;
    }
}

For example in the above code I want to partition it into multiple and condition to partition is whitespace ""

so the vector v should partition to 3 groups

  1. "10" "20"
  2. "30" "40" "50"
  3. "60" "70"

The problem I am facing is in line

auto it = std::partition(begin(v), end(v)-1, [](string empty) {return empty != ""; });

Error

Severity Code Description Project File Line Suppression State
Error C2679 binary '=': no operator found which takes a right-hand operand of type 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>' (or there is no acceptable conversion) C:sourcereposoutbuildx64-debugsample  C:Program FilesMicrosoft Visual Studio2022CommunityVCToolsMSVC14.34.31933includexutility  3919    

Any suggestion what can be changed to fix the error.
Any other efficient way to do the same using std::range or std::view

2

Answers


  1. Using std::find to get the next empty string would be more appropriate here.

    auto i = begin(v), e = end(v);
    while (i != e) {
        auto it = std::find(i, e, "");
        std::copy(i, it, std::ostream_iterator<std::string>(std::cout, " "));
        std::cout << 'n';
        if (it == e) break;
        i = it + 1;
    }
    
    Login or Signup to reply.
  2. With C++20, this can be done trivially with ranges::split_view:

    std::vector<std::string> v{ "10","20","","30","40","50","","60","70" };
    
    for(auto part : v | std::views::split(""))
    {
        for(auto num : part) std::cout << num << ',';
        std::cout << 'n';
    }
    

    Demo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search