如何在c ++中创建映射函数? [英] How to create a map function in c++?

查看:142
本文介绍了如何在c ++中创建映射函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有一个整数列表[1,2,3,4,5]和一个映射函数,它将每个元素乘以10,并返回修饰列表为[10,20,30,40,50]修改原始列表。

Say there is a list of integers [1,2,3,4,5] and a map function that multiplies each element with 10 and returns modified list as [10,20,30,40,50] , with out modifying the original list. How this can be done efficiently in c++.

推荐答案

这是一个例子:

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

using namespace std;

int multiply(int);

int main() {
    vector<int> source;
    for(int i = 1; i <= 5; i++) {
    source.push_back(i);
    }

    vector<int> result;
    result.resize(source.size());
    transform(source.begin(), source.end(), result.begin(), multiply);

    for(vector<int>::iterator it = result.begin(); it != result.end(); ++it) {
        cout << *it << endl;
    }
}

int multiply(int value) {
    return value * 10;
}

这篇关于如何在c ++中创建映射函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆