溫馨提示×

c++ map函數(shù)的使用方法是什么

c++
小億
100
2023-12-22 22:08:17
欄目: 編程語言

在C++中,使用map函數(shù)需要包含<algorithm>頭文件。map函數(shù)的使用方法如下:

  1. 定義一個(gè)目標(biāo)容器,用于存儲(chǔ)映射后的結(jié)果。
  2. 使用map函數(shù)將原容器中的元素映射到目標(biāo)容器中。

以下是一個(gè)示例代碼,演示了如何使用map函數(shù)將一個(gè)整數(shù)數(shù)組中的每個(gè)元素都乘以2,并將結(jié)果存儲(chǔ)在另一個(gè)容器中:

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

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    std::vector<int> result;

    // 使用map函數(shù)將原容器中的元素乘以2,并存儲(chǔ)到目標(biāo)容器中
    std::transform(numbers.begin(), numbers.end(), std::back_inserter(result), [](int n) { return n * 2; });

    // 輸出結(jié)果
    for (int n : result) {
        std::cout << n << " ";
    }
    std::cout << std::endl;

    return 0;
}

輸出結(jié)果為:2 4 6 8 10。

在上述代碼中,std::transform函數(shù)是map函數(shù)的C++標(biāo)準(zhǔn)庫實(shí)現(xiàn),它接受四個(gè)參數(shù):原容器的起始迭代器、原容器的結(jié)束迭代器、目標(biāo)容器的插入迭代器、以及一個(gè)用于指定映射操作的函數(shù)對象(使用了lambda表達(dá)式)。std::back_inserter函數(shù)是一個(gè)插入迭代器,它用于在目標(biāo)容器的末尾插入元素。

注意,map函數(shù)不會(huì)改變原容器,而是產(chǎn)生一個(gè)新的容器存儲(chǔ)映射后的結(jié)果。

0