Use bind1st or bind2nd?
Use bind1st or bind2nd?
vector<int> vwInts;
vector<int> vwIntsB;
for(int i=0; i<10; i++)
vwInts.push_back(i);
transform(vwInts.begin(), vwInts.end(), inserter(vwIntsB, vwIntsB.begin()),
bind1st(plus<int>(), 5)); // method one
transform(vwInts.begin(), vwInts.end(), inserter(vwIntsB, vwIntsB.begin()),
bind2nd(plus<int>(), 5)); // method two
我知道bind1st和bind2nd之间的使用差异,方法一和方法二都为我提供了预期的结果。
在这种情况下(即转换的使用),我可以使用bind1st或bind2nd,这是真的吗?
因为,到目前为止我看到的所有示例都使用方法2。我想知道是否bind1st和bind2nd在上述情况下是相同的
bind1st
绑定plus<int>()
函子的第一个参数,bind2nd
绑定第二个参数。对于plus<int>
,没有任何区别,因为10+20
和20+10
是相同的。
但是如果你对minus<int>
这样做,它会有所不同,因为10-20
和20-10
不一样。你就试试吧。
说明:
int main () {
auto p1 = bind1st(plus<int>(),10);
auto p2 = bind2nd(plus<int>(),10);
cout << p1(20) << endl;
cout << p2(20) << endl;
auto m1 = bind1st(minus<int>(),10);
auto m2 = bind2nd(minus<int>(),10);
cout << m1(20) << endl;
cout << m2(20) << endl;
return 0;
}
输出: 30
30
-10
10
Demo: http://ideone.com/IfSdt
bind1st
绑定函数的第一个参数,而bind2nd
绑定函数的第二个参数。由于这两个参数类型在本例中是相同的,并且operator+
是对称的,因此没有区别。
在这种情况下,它们将分别翻译为5 + a和a + 5,它们被编译为完全相同的
对于您的特殊情况
bind1st()
和
bind2nd()
同样是。
这是因为,plus()
二进制函数运算符看起来像下面的
plus(arg1, arg2)
所以,当你使用bind1st(plus<int>(), 5)
时,对+的调用看起来就像在
plus(5, vwInts)
因此,上面将添加vector的每个值为5
当你使用bind2nd(plus<int>(), 5)
时,对+的调用看起来就像在
plus(vwInts, 5)
so,上面将添加值为5
的vector的每个元素。
因此在你的例子中是相同的
相关文章:
- 瓦尔格林德:数学函数"Conditional jump or move depends on uninitialised value(s)"
- C++核心准则 C35 对于接口类"A base class destructor should be either public and virtual, or protected and nonv
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- Android NDK clang 编译器错误在 Windows 上显示'No such file or directory'
- 模式"allocate memory or use existing data"
- N-API include an .so or dll
- 已解决 - C++ 的崇高文本中的"fatal error: opencv: no such file or directory"
- 将 OR 逻辑运算符从 C++ 转换为 Fortran
- CPP 中的瓦尔格林德和记忆泄漏:"Conditional jump or move depends on uninitialised values"
- 我如何将 OR 与 if 语句一起使用字符串
- 将 if 语句中的字符与 or 进行比较
- Google Or-Tools Glop:如何创建指向 const 对象的指针数组?
- 当初始值设定项是基类名时'initializer does not name a non-static data member or base class'错误
- "No such file or directory" C++标头问题
- 处理 std::enable_if<...中谓词的逻辑"OR">
- C++ 虽然语句不适用于字符串和"or"
- 我在 #include < bits/stdc++h.> 放置时出错"No such file or directory"
- Python Bitwise OR
- 逻辑'double free or corruption (fasttop)'错误
- Use bind1st or bind2nd?