C++ 每个循环在a中的第二个

C++ 每个循环在a中的第二个,c++,foreach,bind2nd,C++,Foreach,Bind2nd,有一件事我现在还不能理解。 我希望输出中的每个元素都增加1。 显然情况并非如此 仔细观察后,我认为这是因为bind2nd函数的返回值被丢弃了;也就是说,该函数不修改容器的元素 我的想法正确吗?是否有人可以确认或提供未修改容器的正确解释 #include <vector> #include <iostream> #include <algorithm> #include <functional> using namespace std; void p

有一件事我现在还不能理解。 我希望输出中的每个元素都增加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; }
#包括
#包括
#包括
#包括使用名称空间标准;无效打印机(int i){

cout
std::for_每个
都不会修改输入序列

要对容器的每个元素应用更改,请改用:

transform(v1.begin(),v1.end(),v1.begin(),bind2nd(plus(),1));
//~~~~~~~~~~将结果放回输入序列

std::for_每个
都不会修改输入顺序

要对容器的每个元素应用更改,请改用:

transform(v1.begin(),v1.end(),v1.begin(),bind2nd(plus(),1));
//~~~~~~~~~~将结果放回输入序列

操作符()的声明是

i、 e.它不修改输入参数。您需要
std::transform

std::transform(v1.cbegin(), v1.cend() v1.begin(), std::bind2nd(std::plus<int>(), 1));

运算符()的声明是

i、 e.它不修改输入参数。您需要
std::transform

std::transform(v1.cbegin(), v1.cend() v1.begin(), std::bind2nd(std::plus<int>(), 1));
std::transform(v1.cbegin(), v1.cend() v1.begin(), std::bind2nd(std::plus<int>(), 1));
std::for_each(v1.begin(), v1.end(), [] (int& x) { ++x; });
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(v1.begin(), v1.end(), [](int &n){ n += 1; });