私はタスクATMをやっています。これは、STLアルゴリズムを使用して、2つの異なるベクトルで、指定された範囲内のすべてのベクトル要素をほぼ等しいものと比較する必要があります。
この状況ではほぼ同じです:2。
誰かがこの問題の解決策を知っていますか?
比較よりも少ない値が必要な場合は、std :: lexicographical_compareを使用して、ほぼ同等の手段を実装するカスタムコンパレータを使用します。
同等性の比較が必要な場合は、コメントで指摘されているように、std::equalを使用してください。
bool comp(int a, int b) {
return std::abs(a-b) <= 2;
}
int main() {
std::vector<int> v0{2,3,4,5,5,5};
std::vector<int> v1{6,7,8,9,8,7};
std::cout << std::boolalpha;
std::cout << std::equal(v0.begin(), v0.end(), v1.begin(), comp);
}
これは、アルゴリズムの使用方法を示すための簡略化された比較関数です。ベクトルの長さが異なる場合の対処方法を決定する必要があります。
g19fanaticの回答に基づく:
template<class iterator1, class iterator2>
bool almostEqual(iterator1 begin1, iterator1 end1,
iterator2 begin2, iterator2 end2, int tolerance)
{
for(;begin1!=end1; ++begin1, ++begin2) {
if (begin2 == end2)
return false;
if (*begin1 - tolerance > *begin2)
return false;
if (*begin1 + tolerance < *begin2)
return false;
}
if (begin2 != end2)
return false;
return true;
}
template<class container1, class container2>
bool almostEqual(container1 left, container2 right, int tolerance)
{
return almostEqual(left.begin(), left.end(),
right.begin(), right.end(), tolerance);
}
コンパイル/実行の証明:http://ideone.com/y6jBR
標準ライブラリ関数inner_product
は、2つのコンテナを反復処理し、ペアごとにいくつかの操作を実行して、結果を累積します。したがって、これを使用して、各ペアが2以内であるかどうかを比較し、すべての比較が真であることを累積できます。
#include <vector>
#include <iostream>
#include <algorithm>
bool all(bool first, bool second)
{
return first && second;
}
bool within_two(int first, int second)
{
return abs(first - second) <= 2;
}
int main()
{
using std::vector;
using std::inner_product;
using std::boolalpha;
using std::cout;
using std::endl;
vector<int> first = {1, 2, 3, 4, 5};
vector<int> second = {3, 4, 5, 6, 7};
bool almost_equal = inner_product(first.begin(), first.end(),
second.begin(),
true,
all, within_two);
cout << "almost_equal=" << boolalpha << almost_equal << endl;
}
出力:
almost_equal=true
#include "math.h"
#include <vector>
std::vector<int> vec1,vec2;
std::vector<bool> resVec;
void almostEqual(std::vector<int> vec1,std::vector<int> vec2,std::vector<bool>& resVec, int tolerance)
{
resVec.clear();
if (vec1.size() != vec2.size()) {return;}
std::vector<int>::iterator it;
int i = 0;
for (it = vec1.begin(); it != vec1.end(); ++it)
{
if (abs(*it - vec2[i++]) <= abs(tolerance))
{
resVec.push_back(true);
} else {
resVec.push_back(false);
}
}
}
私たちが持っているごくわずかなものに基づいて、これは私がすることです....