Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a map function in c++?

Tags:

c++

list

map

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++.

like image 795
yesraaj Avatar asked Jan 08 '10 17:01

yesraaj


People also ask

What is map () in C?

What is a map in C++? A C++ map is a way to store a key-value pair. A map can be declared as follows: #include <iostream> #include <map> map<int, int> sample_map; Each map entry consists of a pair: a key and a value.

Is there mapping in C?

There are also Mapping struct and union types from C and Mapping function pointers from C tutorials.

What is the syntax of map function?

The syntax for the map() method is as follows: arr. map(function(element, index, array){ }, this); The callback function() is called on each array element, and the map() method always passes the current element , the index of the current element, and the whole array object to it.


1 Answers

Here's an example:

#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;
}
like image 99
jason Avatar answered Oct 05 '22 23:10

jason