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

Type Inference (การอนุมานชนิดข้อมูล) ใน 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 อัตโนมัติ