简体   繁体   中英

Using vector iterator in function prototype

I want to do the following:

vector<int> vec;    
auto iter = vec.begin();

Now I want a function which takes iter as an input and returns iter.

____ func(___ & iter)

where ___ is to be filled in. What should ___ be?

std::vector<int>::begin() returns an instance of type std::vector<int>::iterator , or std::vector<int>::const_iterator if the callee is marked const .

In your example, decltype(iter) will be std::vector<int>::iterator , so just declare the function like so:

std::vector<int>::iterator
func (std::vector<int>::iterator iter);

Note that STL iterators are designed to be passed by value, so I got rid of the reference in the function signature.

That actually depends on the iterator type you need. In general it will be vector<int>::iterator . begin() is defined as:

iterator begin() noexcept;
const_iterator begin() const noexcept;

A bit silly example, but here is some examples of using templates and decltype to deduce type of iterators:

#include <vector>
#include <iostream>

using std::vector;
using std::cout;

template <class T> void double_vals(T vbeg, T vend)
{
    for (; vbeg != vend; ++vbeg)
        *vbeg *= 2;
}

template <class T, class T2> auto find_val(T vbeg, T vend, T2 val) -> decltype(vbeg)
{
    for (; vbeg != vend; ++vbeg)
        if (*vbeg == val) return vbeg;

    return vbeg;
}

int main()
{
    vector<int> vec = {10, 20, 30};

    auto it1 = vec.begin();
    auto it2 = vec.end();

    double_vals(it1, it2);
    auto it3 = find_val(it1, it2, 20);
    if (it3 != vec.end())
        cout << "Found value!\n";

    for (auto i : vec)
    {
        cout << i << '\n';
    }

    return 0;
}

// Note that you could avoid using decltype() here by doing 
template <class T, class T2> T find_val(T vbeg, T vend, T2 val)
{
    for (; vbeg != vend; ++vbeg)
        if (*vbeg == val) return vbeg;

    return vbeg;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM