gpt4 book ai didi

C++:函数模板的实例化有问题

转载 作者:行者123 更新时间:2023-11-28 03:35:04 25 4
gpt4 key购买 nike

我正在开发一个包含我编写的类和函数模板的项目。编译时出现此错误:

SNN.h In function `void KNN(const std::vector<T, std::allocator<_CharT> >&, std::vector<Cluster<T, K>, std::allocator<Cluster<T, K> > >&) [with T = int, unsigned int K = 5u]':

之后出现此错误(我认为它们已连接):

1)instantiated from `void ClusteringExample() [with T = int]'
2)instantiated from here:ClusteringExample<int>();
3)SNN.h [Warning] comparing floating point with == or != is unsafe
**4) conversion from `<unknown type>' to non-scalar type `__gnu_cxx::__normal_iterator<const Product*, std::vector<Product, std::allocator<Product> > >' requested**

当 ClusteringExampke 是 func 模板时。这是它的实现:

template <typename T>
void ClusteringExample()
{
std::vector<T> T_input;
std::vector<Cluster<T,cluster_size> > clusters_T;
FillVector( T_input, count_per_line );
SNN( T_input, clusters_T);
for (typename std::vector<Cluster<T,cluster_size> >::size_type i=0;
i<clusters_T.size(); i++ )
{
clusters_T[i].Print();
std::cout << std::endl;
}
std::cout << "===="<< std::endl;
}

KNN代码:**

void  KNN( const std::vector<T>& all_items, std::vector<Cluster<T,K> >& result )
{
result.clear();
if ( K > all_items.size() ) return; //we cannot create clusters bigger than the number of all items
//for each item in all_items we will create a cluster
for (typename std::vector<T>::size_type i=0; i < all_items.size(); i++ )
{
//this vector will save distances to the item i
std::vector<double> distances;
//passing over all items and calculating distance to the item i
for (typename std::vector<T>::size_type j=0; j < all_items.size(); j++ )
{
distances.push_back( Distance(all_items[i], all_items[j] ));
}
//creating new cluster
Cluster<T,K> new_cluster;
//we are looking for K nearest distances
std::sort( distances.begin(), distances.end() );
for ( std::vector<double>::size_type d=0; d<K; d++ )
{
for (typename std::vector<T>::size_type j=0; j < all_items.size(); j++ )
{
if (Distance(all_items[i], all_items[j] ) == distances[d] ) //every item which is closer then the "farest" is added to the cluster
{
new_cluster.Add( all_items[j] ); //we don't use the return value of Add in this implementation, but you need to support it
}
}
}
result.push_back( new_cluster );

**不得不说:它发生在我试图实例化的所有类型(int、double 和类类型)上。这个错误对我来说没有太多信息。任何人都知道问题出在哪里?

最佳答案

如果你真的有这段代码:

template<typename T, size_t K> void Cluster<T,K>::Print() const {
for(typename vector<T>::const_iterator iter=_cluster_vec.begin;iter!=_cluster_vec.end();++iter) {
cout<<(*iter)<<" ";
}
}

然后 (a) 您需要将 begin 更改为 begin() 并且 (b) 如果您将代码与你原来的问题有误。

关于C++:函数模板的实例化有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11170075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com