Search code examples
c++templatesiterator

Template funtion returning an iterator


i would like to make a reusable function that returns an iterator to make it easy to find the middle point of a container and need some help

fixed;

template <typename T> std::vector<int>::const_iterator middlepoint(std::vector<T> const& arr){
    auto temp = arr.begin() + arr.size() /  2;
    return temp;
}

the caller:

auto middle_point = middlepoint(arr.begin(), arr.end());

fixed:

template <typename T>  int middlepoint(std::vector<T> const& arr){
    std::cout << "size: " << arr.size() << endl;
    auto middle_point = arr.begin() + (arr.size()/  2);
    int middle_element = middle_point - arr.begin();
    return middle_element;
}

caller:

int middle_element = middlepoint(arr);

error:

ambiguous

ambiguous, means you declared 2 functions with the same name, but different parameters.


Solution

  • It looks like you're taking the beginning and end iterators and dividing them by 2 to get the middle position. Iterators don't have a valid expression for division, so what you're doing won't work.

    The best way I can think to implement this would be to use the size of the container divided by 2 as an offset from the beginning or the end (whichever works best for you). This way you wouldn't need to pass both iterators to the function.

    auto mid = it.begin() + (arr.size() / 2);  original
    return mid; 
    

    If you can't get the size of the container using the .size() method (which you should be able to because you have access to the iterators), you can create a helper function that cycles through and counts. That shouldn't be needed for your case though because you're using a vector.