samedi 18 juin 2022

Convert Forward Iterator to Input Iterator [closed]

I'm trying to get the distance of a partition point from beginning of the container. The below code demonstrate the issue which I'm facing:

#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
    std::vector<std::string> num_names { "one", "two", "six", "ten", "four", 
                    "five", "nine", "three", "seven", "eight"};
    auto partition_checker = [](auto s) { return s.size() == 3; };

    if(std::is_partitioned(num_names.cbegin(), num_names.cend(), partition_checker)) {
        std::cout << "num_names is partitioned." << std::endl;

        // Get the distance of partition point
        auto pos = std::partition_point(num_names.cbegin(), num_names.cend(), partition_checker);
        std::cout << "First string with size > 3: " << *pos
                  << " at " << std::distance(num_names.begin(), pos) + 1 << " from begining" << std::endl;
    } else {
        std::cout << "num_names is not partitioned" << std::endl;
    }
}

For the above code I get a compilation error:

 error: no matching function for call to 'distance(std::vector<std::__cxx11::basic_string<char> >::iterator, __gnu_cxx::__normal_iterator<const std::__cxx11::basic_string<char>*, std::vector<std::__cxx11::basic_string<char> > >&)'
                   << " at " << std::distance(num_names.begin(), pos) + 1 << std::endl;

partition_point algorithm returns a ForwardIterator while distance algorithm expect an InputIterator.

How can I get the distance using the iterator returned by partition_point?

Aucun commentaire:

Enregistrer un commentaire