有件事我现在还不能想清楚。我期待的是一个输出,其中每个元素的增量为1,显然不是这样。
仔细看后,我认为这是因为bind2nd函数的返回值被丢弃了;也就是说,函数不会修改容器的元素。
我的想法正确吗?有人能确认或提供一个正确的解释,因为容器没有被修改?
#include <vector>
#include <iostream>
#include <algorithm>
#include <functional> using namespace std; void printer(int i) {
cout << i << ", "; } int main() {
int mynumbers[] = { 8, 9, 7, 6, 4, 1 };
vector<int> v1(mynumbers, mynumbers + 6);
for_each(v1.begin(), v1.end(), bind2nd(plus<int>(), 1));//LINE I
for_each(v1.rbegin(), v1.rend(), printer);//LINE II
return 0; }发布于 2016-03-29 13:49:04
for_each(v1.begin(), v1.end(), bind2nd(plus<int>(), 1));相当于:
for (auto first = v1.begin(); first != last; ++first) {
plus<int>()(*first, 1); // i.e. *first + 1;
}正如你所看到的,它不会改变任何事情。
您可以使用函子来用std::for_each更改值。
std::for_each(v1.begin(), v1.end(), [](int &n){ n += 1; });发布于 2016-03-29 13:47:55
operator() of template std::plus的声明是
T operator()(const T& lhs, const T& rhs) const;也就是说,它不修改输入参数。你需要std::transform
std::transform(v1.cbegin(), v1.cend() v1.begin(), std::bind2nd(std::plus<int>(), 1));或者您可以使用lambda来修改它的输入参数:
std::for_each(v1.begin(), v1.end(), [] (int& x) { ++x; });发布于 2016-03-29 13:46:25
std::for_each不修改输入序列。
若要对容器的每个元素应用更改,请使用std::transform:
transform(v1.begin(), v1.end(), v1.begin(), bind2nd(plus<int>(), 1));
// ~~~~~~~~~^ puts the results back into the input sequencehttps://stackoverflow.com/questions/36286070
复制相似问题