C++ 容器实用方法:indexOf和contains

template<typename Container, typename Value>
inline int indexOf(const Container &container, Value value)
{
    auto it = std::find(container.begin(), container.end(), value);
    return it == container.end() ? -1 : std::distance(container.begin(), it);
}

template<typename Container, typename Value>
inline bool contains(const Container &container, Value value)
{
    return std::find(container.begin(),
                     container.end(),
                     value) != container.end();
}

template<typename Container, typename Pred>
inline bool contains_where(const Container &container, Pred pred)
{
    return std::find_if(container.begin(),
                        container.end(),
                        pred) != container.end();
}

template<typename Value>
void move(std::vector<Value> &container, size_t from, size_t to)
{
    const auto b = container.begin();
    if (from < to)
        std::rotate(b + from, b + from + 1, b + to + 1);
    else
        std::rotate(b + to, b + from, b + from + 1);
}

陕ICP备2025078817号-1 陕公网安备61011202001108号