Is there a C++ equivalent to the JS Array.prototype.map method?

When it comes to JavaScript, Array.prototype.map is a powerful tool for creating a new array by applying a function to each element. Consider the following example:

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

Now, in C++, suppose we have 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++) {

    // Creating the Text String
    string input = "hi";
    string index = to_string(i);
    input += index;

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

  // Here lies the challenge,
  // Is there a dynamic function that can be used to return Object's variable to a new array?
  // The desired result could be either a vector of A's text or an array of A's text.
}

Is there any method available to achieve this task and return the values as described?

Answer №1

If you're looking for a JavaScript snippet similar to the one you shared, consider the following C++ code:

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

class A
{
public:
    std::string text;
};

int main()
{
    std::vector<A> elements = {{"hi1"}, {"hi2"}, {"hi3"}};

    std::vector<std::string> texts;
    std::transform(elements.begin(), elements.end(),
                   std::back_inserter(texts),
                   [](const A& elem) { return elem.text; });
}

std::transform will apply the lambda function to each element in the range

[elements.begin(), elements.end())
.

To reduce allocations with push_back, you can use std::vector::reserve:

std::vector<std::string> texts;
texts.reserve(elements.size());
std::transform(elements.begin(), elements.end(),
               std::back_inserter(texts),
               [](const A& elem) { return elem.text; });

Alternatively, you can preallocate memory using std::vector::resize:

std::vector<std::string> texts;
texts.resize(elements.size());
std::transform(elements.begin(), elements.end(),
               texts.begin(),
               [](const A& elem) { return elem.text; });

Answer №2

Looking for a customized mapping function? Give this code a try and feel free to tailor it according to your needs.


#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;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to pass the table ID from one webpage to another using jQuery

I am dealing with 3 variations of tables that each have unique id values. My challenge is transitioning from one page to another and landing on the precise table within the new page. I'm uncertain about how to achieve this using jQuery. <table id= ...

Script designed to track modifications on a specific webpage

Attempting to purchase items online has become a frustrating challenge as stock seems to disappear within minutes of being added :/ I am currently working on creating a custom grease/tampermonkey script to monitor the page and notify me when products beco ...

Retrieve the value of a specific key from various files and then generate a random quantity to be written into another file

I am dealing with numerous files that have a specific format: {"reviewerID": "A4IL0CLL27Q33", "asin": "104800001X", "reviewerName": "D. Brennan", "helpful": [0, 1], "reviewText": "I hate it when my shirt collars, not otherwise secured in place by buttons, ...

Bootstrap 5 does not support tab navigation functionality

I created a new HTML page, and I encountered an issue while trying to enable tabs using JavaScript. <html> <head> <title>Excel Viewer</title> <link hr ...

converting time stamps to written text

Is there a JavaScript library available that can convert a timestamp (Date Java class value) to text? For example: Just two minutes ago 4 hours back 23 August 2009 Does such a library exist? If not, I'll take on the challenge of implementing it ...

How do I save the value of a callback function in Vue data?

#I am facing an issue where the value of this.zuobiao is not being logged after I call the function that assigns a value to it. Why is this happening? getUserProfile() { uni.getLocation({ type: 'gcj02 ', geocode: true, success: (res) => ...

A guide to retrieving the contents of an input field based on its assigned value and name attributes through Javascript

Can anyone help me with selecting an input element in my HTML code? Here is the input I want to select: <input id="tb-radio-gym_custom_radio-10ce67e3" type="radio" value="OUI" name="form_fields[gym_custom_radio]" data-price-inc="0" checked="checked"> ...

Ways to stop the default action in a confirm dialog while using Angular JS

Within my save function, I have the following: $scope.saveData = function () { if (confirm("Are you sure you want to save") === false) { return } // do saving When using the above code and clicking "yes," I encounter an error. Interestin ...

What is the best way to create a slideshow using an IFrame?

Currently seeking a solution for an iframe slideshow that can smoothly transition between multiple HTML iframes. I have a total of 5 iframes that need to rotate automatically and continuously. Any suggestions on how to build a lively and dynamic iframe sl ...

Ensure the Json object contains an integer

I am facing an issue where I receive a Json data in dictionary format. Below is a sample json: Receivedtext: { "x": "pricef", "b": "usd", "ds": [ "tpr", "avgp", "mcap", "ppc7D", "ppc12h", "ppc4h", "ppc24h" ], "data": ...

What are some alternative methods for organizing folder structure in Express Handlebars when managing views?

Is there a more efficient way to render HTML files without constantly needing them to have different names? I'm looking for a method where handlebars can identify which file in which folder to render, without encountering conflicts with files of the s ...

What are the steps to get the Dropdown Button to function in HTML and CSS?

Currently, I am in the process of constructing a website and have set it up so that when the window width is less than 768px, the navbar collapses into a vertical orientation. The issue I am facing is that even though the navbar collapses, the individual i ...

Animation triggered by scrolling is not functioning/displaying div

I'm attempting to make a div fade up when it enters the viewport by using the library found at https://github.com/michalsnik/aos Unfortunately, all that seems to happen is that the div gets hidden. In the head section of my HTML file, I've refe ...

Leveraging Vue js components while utilizing it from a content delivery network (CDN

I'm attempting to utilize the ButtonCounter component as a demonstration (source: https://vuejs.org/guide/essentials/component-basics.html#defining-a-component), but I am facing difficulties in getting it to function properly. I am utilizing Vue.js 3 ...

Can JavaScript be used to modify the headers of an HTTP request?

Can JavaScript be used to modify or establish HTTP request headers? ...

Exploring the world of SPA: Implementing Data Transfer Objects

Considering implementing a Single Page Application (SPA) using a JavaScript framework like Angular JS. Currently, I have multiple existing Web APIs containing the necessary information for the app. I need to add another API that will handle new data and re ...

A guide to incorporating nested loops with the map method in React JS

I've come across numerous threads addressing the nested loop using map in React JS issue, but I'm still struggling to implement it in my code. Despite multiple attempts, I keep encountering errors. Here are some topics I've explored but cou ...

Error message: Invalid credentials for Twitter API authentication

My attempts to post a tweet seem to be failing for some reason. I suspect that the issue might be related to the signature string, but from following Twitter's instructions on signing requests, everything appears correct. Here is the code snippet I ...

"Fill the designated area on the webpage with data retrieved from an external script

In my current project, I am utilizing Angular and JQuery to enhance re-usability by setting the header and footer as partials. However, I encountered an issue where I needed certain javascript functions to be executed within the footer upon loading - a tas ...

Finding the best way to transfer text between DIV elements?

I have a dilemma involving two DIV elements positioned absolutely on the sides of an HTML page, much like this EXAMPLE: <div class="left"> </div> <div class="right"> </div> These are styled using the following CSS: .left{ pos ...