我知道 C++ 有 lambdas 和 std::bind1st、std::bind2nd 和 std::bind 已被弃用。
但是,从 C++ 的基础开始,我们可以更好地理解新特性。
所以,我从这个非常简单的代码开始,使用一个int 数组:
第一个例子:使用std::bind2nd
int array1[] = { 10, 20, 30, 40, 50, 60, 40 };
int c1, c2, c3;
c1 = count_if(array1, array1 + 7, bind2nd(greater<int>(), 40));
c2 = count_if(array1, array1 + 7, bind2nd(less<int>(), 40));
c3 = count_if(array1, array1 + 7, bind2nd(equal_to<int>(), 40));
cout << "There are " << c1 << " elements that are greater than 40." << endl;
cout << "There are " << c2 << " elements that are lesser than 40." << endl;
cout << "There are " << c3 << " elements that are equal to 40." << endl;
第二个例子:使用std::bind
greater<int> big;
less<int> small;
equal_to<int> equal;
c1 = count_if(array1, array1 + 7, bind(big, _1, 40));
c2 = count_if(array1, array1 + 7, bind(small, _1, 40));
c3 = count_if(array1, array1 + 7, bind(equal, _1, 40));
cout << "There are " << c1 << " elements that are greater than 40." << endl;
cout << "There are " << c2 << " elements that are lesser than 40." << endl;
cout << "There are " << c3 << " elements that are equal to 40." << endl;
在这两种情况下,输出都是:
There are 2 elements that are greater than 40.
There are 3 elements that are lesser than 40.
There are 2 elements that are equal to 40.
如何对如下所示的双向数组
执行相同操作:(我想对第二个坐标进行相同的操作)
int array2[7][2] = { { 1, 10 }, { 2, 20 }, { 3, 30 },
{ 4, 40 }, { 5, 50 }, { 6, 60 }, { 4, 40 } };
并使用这样的结构数组:
struct st
{
char c;
int i;
};
st array3[] = { { 'a', 10 }, { 'b', 20 }, { 'c', 30 },
{ 'd', 40 }, { 'e', 50 }, { 'f', 60 }, { 'd', 40 } };
在这种情况下,我想对结构数组中的字段“int”执行相同的操作。
谁能帮我?
谢谢