#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void myfunction(int i)
{
cout<<" "<<i;
};
void multiply(int a)
{
a*2;
}
int main()
{
int t[]={10,5,9,6,2,4,7,8,3,1};
vector<int> v1(t,t+10);
for_each(v1.begin(),v1.end(),multiply);
iter_swap(v1.begin(), t+9);
for_each(v1.begin(),v1.end(),myfunction);
return 0;
}
こんにちは、私は実際にこのコードについて質問があります。
これを実行すると、結果が1 5 9 6 2 4 7 8 3 1であることがわかりiter_swap(v1.begin(), t+9);
、途中でステートメントを割り当てたにもかかわらず、最後の要素がまだ1である理由がわかりません。
が与えられたiter_swap(v1.begin(), t+9);
場合std::vector
v1
、配列の1番目の要素と10番目の要素を交換しますt
。v1
とt
は2つの独立したオブジェクトです。そして、あなたはの要素をプリントアウトしているv1
ようにfor_each(v1.begin(),v1.end(),myfunction);
、しかし第10要素はv1
変更されません。
あなたが望むかもしれません
iter_swap(v1.begin(), v1.end()-1); // swap the 1st and 10th element of v1
for_each(v1.begin(),v1.end(),myfunction);
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加