偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

C++ 也能像 Python 一樣優(yōu)雅?pair、tuple、tie 來(lái)幫忙

開(kāi)發(fā)
今天咱們就來(lái)聊聊 C++ 里的三個(gè)神器:pair、tuple和tie。用好了這仨,你的 C++ 代碼也能像 Python 一樣簡(jiǎn)潔漂亮。

大家好,我是小康。

寫(xiě)過(guò) Python 的朋友都知道,Python處理多個(gè)返回值有多爽:x, y = func(),想交換兩個(gè)變量?a, b = b, a 一行搞定。每次寫(xiě) C++ 的時(shí)候,是不是都羨慕得不行?

其實(shí),C++也能寫(xiě)得很優(yōu)雅!今天咱們就來(lái)聊聊 C++ 里的三個(gè)神器:pair、tuple和tie。用好了這仨,你的 C++ 代碼也能像 Python 一樣簡(jiǎn)潔漂亮。

別再羨慕 Python 了,C++同樣可以很優(yōu)雅!

一、第一個(gè)救星:pair - 成雙成對(duì)好伙伴

1. 什么是pair?

想象一下,你去買(mǎi)奶茶,店員問(wèn)你:"要什么口味?什么甜度?"這就是兩個(gè)相關(guān)但不同的信息。在 C++ 里,pair就是專門(mén)用來(lái)裝這種"成對(duì)出現(xiàn)"數(shù)據(jù)的容器。

簡(jiǎn)單說(shuō),pair就是一個(gè)能裝兩個(gè)不同類型數(shù)據(jù)的小盒子。

2. 怎么用pair?

#include <iostream>
#include <utility>  // pair在這里
using namespace std;

int main() {
    // 創(chuàng)建一個(gè)pair,裝個(gè)奶茶訂單
    pair<string, int> order("珍珠奶茶", 7);  // 口味和甜度
    
    cout << "我要一杯 " << order.first << "," << order.second << "分甜" << endl;
    
    // 還可以這樣創(chuàng)建
    auto order2 = make_pair("椰果奶茶", 5);
    cout << "再來(lái)一杯 " << order2.first << "," << order2.second << "分甜" << endl;
    
    return 0;
}

輸出結(jié)果:

我要一杯 珍珠奶茶,7分甜
再來(lái)一杯 椰果奶茶,5分甜

看到?jīng)]?用first取第一個(gè)值,用second取第二個(gè)值,簡(jiǎn)單粗暴!

2. pair的實(shí)際應(yīng)用場(chǎng)景

(1) 場(chǎng)景1:函數(shù)返回多個(gè)值

以前我們想讓函數(shù)返回兩個(gè)值,得這么寫(xiě):

// 老土的寫(xiě)法
void getMinMax(vector<int>& nums, int& minVal, int& maxVal) {
    // 通過(guò)引用返回...好麻煩
}

現(xiàn)在用 pair,瞬間優(yōu)雅:

#include <iostream>
#include <utility>  // pair在這里
#include <algorithm>  // max_element在這里
#include <vector> 

using namespace std;

pair<int, int> getMinMax(vector<int>& nums) {
    int minVal = *min_element(nums.begin(), nums.end());
    int maxVal = *max_element(nums.begin(), nums.end());
    return make_pair(minVal, maxVal);
}

int main() {
    vector<int> numbers = {3, 1, 4, 1, 5, 9, 2, 6};
    auto result = getMinMax(numbers);
    
    cout << "最小值:" << result.first << endl;
    cout << "最大值:" << result.second << endl;
    return 0;
}

輸出結(jié)果:

最小值:1
最大值:9

場(chǎng)景2:map的鍵值對(duì)

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

int main() {
    map<string, int> scoreMap;
    scoreMap["小明"] = 95;
    scoreMap["小紅"] = 87;
    
    // 遍歷map時(shí),每個(gè)元素就是一個(gè)pair
    for(auto& student : scoreMap) {
        cout << student.first << "考了" << student.second << "分" << endl;
    }
    return 0;
}

二、第二個(gè)救星:tuple - 數(shù)據(jù)打包專業(yè)戶

1. 什么是tuple?

如果說(shuō) pair 是個(gè)只能裝兩個(gè)東西的小盒子,那 tuple 就是個(gè)能裝 N 個(gè)東西的大箱子。你想裝多少就裝多少!

2. 基礎(chǔ)用法

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

int main() {
    // 創(chuàng)建一個(gè)學(xué)生信息tuple:姓名、年齡、成績(jī)、是否及格
    tuple<string, int, double, bool> student("張三", 20, 85.5, true);
    
    // 取值要用get<索引>()
    cout << "姓名:" << get<0>(student) << endl;
    cout << "年齡:" << get<1>(student) << endl;
    cout << "成績(jī):" << get<2>(student) << endl;
    cout << "是否及格:" << (get<3>(student) ? "是" : "否") << endl;
    
    return 0;
}

輸出結(jié)果:

姓名:張三
年齡:20
成績(jī):85.5
是否及格:是

3. tuple的高級(jí)玩法

創(chuàng)建tuple的幾種方式:

// 方式1:直接構(gòu)造
tuple<int, string, double> t1(1, "hello", 3.14);

// 方式2:使用make_tuple
auto t2 = make_tuple(2, "world", 2.71);

// 方式3:C++17的推導(dǎo)
tuple t3{3, "test", 1.41};  // 編譯器自動(dòng)推導(dǎo)類型

修改tuple中的值:

tuple<string, int> info("小王", 25);
get<1>(info) = 26;  // 修改年齡
cout << get<0>(info) << "今年" << get<1>(info) << "歲了" << endl;

4. 實(shí)際應(yīng)用:函數(shù)返回多個(gè)值

// 解析一個(gè)日期字符串,返回年月日
tuple<int, int, int> parseDate(string dateStr) {
    // 簡(jiǎn)化版解析(實(shí)際項(xiàng)目中要更嚴(yán)謹(jǐn))
    int year = 2024, month = 12, day = 25;
    return make_tuple(year, month, day);
}

int main() {
    auto date = parseDate("2024-12-25");
    
    cout << "年份:" << get<0>(date) << endl;
    cout << "月份:" << get<1>(date) << endl;
    cout << "日期:" << get<2>(date) << endl;
    return 0;
}

三、第三個(gè)救星:tie - 解包大師

1. tie是干啥的?

前面我們用 pair 和 tuple 打包數(shù)據(jù),但取數(shù)據(jù)時(shí)還是要用 first、second 或者get<>(),有點(diǎn)麻煩。tie 就是來(lái)解決這個(gè)問(wèn)題的,它能把打包的數(shù)據(jù)一口氣解開(kāi),分別賦值給不同的變量。

2. 基礎(chǔ)用法

#include <iostream>  
#include <string>   
#include <utility>  
#include <tuple>
using namespace std;

int main() {
    pair<string, int> order("抹茶拿鐵", 6);
    
    // 傳統(tǒng)取值方式
    string drink = order.first;
    int sweetness = order.second;
    
    // 使用tie一步到位
    string drink2;
    int sweetness2;
    tie(drink2, sweetness2) = order;
    
    cout << "飲品:" << drink2 << ",甜度:" << sweetness2 << endl;
    return 0;
}

3. tie的實(shí)際應(yīng)用

(1) 場(chǎng)景1:變量交換

以前交換兩個(gè)變量,得用臨時(shí)變量:

// 老辦法
int a = 10, b = 20;
int temp = a;
a = b;
b = temp;

現(xiàn)在用tie,一行搞定:

int a = 10, b = 20;
cout << "交換前:a=" << a << ", b=" << b << endl;

tie(a, b) = make_pair(b, a);  // 神奇的一行代碼
cout << "交換后:a=" << a << ", b=" << b << endl;

輸出結(jié)果:

交換前:a=10, b=20
交換后:a=20, b=10

(2) 場(chǎng)景2:處理函數(shù)返回的tuple

// 計(jì)算圓的周長(zhǎng)和面積
tuple<double, double> calculateCircle(double radius) {
    double perimeter = 2 * 3.14159 * radius;
    double area = 3.14159 * radius * radius;
    return make_tuple(perimeter, area);
}

int main() {
    double r = 5.0;
    double perimeter, area;
    
    // 一步解包
    tie(perimeter, area) = calculateCircle(r);
    
    cout << "半徑為" << r << "的圓:" << endl;
    cout << "周長(zhǎng):" << perimeter << endl;
    cout << "面積:" << area << endl;
    return 0;
}

輸出結(jié)果:

半徑為5的圓:
周長(zhǎng):31.4159
面積:78.5398

(3) 場(chǎng)景3:忽略不需要的值

有時(shí)候我們只需要tuple中的部分值,可以用std::ignore來(lái)忽略:

tuple<string, int, double, bool> studentInfo("李四", 22, 92.5, true);

string name;
double score;

// 只要姓名和成績(jī),忽略年齡和及格狀態(tài)
tie(name, ignore, score, ignore) = studentInfo;

cout << name << "的成績(jī)是" << score << endl;

四、C++17的新玩法:結(jié)構(gòu)化綁定

如果你用的是C++17或更新版本,還有個(gè)更酷的寫(xiě)法叫"結(jié)構(gòu)化綁定":

// C++17寫(xiě)法,更簡(jiǎn)潔
auto [drink, sweetness] = make_pair("焦糖瑪奇朵", 8);
cout << drink << "," << sweetness << "分甜" << endl;

// 處理tuple也很簡(jiǎn)單
auto [name, age, score] = make_tuple("王五", 21, 88.5);
cout << name << "," << age << "歲,得分" << score << endl;

五、實(shí)戰(zhàn)演練:擼個(gè)游戲裝備管理系統(tǒng)

咱們來(lái)寫(xiě)個(gè)有意思的例子——游戲裝備管理系統(tǒng)!想象你在玩RPG游戲,需要管理各種裝備的屬性。

#include <iostream>
#include <vector>
#include <tuple>
#include <algorithm>
#include <iomanip>
using namespace std;

// 裝備信息:名稱、攻擊力、防御力、稀有度、價(jià)格
using Equipment = tuple<string, int, int, string, double>;

// 計(jì)算裝備戰(zhàn)斗力和性價(jià)比
pair<int, double> calculateStats(const Equipment& equipment) {
    auto [name, attack, defense, rarity, price] = equipment;
    int combatPower = attack * 2 + defense;  // 攻擊力權(quán)重更高
    double costEfficiency = combatPower / price;  // 性價(jià)比
    return make_pair(combatPower, costEfficiency);
}

// 找出最強(qiáng)和最弱裝備
pair<Equipment, Equipment> findBestAndWorst(vector<Equipment>& equipments) {
    auto strongest = *max_element(equipments.begin(), equipments.end(),
        [](const Equipment& a, const Equipment& b) {
            auto [powerA, efficiencyA] = calculateStats(a);
            auto [powerB, efficiencyB] = calculateStats(b);
            return powerA < powerB;
        });
    
    auto weakest = *min_element(equipments.begin(), equipments.end(),
        [](const Equipment& a, const Equipment& b) {
            auto [powerA, efficiencyA] = calculateStats(a);
            auto [powerB, efficiencyB] = calculateStats(b);
            return powerA < powerB;
        });
    
    return make_pair(strongest, weakest);
}

// 根據(jù)預(yù)算推薦裝備
tuple<Equipment, string, bool> recommendEquipment(vector<Equipment>& equipments, double budget) {
    Equipment bestChoice;
    bool found = false;
    double bestEfficiency = 0;
    
    for(const auto& equipment : equipments) {
        auto [name, attack, defense, rarity, price] = equipment;
        if(price <= budget) {
            auto [power, efficiency] = calculateStats(equipment);
            if(!found || efficiency > bestEfficiency) {
                bestChoice = equipment;
                bestEfficiency = efficiency;
                found = true;
            }
        }
    }
    
    string recommendation = found ? "強(qiáng)烈推薦!" : "預(yù)算不足,建議攢錢(qián)";
    return make_tuple(bestChoice, recommendation, found);
}

int main() {
    vector<Equipment> equipments = {
        make_tuple("新手木劍", 15, 5, "普通", 50.0),
        make_tuple("鋼鐵長(zhǎng)劍", 35, 15, "稀有", 300.0),
        make_tuple("龍鱗戰(zhàn)甲", 10, 45, "史詩(shī)", 800.0),
        make_tuple("傳說(shuō)之刃", 80, 20, "傳說(shuō)", 1500.0),
        make_tuple("魔法法杖", 60, 10, "稀有", 600.0),
        make_tuple("守護(hù)者盾牌", 5, 50, "史詩(shī)", 700.0)
    };
    
    cout << "?? === 游戲裝備庫(kù)存 === ??" << endl;
    cout << left << setw(15) << "裝備名稱"
         << setw(8) << "攻擊力" << setw(8) << "防御力"
         << setw(8) << "稀有度" << setw(10) << "價(jià)格"
         << setw(10) << "戰(zhàn)斗力" << "性價(jià)比" << endl;
    cout << string(75, '-') << endl;
    
    for(const auto& equipment : equipments) {
        auto [name, attack, defense, rarity, price] = equipment;
        auto [combatPower, efficiency] = calculateStats(equipment);
        
        cout << left << setw(15) << name 
             << setw(8) << attack << setw(8) << defense 
             << setw(8) << rarity << setw(10) << fixed << setprecision(1) << price
             << setw(10) << combatPower << setprecision(3) << efficiency << endl;
    }
    
    auto [strongest, weakest] = findBestAndWorst(equipments);
    
    cout << "\n??  === 裝備評(píng)測(cè) === ??" << endl;
    auto [strongName, strongAttack, strongDefense, strongRarity, strongPrice] = strongest;
    auto [strongPower, strongEfficiency] = calculateStats(strongest);
    cout << "最強(qiáng)裝備:" << strongName << "(戰(zhàn)斗力" << strongPower << ")??" << endl;
    
    auto [weakName, weakAttack, weakDefense, weakRarity, weakPrice] = weakest;
    auto [weakPower, weakEfficiency] = calculateStats(weakest);
    cout << "最弱裝備:" << weakName << "(戰(zhàn)斗力" << weakPower << ")??" << endl;
    
    cout << "\n?? === 購(gòu)買(mǎi)建議 === ??" << endl;
    vector<double> budgets = {100, 400, 800, 2000};
    
    for(double budget : budgets) {
        auto [recommended, advice, canAfford] = recommendEquipment(equipments, budget);
        cout << "預(yù)算" << budget << "金幣:";
        
        if(canAfford) {
            auto [recName, recAttack, recDefense, recRarity, recPrice] = recommended;
            auto [recPower, recEfficiency] = calculateStats(recommended);
            cout << recName << "(戰(zhàn)斗力" << recPower << ",性價(jià)比"
                 << fixed << setprecision(3) << recEfficiency << ")" << advice << endl;
        } else {
            cout << advice << endl;
        }
    }
    
    // 展示變量交換的實(shí)際應(yīng)用
    cout << "\n?? === 裝備交換演示 === ??" << endl;
    auto weapon1 = make_tuple("火焰劍", 45, 10, "稀有", 400.0);
    auto weapon2 = make_tuple("冰霜斧", 40, 15, "稀有", 350.0);
    
    cout << "交換前:" << endl;
    cout << "武器1:" << get<0>(weapon1) << "(攻擊" << get<1>(weapon1) << ")" << endl;
    cout << "武器2:" << get<0>(weapon2) << "(攻擊" << get<1>(weapon2) << ")" << endl;
    
    // 使用tie進(jìn)行裝備交換
    tie(weapon1, weapon2) = make_pair(weapon2, weapon1);
    
    cout << "交換后:" << endl;
    cout << "武器1:" << get<0>(weapon1) << "(攻擊" << get<1>(weapon1) << ")" << endl;
    cout << "武器2:" << get<0>(weapon2) << "(攻擊" << get<1>(weapon2) << ")" << endl;
    
    return 0;
}

輸出結(jié)果:

?? === 游戲裝備庫(kù)存 === ??
裝備名稱   攻擊力防御力稀有度價(jià)格    戰(zhàn)斗力 性價(jià)比
---------------------------------------------------------------------------
新手木劍   15      5       普通  50.0      35        0.700
鋼鐵長(zhǎng)劍   35      15      稀有  300.0     85        0.283
龍鱗戰(zhàn)甲   10      45      史詩(shī)  800.0     65        0.081
傳說(shuō)之刃   80      20      傳說(shuō)  1500.0    180       0.120
魔法法杖   60      10      稀有  600.0     130       0.217
守護(hù)者盾牌5       50      史詩(shī)  700.0     60        0.086

??  === 裝備評(píng)測(cè) === ??
最強(qiáng)裝備:傳說(shuō)之刃(戰(zhàn)斗力180)??
最弱裝備:新手木劍(戰(zhàn)斗力35)??

?? === 購(gòu)買(mǎi)建議 === ??
預(yù)算100.000金幣:新手木劍(戰(zhàn)斗力35,性價(jià)比0.700)強(qiáng)烈推薦!
預(yù)算400.000金幣:新手木劍(戰(zhàn)斗力35,性價(jià)比0.700)強(qiáng)烈推薦!
預(yù)算800.000金幣:新手木劍(戰(zhàn)斗力35,性價(jià)比0.700)強(qiáng)烈推薦!
預(yù)算2000.000金幣:新手木劍(戰(zhàn)斗力35,性價(jià)比0.700)強(qiáng)烈推薦!

?? === 裝備交換演示 === ??
交換前:
武器1:火焰劍(攻擊45)
武器2:冰霜斧(攻擊40)
交換后:
武器1:冰霜斧(攻擊40)
武器2:火焰劍(攻擊45)

六、總結(jié)

好了,咱們來(lái)總結(jié)一下今天學(xué)的三個(gè)小工具:

  • pair:專門(mén)裝兩個(gè)相關(guān)數(shù)據(jù),取值用first和second。適合函數(shù)返回兩個(gè)值、處理鍵值對(duì)等場(chǎng)景。
  • tuple:能裝N個(gè)數(shù)據(jù)的萬(wàn)能容器,取值用get<索引>()。適合需要返回多個(gè)不同類型數(shù)據(jù)的場(chǎng)景。
  • tie:專門(mén)用來(lái)解包pair和tuple的工具,能一次性把數(shù)據(jù)分配給多個(gè)變量。還能用來(lái)做變量交換這種騷操作。

現(xiàn)代C++: 如果你用C++17,結(jié)構(gòu)化綁定讓代碼更簡(jiǎn)潔,直接 auto [a, b, c] = ... 就搞定。

這三個(gè)工具組合使用,能讓你的代碼變得更清晰、更優(yōu)雅。再也不用為了返回多個(gè)值而糾結(jié),再也不用定義一堆臨時(shí)變量了!

記住,編程不是為了炫技,而是為了讓代碼更好維護(hù)、更好理解。這些工具用好了,你的代碼會(huì)讓同事們刮目相看的!

下次寫(xiě)代碼時(shí),試試用這些小工具,你會(huì)發(fā)現(xiàn)編程原來(lái)可以這么舒服!

責(zé)任編輯:趙寧寧 來(lái)源: 跟著小康學(xué)編程
相關(guān)推薦

2021-08-12 06:08:15

CSS 技巧組件狀態(tài)

2011-10-27 09:42:19

ASP.NET

2023-05-23 13:59:41

RustPython程序

2013-12-31 09:19:23

Python調(diào)試

2013-12-17 09:02:03

Python調(diào)試

2021-04-12 10:20:20

Java微服務(wù)Go

2021-05-20 08:37:32

multiprocesPython線程

2023-04-05 14:19:07

FlinkRedisNoSQL

2022-10-21 13:52:56

JS 報(bào)錯(cuò)調(diào)試本地源碼

2017-05-22 10:33:14

PythonJuliaCython

2022-12-21 15:56:23

代碼文檔工具

2020-11-17 15:31:23

Java微服務(wù)Go

2024-08-29 08:07:59

GoAPI開(kāi)發(fā)

2020-08-25 08:56:55

Pythonawk字符串

2014-09-22 09:27:57

Python

2013-08-22 10:17:51

Google大數(shù)據(jù)業(yè)務(wù)價(jià)值

2015-03-16 12:50:44

2011-01-18 10:45:16

喬布斯

2012-06-08 13:47:32

Wndows 8Vista

2015-02-05 13:27:02

移動(dòng)開(kāi)發(fā)模塊SDK
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)