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

Type Deduction ใน C++ คืออะไร?

Type inference หรือ deduction หมายถึงการตรวจจับชนิดข้อมูลของ expression แบบอัตโนมัติในภาษาโปรแกรมมิ่ง เป็นคุณสมบัติที่มีในภาษาบางภาษาที่เป็น strongly statically typed ใน C++ คีย์เวิร์ด auto (เพิ่มใน C++11) ใช้สำหรับ automatic type deduction ตัวอย่างเช่น คุณต้องการสร้าง iterator เพื่อวนลูป vector คุณสามารถใช้ auto ได้ -

ตัวอย่าง

#include <iostream>
#include <vector>
using namespace std;
int main() {
    vector<int> arr(10);
    for(auto it = arr.begin(); it != arr.end(); it++) {
        cin >> *it;
    }
    return 0;
}

ในโปรแกรมข้างต้น it จะได้ชนิด std::vector<int>::iterator โดยอัตโนมัติ