peri hokiperihokiclarustologisticsrimashaop.compola taktis menang gates of olympus x1000 perihokipemain perihoki bongkar trik jepep starlight princess x1000perihoki beri panduan lengkap bermain mahjong ways 2 pgsofttips cara penghasil uang pgsoft mahjong ways 2 perihokimahjong wins 3 perihoki memberikan penggali terbesarfenomena gates of olympus buka peluang besar bagi duta76cara dapat pola emas rahasia di duta7 wild west goldtrik menang pgsoft mahjong ways 2 modal receh maxwin duta76duta76 main pgsoft mahjong ways 2 di sela istirahatscatter hitam mahjong wins 3 spin pasti jepe duta76perihoki spin mahjong ways 2 pgsoft scatter hitam maxwinsimbol mahjong wins 3 yang sering muncul di awal perihokitrik gampang menang mahjong winscuan mahjong wins 3 tanpa hentipola spin taruhan kecil mahjong winsstrategi kunci scatter hitam beruntungacor total mahjong wayskemenangan maksimal mahjong wayskemenangan pria pekanbaru mahjong waysmahjong wins3 fenomena baru sumatera baratmenangkan mahjong dengan lincahmenembus batas keberuntungan mahjong waysmenjajal keberuntungan di mahjong wayspola gratis mahjong ways1scatter hitam senjata rahasia mahjong winsteknik spinning menguntungkan untuk scatter hitamanalisis rtp tertinggi mahjong winsfenomena scatter hitam mahjong winsibu rumah tangga dan keberuntungan mahjongkeseruan main mahjong wins3menang mahjong pengguna baru di sosial mediamenghargai setiap momen di mahjong waysserunya main mahjong di warung internetspin slow motion mancing scatterstrategi jitu maxwin mahjong waysstrategi jitu menang mahjong modal kecil jackpot besaranak kampung papua menggemparkan mahjongkeajaiban scatter hitam mahjong wayskeberhasilan joni mahjong winskejaiban mahjong ways di ujung jalanketua mahjong wins3 kehadiran kemenangan dimulai dari balimahjong kehadiran yang menguntungkanmahjong menggila adat88panduan kilat raih 108 jutatips memenangkan mahjongbarista kopi menang 110 juta spin mahjongdakota76 scatter hitam mahjong wins 3gagal cpns menang mahjong wins 3 rp120 jutakisah karyawan minimarket dapat thr lebih awal mahjong winskisah pelajar sma kuasai mahjong wins 3 inspirasi sekolahkisah penjaga parkir tanah abang motor baru mahjong winskisah sukses ibu rumah tangga bandung mahjong winsmahasiswa kkn beli iphone15 mahjong wins3 dakotamantan anak band influencer mahjong scatter hitampola rtp senin gates of olympus guru matematikatukang cuci motor menemukan keberuntungan di mahjong

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 282

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: session_set_cookie_params(): Cannot change session cookie parameters when headers already sent

Filename: Session/Session.php

Line Number: 294

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 304

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 314

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 315

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 316

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 317

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 375

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: drivers/Session_files_driver.php

Line Number: 108

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: session_set_save_handler(): Cannot change save handler when headers already sent

Filename: Session/Session.php

Line Number: 110

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: session_start(): Cannot start session when headers already sent

Filename: Session/Session.php

Line Number: 143

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

[STL] Cách sắp xếp một vector trong C++ - Freetuts
STARTING
CONTROL STATEMENT
FUNCTION
ARRAY & POINTER
OOP
STL
ITERATORS
OTHER FEATURES
CÁC CHỦ ĐỀ
BÀI MỚI NHẤT
MỚI CẬP NHẬT

[STL] Cách sắp xếp một vector trong C++

Việc sắp xếp dữ liệu là một trong những thao tác cơ bản và quan trọng. Với việc sử dụng STL (Standard Template Library), việc sắp xếp các phần tử trong một vector trở nên đơn giản và hiệu quả hơn bao giờ hết. Trong bài viết này, mình sẽ tìm hiểu về cách sắp xếp một vector trong C++ bằng cách sử dụng các công cụ và thuật toán có sẵn trong STL.

test php

banquyen png
Bài viết này được đăng tại freetuts.net, không được copy dưới mọi hình thức.

Chúng ta sẽ bắt đầu bằng cách giới thiệu về vector trong STL và vai trò của nó trong việc lưu trữ dữ liệu. Sau đó, sẽ đi sâu vào các phương pháp sắp xếp vector, bao gồm sắp xếp tăng dần, sắp xếp giảm dần và cách sắp xếp sử dụng hàm so sánh tùy chỉnh. Cuối cùng, mình sẽ xem xét một số ví dụ minh họa để hiểu rõ hơn cách sử dụng các phương pháp này trong thực tế.

Screenshot 202024 03 26 20180116 png

Vector trong STL của C++

Vector là một trong những cấu trúc dữ liệu phổ biến nhất trong STL (Standard Template Library) của C++. Nó là một loại mảng động có kích thước linh hoạt, cho phép thêm, xóa và truy cập các phần tử một cách dễ dàng.

Khi khai báo một vector, bạn không cần phải chỉ định kích thước ban đầu của nó. Vector tự động mở rộng khi cần thiết để chứa thêm phần tử mới. Điều này làm cho việc sử dụng vector trở nên linh hoạt và thuận tiện trong việc lưu trữ dữ liệu.

Bài viết này được đăng tại [free tuts .net]

Ví dụ:

#include <iostream>
#include <vector>

int main() {
    // Khai báo và khởi tạo vector rỗng
    std::vector<int> myVector;

    // Thêm các phần tử vào vector
    myVector.push_back(10);
    myVector.push_back(20);
    myVector.push_back(30);
    //Bài được đăng tại freetuts.net

    // Truy cập và hiển thị các phần tử trong vector
    std::cout << "Vector: ";
    for (int i = 0; i < myVector.size(); ++i) {
        std::cout << myVector[i] << " ";
    }
    std::cout << std::endl;

    return 0;
}

Kết quả:

Screenshot 202024 03 26 20170136 png

Trong ví dụ trên, mình đã khai báo và khởi tạo một vector rỗng ban đầu. Sau đó, đã thêm các phần tử vào vector bằng phương thức push_back() và truy cập các phần tử trong vector bằng cách sử dụng chỉ số. Vector tự động mở rộng kích thước của mình để chứa các phần tử mới khi cần thiết.

Cách sắp xếp một vector trong C++

Sắp xếp tăng dần

Để sắp xếp một vector theo thứ tự tăng dần, mình có thể sử dụng hàm std::sort() trong STL. Hàm này sẽ sắp xếp các phần tử của vector theo thứ tự tăng dần.

Hàm std::sort() trong STL:

  • Hàm std::sort() được sử dụng để sắp xếp các phần tử trong một range thành thứ tự tăng dần.
  • Hàm này có thể được sử dụng với các kiểu dữ liệu cơ bản và cũng với các kiểu dữ liệu do người dùng định nghĩa.

Ví dụ minh họa:

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    // Khai báo và khởi tạo vector
    std::vector<int> myVector = {5, 2, 8, 1, 9};

    // Sắp xếp vector theo thứ tự tăng dần
    std::sort(myVector.begin(), myVector.end());
    //Bài được đăng tại freetuts.net

    // Hiển thị vector sau khi đã sắp xếp
    std::cout << "Vector sau khi sap xep tang dan: ";
    for (int num : myVector) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}

Kết quả:

Screenshot 202024 03 26 20175138 png

Trong ví dụ này, mình khai báo và khởi tạo một vector với các giá trị ban đầu. Sau đó, chúng ta sử dụng hàm std::sort() để sắp xếp vector này thành thứ tự tăng dần. Cuối cùng, hiển thị vector sau khi đã sắp xếp.

Sắp xếp giảm dần

Để sắp xếp một vector theo thứ tự giảm dần, chúng ta có thể sử dụng hàm so sánh ngược std::greater<>() trong STL. Hàm này sẽ sắp xếp các phần tử của vector theo thứ tự giảm dần.

Hàm std::greater<>() trong STL:

  • Hàm std::greater<>() được sử dụng để so sánh hai phần tử và trả về true nếu phần tử đầu tiên lớn hơn phần tử thứ hai, ngược lại trả về false.

Ví dụ minh họa:

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    // Khai báo và khởi tạo vector
    std::vector<int> myVector = {5, 2, 8, 1, 9};

    // Sắp xếp vector theo thứ tự giảm dần
    std::sort(myVector.begin(), myVector.end(), std::greater<int>());
    //Bài được đăng tại freetuts.net

    // Hiển thị vector sau khi đã sắp xếp
    std::cout << "Vector sau khi sap xep giam dan: ";
    for (int num : myVector) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}

Kết quả:

Screenshot 202024 03 26 20175201 png

Trong ví dụ này, mình khai báo và khởi tạo một vector với các giá trị ban đầu. Sau đó, mình sử dụng hàm std::sort() với hàm so sánh ngược std::greater<>() để sắp xếp vector này thành thứ tự giảm dần. Cuối cùng, mình hiển thị vector sau khi đã sắp xếp.

Sắp xếp sử dụng hàm so sánh tùy chỉnh

Để sắp xếp một vector theo một tiêu chí nhất định, mình có thể sử dụng hàm so sánh tùy chỉnh. Điều này cho phép sắp xếp vector dựa trên một thuộc tính cụ thể hoặc một tiêu chí phức tạp khác.

Cách sử dụng hàm so sánh tùy chỉnh:

  • Mình có thể sử dụng hàm so sánh tùy chỉnh bằng cách truyền một hàm so sánh hoặc một hàm so sánh lambda như một tham số cho hàm std::sort().

Ví dụ minh họa:

#include <iostream>
#include <vector>
#include <algorithm>
//Bài được đăng tại freetuts.net

// Hàm so sánh tùy chỉnh để sắp xếp vector theo giá trị tuyệt đối
bool customCompare(int a, int b) {
    return std::abs(a) < std::abs(b);
}

int main() {
    // Khai báo và khởi tạo vector
    std::vector<int> myVector = {5, -2, 8, -1, 9};

    // Sắp xếp vector theo giá trị tuyệt đối
    std::sort(myVector.begin(), myVector.end(), customCompare);

    // Hiển thị vector sau khi đã sắp xếp
    std::cout << "Vector sau khi sap xep theo gia tri tuyet doi: ";
    for (int num : myVector) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}

Kết quả:

Screenshot 202024 03 26 20175223 png

Trong ví dụ này, mình sử dụng một hàm so sánh tùy chỉnh customCompare() để sắp xếp vector theo giá trị tuyệt đối của các phần tử.

Kết bài

Trong khi viết ứng dụng C++, việc sắp xếp dữ liệu là một yếu tố quan trọng để tối ưu hóa hiệu suất và tăng tính linh hoạt của chương trình. Qua bài viết này, chúng ta đã hiểu rõ về cách sử dụng STL để sắp xếp một vector trong C++. Từ việc khai báo và sử dụng các phương thức cơ bản cho đến việc áp dụng các thuật toán sắp xếp và tìm kiếm, chúng ta đã nhận thấy tính tiện lợi và mạnh mẽ của STL trong việc xử lý dữ liệu. Hy vọng rằng thông qua bài viết này, bạn sẽ có được kiến thức và kỹ năng cần thiết để hiệu quả sử dụng vector và sắp xếp dữ liệu trong các ứng dụng C++ của mình.

Cùng chuyên mục:

Các hàm xử lý mảng đa chiều (array.h) trong C/C++

Các hàm xử lý mảng đa chiều (array.h) trong C/C++

Các hàm xử lý ngày tháng (datetime.h) trong C/C++

Các hàm xử lý ngày tháng (datetime.h) trong C/C++

Các hàm xử lý số thực (float.h) trong C/C++

Các hàm xử lý số thực (float.h) trong C/C++

Các hàm xử lý số nguyên lớn (bigint.h) trong C/C++

Các hàm xử lý số nguyên lớn (bigint.h) trong C/C++

Các hàm xử lý thời gian (time.h) trong C

Các hàm xử lý thời gian (time.h) trong C

Các hàm xử lý chuỗi (string.h) trong C/C++

Các hàm xử lý chuỗi (string.h) trong C/C++

Thread Pools và Parallel Algorithms trong C++

Thread Pools và Parallel Algorithms trong C++

Tạo và quản lý các Multithreading trong C++

Tạo và quản lý các Multithreading trong C++

Xử lý ngoại lệ khi làm việc với Memory Allocation trong C++

Xử lý ngoại lệ khi làm việc với Memory Allocation trong C++

Try, Catch, và Throw của Exception Handling trong C++

Try, Catch, và Throw của Exception Handling trong C++

Cách sử dụng Lambda Expressions trong C++

Cách sử dụng Lambda Expressions trong C++

Sử dụng weak_ptr trong C++

Sử dụng weak_ptr trong C++

Sử dụng shared_ptr trong C++

Sử dụng shared_ptr trong C++

Sử dụng unique_ptr trong C++

Sử dụng unique_ptr trong C++

Tổng quan về Smart Pointers trong C++

Tổng quan về Smart Pointers trong C++

Sử dụng Iterators trong STL của C++

Sử dụng Iterators trong STL của C++

[Iterator] Sử dụng Vector trong C++

[Iterator] Sử dụng Vector trong C++

[Iterator] Sử dụng trong List trong C++

[Iterator] Sử dụng trong List trong C++

[STL] Sử dụng Vector trong C++

[STL] Sử dụng Vector trong C++

Tổng quan về Iterators trong C++

Tổng quan về Iterators trong C++

Top