Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

C++: เทคนิคย่อโค้ดสำหรับการแข่งขันเขียนโปรแกรม (Competitive Programming)

ในส่วนนี้เราจะดูตัวอย่างกลยุทธ์การย่อโค้ดสำหรับการแข่งขันเขียนโปรแกรม สมมติเราต้องเขียนโค้ดจำนวนมาก ในโค้ดนั้น เราสามารถปฏิบัติตามกลยุทธ์บางอย่างเพื่อทำให้สั้นลง

เราสามารถเปลี่ยนชื่อชนิดข้อมูล (type-name) ให้สั้นลงได้ โปรดตรวจสอบโค้ดเพื่อเข้าใจแนวคิด

ตัวอย่างโค้ด

#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

ดังนั้นหลังจากนั้น เราสามารถใช้ 'll' แทนการเขียน 'long long' ซ้ำๆ ได้

ตัวอย่างอีกอย่างของการใช้ typedef เหมือนด้านล่าง เมื่อเราเขียน template หรือ STL function เราสามารถใช้ macro สำหรับย่อโค้ดได้ ใช้ได้ดังนี้

ตัวอย่าง

#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