std::equal_to允許將相等比較用作函數,這意味著可以將其作為參數傳遞給模板和函數。對於相等運算符==,這是不可能的,因為運算符不能作為參數傳遞。
頭文件:
#include <functional.h>
模板類別:
template struct equal_to:binary_function { // Declaration of the equal operation bool operator() (const T& x, const T& y) const { return x==y; } // Type of first parameter typedef T first_argument_type; // Type of second parameter typedef T second_argument_type; // The result is returned // as bool type typedef bool result_type; }
用法:
std::equal_to <int> ()
參數:該函數接受參數T的類型作為參數,以供函數調用進行比較。
返回類型:它根據條件返回布爾值(讓a和b為2個元素):
- 真正:如果a等於b。
- 假:如果a不等於b。
下麵是C++中std::equal_to的圖示:
程序1:
// C++ code to illustrate std::equal_to
#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>
using namespace std;
// Driver Code
int main()
{
// Intialise vectors
vector<int> v1 = { 50, 55, 60,
65, 70 };
vector<int> v2 = { 50, 55, 85,
65, 70 };
// Declaring pointer of pairs
pair<vector<int>::iterator,
vector<int>::iterator>
pairs1;
// Use mismatch() function to
// search first mismatch between
// v1 and v2
pairs1 = mismatch(v1.begin(), v1.end(),
v2.begin(),
equal_to<int>());
// Print the mismatch pair
cout << "The 1st mismatch element"
<< " of 1st container:";
cout << *pairs1.first << endl;
cout << "The 1st mismatch element"
<< " of 2nd container:";
cout << *pairs1.second << endl;
return 0;
}
輸出:
The 1st mismatch element of 1st container:60 The 1st mismatch element of 2nd container:85
程序2:
// C++ program to illustrate std::equals_to
#include <algorithm>
#include <functional>
#include <iostream>
using namespace std;
// Template
template <typename A, typename B,
typename U = std::equal_to<int> >
// Function to check if a = b or not
bool f(A a, B b, U u = U())
{
return u(a, b);
}
// Driver Code
int main()
{
int X = 1, Y = 2;
// If X is equals to Y or not
cout << std::boolalpha;
cout << f(X, Y) << '\n';
X = -1, Y = -1;
// If X is equals to Y or not
cout << f(X, Y) << '\n';
return 0;
}
輸出:
false true
參考: http://www.cplusplus.com/reference/functional/equal_to/
相關用法
- C語言 strtok()、strtok_r()用法及代碼示例
- C語言 memset()用法及代碼示例
- C++ std::mismatch()用法及代碼示例
- C++ wcscpy()用法及代碼示例
- C++ wcscmp()用法及代碼示例
- C++ set_symmetric_difference用法及代碼示例
- C++ ratio_equal()用法及代碼示例
- C++ quick_exit()用法及代碼示例
- C++ multiset lower_bound()用法及代碼示例
- C++ multiset upper_bound()用法及代碼示例
- C++ multiset max_size()用法及代碼示例
- C++ forward_list max_size()用法及代碼示例
- C++ std::allocator()用法及代碼示例
- C++ array data()用法及代碼示例
- C++ multiset size()用法及代碼示例
- C++ ratio_not_equal()用法及代碼示例
- C++ std::bit_or用法及代碼示例
注:本文由純淨天空篩選整理自nishanthandge大神的英文原創作品 std::equal_to in C++ with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。