std :: bind2nd和std :: bind与二维数组和结构数组

时间:2016-11-10 10:00:51

标签: c++ arrays struct bind bind2nd

我知道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'进行相同的操作。

任何人都可以帮助我吗?

谢谢

1 个答案:

答案 0 :(得分:2)

bind1stbind2nd和他们的兄弟在C ++ 11中被弃用,并且在C ++ 17中被彻底删除。以防你不知道这一点。

使用bind,解决方案相当简单,您可以使用bind表达式可组合的事实,并且可以使用bind来提取数据成员({{1}为简洁省略):

placeholders

使用auto gr = count_if(array3, array3 + 7, bind(greater<>{}, bind(&st::i, _1), 40)); auto ls = count_if(array3, array3 + 7, bind(less<>{}, bind(&st::i, _1), 40)); auto eq = count_if(array3, array3 + 7, bind(equal_to<>{}, bind(&st::i, _1), 40)); 并不容易。您需要声明一个具有多个typedef的函数对象(不能使用函数)。您可以使用bind2nd来简化此操作:

binary_function

然后你可以打电话

struct my_greater : binary_function<st, int, bool>
{
    bool operator()(st const& l, int r) const {
        return greater<>{}(l.i, r);
    }
};

在C ++ 11中你可以使用lambdas:

auto old = count_if(array3, array3 + 7, bind2nd(my_greater{}, 40));

demo of all

如果你有C ++ 11或更新版本,那么使用lambdas几乎总是更好的选择。这不仅仅是一个“良好的默认”,你必须真正扭曲auto XI = count_if(array3, array3 + 7, [](st const& l){ return l.i > 40}); 的情况才能成为更好的解决方案。