Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any similar function like JS Array.prototype.map in c++?

In JS, Array.prototype.map can be used for creating a new array for calling a function on every element like:

const elements = [{ text: 'hi1' }, { text: 'hi2' }, { text: 'hihi3'}];
const map = elements.map(element => element.text);
console.log(map); // Return ["hi1", "hi2", "hi3"]

So in c++, given a vector of custom class vector<A>

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

class A {
public:
  std::string text;
  A(std::string text) {
    this->text = text;
  }
};

int main() {
  vector<A> elements;
  for(int i = 0 ; i < 3 ; i++) {

    // Just Forming The Text String
    string input = "hi";
    string index = to_string(i);
    input += index;

    // Insert Element into Vector
    A element(input);
    elements.push_back(element);
  }

  // Here is the problem,
  // Is there any dynamic function to return Object's variable to a new array ?
  // So the result can be: 1. a vector of A's text OR 2. an array of A's text
}

Is there any dynamic function to return the vector of A's Text OR An array of A's text?

like image 867
Ray Li Avatar asked Jun 28 '18 03:06

Ray Li


People also ask

What is faster forEach or map?

There seems to be a very small difference between forEach() and map() with respect to speed. map() is faster, but these are so miniscule that it shouldn't affect your application's performance significantly. You can almost always use map() and other array methods like filter() and reduce() instead of using forEach().

What is array prototype map () useful for?

Array.prototype.map() The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

What is the difference between the array forEach method and array map method?

Differences between forEach() and map() methods:The forEach() method does not create a new array based on the given array. The map() method creates an entirely new array. The forEach() method returns “undefined“. The map() method returns the newly created array according to the provided callback function.

Is map an array C++?

C++ allows us a facility to create an array of maps. An array of maps is an array in which each element is a map on its own. Example 1: Below is the C++ program to implement an array of maps.


2 Answers

The closest thing to the JS snippet you've shown would be something like this:

#include <vector>
#include <string>
#include <algorithm>

class A
{
public:
    std::string text;

    // note: no constructor needed in this case!
};

int main()
{
    // using aggregate initialization instead of calling constructor and push_back
    std::vector<A> elements = {{"hi1"}, {"hi2"}, {"hi3"}};

    std::vector<std::string> texts;
    std::transform(elements.begin(), elements.end(), // input iterators
                   std::back_inserter(texts),        // output iterators (inserts at the end of texts)
                   [](const A& elem) { return elem.text; }); // lambda which maps A to std::string
}

std::transform calls the lambda for each element in range [elements.begin(), elements.end()), assigns its result to the output iterator (std::back_inserter in this case) and increments the output iterator.

Back inserter is a special iterator that calls push_back on a container in its assignment operator.

If you care about number of allocations done by push_back, you can use std::vector::reserve:

std::vector<std::string> texts;
texts.reserve(elements.size()); // make sure that enough storage is allocated up front
std::transform(elements.begin(), elements.end(), // input iterators
               std::back_inserter(texts),        // output iterators (inserts at the end of texts)
               [](const A& elem) { return elem.text; }); // lambda which maps A to std::string

or std::vector::resize (note - in this case you can't use back inserter):

std::vector<std::string> texts;
texts.resize(elements.size()); // create all std::string objects
std::transform(elements.begin(), elements.end(), // input iterators
               texts.begin(),                    // output iterator
               [](const A& elem) { return elem.text; }); // lambda which maps A to std::string
like image 170
joe_chip Avatar answered Oct 02 '22 23:10

joe_chip


I tried to make a custom map function. Hope you can modify it


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

template <typename T>
vector<T> map(const vector<T>& array, T (*func)(T))
{
    vector<T> result;
    for (const T& element : array) {
        result.push_back(func(element));
    }
    return result.reserve(array.size());
}

int main()
{
    vector<float> array = { 1.2, 3.2, 3.1 };

    auto newArray = map<float>(array, [](float e) {
        return e * 2;
    });

    for (auto& i : newArray) {
        cout << i;
    }
    return 0;
}


like image 34
llsanketll Avatar answered Oct 02 '22 23:10

llsanketll