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

การส่ง Vector ให้ Constructor ใน C++

นี่คือโปรแกรม C++ เรียบง่ายสำหรับส่ง Vector ให้ Constructor

อัลกอริทึม

Begin
    Declare class Vector
    Declare vec of vector type
    Declare constructor taking vector object v as parameter
    Initialize vec = v
    Declare show() to display vector values
    Declare v vector with values
    Declare ob object of Vector class passing v
    Call show() to display all values
End.

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

#include <iostream>
#include <vector>
using namespace std;

class Vector {
    vector<int> vec;
public:
    Vector(vector<int> v) { vec = v; }
    void show() {
        for (int i = 0; i < vec.size(); i++) cout << vec[i] << " ";
    }
};

int main() {
    vector<int> v = {7,6,5,4};
    Vector ob(v);
    ob.show();
    return 0;
}

ผลลัพธ์

7 6 5 4