我正在开发一个包含类和函数模板的项目,我写了这些模板。 在编译时我遇到了这个错误:
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;
}
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和类类型)。 这个错误给我的信息量不大。 任何人都可以找到问题所在的线索吗?
答案 0 :(得分:2)
如果你真的有这个代码:
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)如果您在原始问题中发布了错误代码,那么您很快就会得到答案。
答案 1 :(得分:0)
表达式Distance(all_items[i], all_items[j] ) == distances[d]
可能会有一些令人惊讶的效果......您永远不应该将浮点数(float
或double
)与等式或不等式进行比较。
我建议您阅读IEEE 754标准并使用Google进行双重等同比较以获取更多信息。
此外,比较和评论似乎没有相关,你比较平等,但评论声称:
//every item which is closer then the "farest" is added to the cluster
也许你的意思是<=
?