以下のC++のプログラム文があります。
#include <iostream>
#include <vector>
using namespace std;
class KiwiJuiceEasy
{
public:
vector <int> thePouring(vector <int> capacities, vector <int> bottles, vector <int> fromId, vector <int> toId)
{
for(int i=0; i<capacities.size(); i++ ){
if( bottles[fromId[i]] + bottles[toId[i]] <= capacities[toId[i]] ){
bottles[toId[i]] += bottles[fromId[i]];
bottles[fromId[i]] = 0;
}else if( bottles[fromId[i]] + bottles[toId[i]] > capacities[toId[i]] ){
cout << bottles[fromId[i]] << endl; //5が表示される
bottles[fromId[i]] = bottles[fromId[i]] - ( capacities[toId[i]] - bottles[toId[i]] );
cout << capacities[toId[i]] - bottles[toId[i]] << endl; //2が表示される
cout << bottles[fromId[i]] << endl; //3が表示される
bottles[toId[i]] = capacities[toId[i]];
}
}
return bottles;
}
};
{10, 10}
{5, 8}
{0}
{1}
その結果
{0, 10}
が返されます。本当は
{3, 10 }
が返されてほしいのです。
coutで途中の値を出力してみると上から順番に
5
2
3
が出力されます。上記のプログラム文のコメント部分にも書いています。
cout << bottles[fromId] << endl; //3が表示される
↑でbottles[fromId] に3が代入されていることが分かるかと思いますが、return文で帰ってくる
配列は{3, 10 }ではなく{0, 10 }です。どこかでbottles[fromId]の値が0になっているようなので
すがどこで0になっているのかわかりません。
どなたかわかる方は教えてもらえないでしょうか?