C++:競賽程式設計中縮短程式碼的方法?


在本部分中,我們將看到一些適合競賽程式設計的程式碼縮減策略示例。假設我們必須編寫大量程式碼。在該程式碼中,我們可以遵循一些策略來使其更短。

我們可以更改型別名稱使其更短。請檢查以獲取該思路的程式碼

示例程式碼

#include <iostream>
using namespace std;
int main() {
   long long x = 10;
   long long y = 50;
   cout << x << ", " << y;
}

輸出

10, 50

示例程式碼(使用 typedef 縮短)

#include <iostream>
using namespace std;
typedef long long ll;
int main() {
   ll x = 10;
   ll y = 50;
   cout << x << ", " << y;
}

輸出

10, 50

如此一來,我們無需一次次寫下“long long”,而可以使用“ll”。

使用 typedef 的另一個示例如下。編寫模板或 STL 函式時,我們也可以使用宏來縮短程式碼。我們可以如下使用它們。

示例

#include <iostream>
#include <vector>
#define F first
#define S second
#define PB push_back
using namespace std;
typedef long long ll;
typedef vector<int< vi;
typedef pair<int, int< pii;
int main() {
   vi v;
   pii p(50, 60);
   v.PB(10);
   v.PB(20);
   v.PB(30);
   for(int i = 0; i<v.size(); i++)
      cout << v[i] << " ";
      cout << endl;
      cout << "First : " << p.F;
      cout << "\nSecond: " << p.S;
}

輸出

10 20 30
First : 50
Second: 60

更新於:2019 年 8 月 19 日

331 次瀏覽

開始你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.