溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

字符串去重C++庫(kù)函數(shù)

發(fā)布時(shí)間:2024-10-09 14:55:17 來(lái)源:億速云 閱讀:78 作者:小樊 欄目:編程語(yǔ)言

在 C++ 中,可以使用 std::setstd::unordered_set 容器來(lái)實(shí)現(xiàn)字符串去重。這兩個(gè)容器中的元素都是唯一的,因此可以將字符串插入其中,然后將重復(fù)的字符串過(guò)濾掉。

以下是使用 std::set 進(jìn)行字符串去重的示例代碼:

#include <iostream>
#include <set>
#include <string>
#include <vector>

int main() {
    std::vector<std::string> strs = {"apple", "banana", "orange", "apple", "banana", "grape"};

    // 使用 set 去重
    std::set<std::string> str_set(strs.begin(), strs.end());

    // 將去重后的字符串存入 vector 中
    std::vector<std::string> unique_strs(str_set.begin(), str_set.end());

    // 輸出去重后的字符串
    for (const auto& str : unique_strs) {
        std::cout << str << std::endl;
    }

    return 0;
}

輸出結(jié)果為:

apple
banana
grape
orange

以下是使用 std::unordered_set 進(jìn)行字符串去重的示例代碼:

#include <iostream>
#include <unordered_set>
#include <string>
#include <vector>

int main() {
    std::vector<std::string> strs = {"apple", "banana", "orange", "apple", "banana", "grape"};

    // 使用 unordered_set 去重
    std::unordered_set<std::string> str_set(strs.begin(), strs.end());

    // 將去重后的字符串存入 vector 中
    std::vector<std::string> unique_strs(str_set.begin(), str_set.end());

    // 輸出去重后的字符串
    for (const auto& str : unique_strs) {
        std::cout << str << std::endl;
    }

    return 0;
}

輸出結(jié)果為:

apple
banana
grape
orange
向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

c++
AI