C++将向量传递给函数模板

Mar*_*edy 0 c++ vector

我想检查两个向量是否有任何共同的元素.这个语法出了什么问题?

// Check whether the current list and the input l2 share any nodes or not 
bool shared(const VectorList< NODETYPE > &l2); 

template< typename NODETYPE > //SHARED
bool VectorList< NODETYPE>::shared(const VectorList< NODETYPE > &l2)
{

    for(int i = 0; i < (int)vList.size(); i++)
      {
        for (int j = i; j < (int)l2.size() ; j++)
            {
                    if (vList[i] == l2[j])
                    {
                        return(1);
                    }
            }
      }

    return(0);

}
Run Code Online (Sandbox Code Playgroud)

seh*_*ehe 5

假设您已将VectorList实现为(类似于)标准容器,我会考虑编写(请参阅参考资料find_first_of):

template<typename T>
bool VectorList<T>::shared(const VectorList<T> &l2) const // <-- NOTE added const
{
    return end() != std::find_first_of(
        begin(), end(), 
        l2.begin(), l2.end());
}
Run Code Online (Sandbox Code Playgroud)

请注意,(最坏情况)运行时复杂性仍然是二次的(或O(n*m))