掲示板システム
ホーム
アクセス解析
カテゴリ
ログアウト
配列の中で一番近い値を求める。 (ID:66695)
名前
ホームページ(ブログ、Twitterなど)のURL (省略可)
本文
> 目標値との差が最も近い"ふたつ"を覚えておけばよさそう。 あー、ダメダメ。 ↓とりあえずこんなところで。 #include <iostream> #include <algorithm> #include <iterator> #include <functional> template<typename T> struct norm : std::binary_function<T,T,T> { T operator()(T x, T y) const { return std::max(x-y,y-x); } }; template<typename T> struct norm_less : std::binary_function<T,T,bool> { T value_; norm_less(T v) : value_(v) {} bool operator()(T x, T y) const { norm<T> f; return f(x,value_) < f(y,value_); } }; int main(){ const int N = 8; int data[N] = { 1, 2, 3, 3, 5, 5, 6, 7 }; int target = 4; norm<int> n; int min_norm = n(*std::min_element(data, data+N, norm_less<int>(target)),target); for ( int i = 0; i < N; ++i ) { if ( n(target,data[i]) == min_norm ) std::cout << data[i] << ' '; } }
←解決時は質問者本人がここをチェックしてください。
更新する
戻る
掲示板システム
Copyright 2021 Takeshi Okamoto All Rights Reserved.