Vector

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

การประกาศ Vector นั้นสามารถทำได้โดยการใช้คำสั่งดังนี้

// vector<data_type> vector_name;
vector<int> Hallway(9);
vector<int> Hallway;
vector<int> Hallway {1,2,3,4,5};
vector<int> Hallway = {1,2,3,4,5};
vector<double> grade;
vector <char> Alpgrade;
vector<string> cars {"Jame","Jack","John"};

ฟังก์ชันที่เกี่ยวข้องกับเวกเตอร์คือ:

ฟังก์ชันที่ถูกใช้บ่อยที่สุด

  • push_back(): appends an element to the end

  • pop_back() Erases the last element

  • size() provides the number of elements

  • begin() provides reference to last element

  • end() provides reference to end of Vector.

  1. Iterators (ตัววนซ้ำ)

    • begin() – Returns an iterator pointing to the first element in the vector

    • end() – Returns an iterator pointing to the theoretical element that follows the last element in the vector

    • rbegin() – Returns a reverse iterator pointing to the last element in the vector (reverse beginning). It moves from last to first element

    • rend() – Returns a reverse iterator pointing to the theoretical element preceding the first element in the vector (considered as reverse end)

    • cbegin() – Returns a constant iterator pointing to the first element in the vector.

    • cend() – Returns a constant iterator pointing to the theoretical element that follows the last element in the vector.

    • crbegin() – Returns a constant reverse iterator pointing to the last element in the vector (reverse beginning). It moves from last to first element

    • crend() – Returns a constant reverse iterator pointing to the theoretical element preceding the first element in the vector (considered as reverse end)

Output

2. Capacity (ความจุ)

  • size() – Returns the number of elements in the vector.

  • max_size() – Returns the maximum number of elements that the vector can hold.

  • capacity() – Returns the size of the storage space currently allocated to the vector expressed as number of elements.

  • resize(n) – Resizes the container so that it contains ‘n’ elements.

  • empty() – Returns whether the container is empty.

  • shrink_to_fit() – Reduces the capacity of the container to fit its size and destroys all elements beyond the capacity.

  • reserve() – Requests that the vector capacity be at least enough to contain n elements.

Output

Reference

Last updated

Was this helpful?