distance函数出错

在求解“最邻近点对”问题的时候需要求两点间距离,于是自己实现了一个函数:

int distance(const Point &p1,const Point &p2);

但是调用总是会出错,后来发现原因在于系统头文件xutility.h中有这么一个函数

template<class _InIt> inline
    typename iterator_traits<_InIt>::difference_type
        distance(_InIt _First, _InIt _Last)
    {   // return distance between iterators
    typename iterator_traits<_InIt>::difference_type _Off = 0;
    _Distance2(_First, _Last, _Off, _Iter_cat(_First));
    return (_Off);
    }

这是一个内联函数,会把程序中的自定义的distance替换成这个函数,该函数作用在于求容器里相邻元素的差(类似于等差数列中的公差),下面给段例子

template<class InputIterator>
  typename iterator_traits<InputIterator>::difference_type
    distance (InputIterator first, InputIterator last);
例如:

// distance example
#include <iostream>
#include <iterator>
#include <list>
using namespace std;

int main () {
  list<int> mylist;
  for (int i=0; i<10; i++) mylist.push_back (i*10);

  list<int>::iterator first = mylist.begin();
  list<int>::iterator last = mylist.end();

  cout << "The distance is: " << distance(first,last) << endl;

  return 0;
}

结果:10

因此最简单的解决方案是换一个函数名,比如换成

int dist(const Point &p1,const Point &p2);

虽然很蛋疼,也就只能这样了

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
function crowding_distance = calculate_crowding_distance(objectives, ndx) % objectives为目标函数值矩阵 % ndx为每个个体所属的帕累托前沿编号 crowding_distance = zeros(1, size(objectives, 1)); nFronts = length(unique(ndx)); for iFront = 1:nFronts frontIndices = find(ndx == iFront); nPoints = length(frontIndices); if nPoints == 1 % 如果只有一个个体,则其拥挤度为inf crowding_distance(frontIndices) = inf; else for iObjective = 1:size(objectives, 2) % 对第iObjective个目标函数进行排序,得到该维度上的排序索引 [~, sortedIndices] = sort(objectives(frontIndices, iObjective)); % 对该维度上排名最小的个体和排名最大的个体赋予最大拥挤度 crowding_distance(frontIndices(sortedIndices(1))) = inf; crowding_distance(frontIndices(sortedIndices(end))) = inf; % 计算其它个体的拥挤度 for iPoint = 2:(nPoints-1) range = objectives(frontIndices(sortedIndices(end))) - objectives(frontIndices(sortedIndices(1))); if range == 0 crowding_distance(frontIndices(sortedIndices(iPoint))) = inf; else crowding_distance(frontIndices(sortedIndices(iPoint))) = crowding_distance(frontIndices(sortedIndices(iPoint))) ... + (objectives(frontIndices(sortedIndices(iPoint+1)), iObjective) - objectives(frontIndices(sortedIndices(iPoint-1)), iObjective)) / range; end end end end end end这段代码报错:Index exceeds the number of array elements. Index must not exceed 0. 出错 calculate_crowding_distance (第 19 行) crowding_distance(frontIndices(sortedIndices(1))) = inf;该如何修改
05-24

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值