简体   繁体   中英

Return pointer or iterator

I'm rewriting a free function which takes a reference to a std::vector. Based on a given criteria, it then returns the index of the item in the vector or -1 if its not found. I would prefer if it returned a pointer to the item or a std::vector<>::iterator?

What should I consider when deciding what to return?

Return an iterator, and yourVector.end() if the element is not found.

This is what the standard library uses.

Example:

auto my_function(std::vector<int>& v) -> decltype(v.begin())
{
    // Do the search
    ...
    else return v.end();
}

Better is if you can do

template <typename I>
I my_function(I begin, I end)
{
     // Do the search
     ...
     else return end;
}

template <typename C>
auto my_function(C&& c) -> decltype(std::begin(c))
{
    return my_function(std::begin(c), std::end(c));
}

because it will work for any container (including arrays):

double my_array[] = { 1, 2, 42, -7 };
auto p = my_function(my_array);

只需使用惯用的方式返回一个插入器,如果找不到该项目,则返回.end()

You should definitely return an std::vector<>::iterator , and here is why:

When you treat a data structure, you should always give out the correct "accession objects". If you use an actual array ( int[] ), you can give out pointers. But for std::vector<>, the correct "accession objects" are iterators and you should never access elements in the vector by pointers.

You can return your_vec.end() to signal that the element was not found.

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