回復 3# may - for (auto it : poly) {
- if (it.second != 0) {
- terms.push_back({it.second, it.first.first, it.first.second});
- }
- }
複製代碼 -------------------------------------
背景說明:
poly 是一個 map<pair<int, int>, int>:
每一項的 key 是 pair<int, int>(代表 x 的指數 和 y 的指數)
每一項的 value 是 int(代表這一項的 係數)
例如:
poly[{2, 1}] = 3; // 表示 3x^2y^1
poly[{1, 3}] = -4; // 表示 -4x^1y^3
--------------------------------------
for 迴圈解釋:
for (auto it : poly)
這行是 C++ 的範圍式 for 迴圈(range-based for loop),會把 poly map 中的每一筆資料逐一取出:
it 的型別其實是 pair<pair<int, int>, int>
因為:
key 是 pair<int, int>(代表指數:x, y)
value 是 int(代表係數)
-----------------------------
條件篩選:if (it.second != 0)
it.second 是這一項的「係數」
若係數是 0,就不處理它(因為 0 不需要顯示在多項式中)
若不是 0,就加入 terms 向量中
-------------------------
重點:加入 terms 向量
terms.push_back({it.second, it.first.first, it.first.second});
這句的意思是把這項轉成 Term 結構並加入 terms 向量中。
it.second // 係數 coef
it.first.first // x 的指數 xExp
it.first.second // y 的指數 yExp
也就是:
Term t;
t.coef = it.second;
t.xExp = it.first.first;
t.yExp = it.first.second;
terms.push_back(t);
整段功能總結:
這段程式碼的功能是:
把多項式中「係數不為 0」的項目轉換成 Term 結構,並儲存到 terms 向量中,準備後續排序與輸出。
---------------------------
舉個例子(假設 poly 裡面資料是這樣):
poly = {
{{2, 1}, 3},
{{1, 3}, -4},
{{0, 0}, 0} // 這項會被略過
};
則這段程式執行完後:
terms = {
{3, 2, 1}, // 3x^2y^1
{-4, 1, 3} // -4x^1y^3
}; |