Home > OS >  std::partition to partition a a vector of string
std::partition to partition a a vector of string

Time:12-24

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:\source\repos\out\build\x64-debug\sample  C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.34.31933\include\xutility  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

CodePudding user response:

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

CodePudding user response:

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;
}
  • Related