ในการแข่งขันโปรแกรมมิ่ง (Competitive Programming) สิ่งสำคัญที่สุดคือโค้ดที่มีประสิทธิภาพ โค้ดที่ optimized และรวดเร็วสามารถทำให้อันดับต่างกันได้
เพื่อเขียนโค้ด C/C++ ให้มีประสิทธิภาพใน competitive programming นี่คือเครื่องมือที่มีประสิทธิภาพบางอย่าง
ก่อนอื่น ให้ทบทวนคำพื้นฐานบางอย่าง
Template คือการเขียนโค้ดที่ไม่ขึ้นอยู่กับ type เฉพาะ
Macro คือ named code fragment
Vectors คือ dynamic arrays ที่ปรับขนาดอัตโนมัติเมื่อ insert/delete element
ตอนนี้ มาดู basic updates ในโค้ดที่ช่วยเพิ่มประสิทธิภาพ
ใช้ faster input/output method ใน C/C++ − scanf/printf เร็วกว่า cin/cout
กำหนดตัวแปรด้วยค่าสูงสุดและต่ำสุด − ใช้ min-max function ลดความยุ่งยาก
สร้าง Range-based loops − สำหรับโค้ดที่มีประสิทธิภาพ ใช้ ranged loops iterate ผ่าน array และ vectors
ตัวอย่าง
#include<iostream>
using namespace std;
int main() {
cout<<"Iterating over array using ranged array: ";
int array[]= {6, 10, 31, 17, 50};
for (const auto &value: array)
cout<<value<<" ";
return 0;
}
ผลลัพธ์
Iterating over array using ranged array: 6 10 31 17 50
- ใช้ header files ที่เหมาะสม − โดยทั่วไป C++ มี libraries หลายตัว #include<bits/stdc++.h> มีเกือบทุกไฟล์ที่ต้องใน competitive programming แต่ต้องแน่ใจว่าจำเป็นจริงๆ ก่อน include มิฉะนั้นอาจใช้พื้นที่ computing มากเกินไป
ใช้ containers ลดพื้นที่ − containers เช่น vectors, maps, lists ใช้แก้ปัญหาเยอะใน competitive programming predefined functions บน containers ลดขนาดโค้ดและทำให้มีประสิทธิภาพมากขึ้น
ใช้ auto ประกาศ data types เพราะ type ถูกกำหนดที่ compile time