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

using http to handle a 404 error

This specific function is designed to fetch data under normal circumstances and to return a value of 0 in the event of a 404 error. function retrieveData(url) { if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); ...

Tips for verifying a login modal on an asp.net webforms using jQuery?

I am currently working on an asp.net webpage that utilizes a modal bootstrap for user login. Upon clicking the Login button, it should authenticate the user and initiate a server-side method called "ExportToZip" to download a zip file. My issue lies in ens ...

Tips for muting console.log output from a third-party iframe

As I work on developing a web application using NEXT.js, I am encountering an issue with a third party iframe that is generating numerous console logs. I am seeking a way to silence these outputs for the iframe. The code in question simply includes an < ...

Leveraging AJAX within a RESTful API in a Node.js environment to retrieve a JSON file and dynamically parse its contents according to the specific button selected on the front-end interface

Can anyone help me with understanding the communication process between server.js (Node.js) and the front-end JavaScript file? I am trying to implement AJAX as a RESTful API in the server to retrieve a JSON file, parse it based on specific button clicks in ...

Tips for enhancing the color saturations of cells that overlap in an HTML table

My goal is to enhance the color of overlapping cells in my HTML tables. For instance, when I click on cell 2, the .nextAll(':lt(5)') method will change the class of the next 4 cells. https://i.stack.imgur.com/mwv8x.png Next, clicking on cell 3 ...

Program written in the PHP language that generates output in the form of an

Currently, I am struggling with creating a PHP script that can generate JSON data in the specified format. Despite my efforts, I have not been successful in achieving this. { "authentication_credentials": { "api_key": "hybghhmimjij48fr847gt4fdf847v8 ...

Tips for inserting user input into an array and showcasing it

const [inputValue, setInputValue] = useState(""); return ( <input onChange={(event) => setInputValue(event.target.value)} /> <p>{inputValue}</p> ); I'm facing a problem where I need to take input from a user and store it in ...

Tips for manipulating observableArray information retrieved through the $.getJSON method

Recently, I've started using knockout.js and I'm really enjoying it so far! While working in MVC4, I encountered a small issue. I had successfully implemented kojs with static data, but now I need to work with data passed from a controller via JS ...

The API results are able to be displayed in the console, but unfortunately cannot be shown on the user interface. Any efforts to map the results will result in an Un

Can anyone help me troubleshoot an issue with displaying information from a free API on my page? I'm developing a cryptocurrency app using React, and while I can see the array data with console.log(response.data), I encounter an error when I try to se ...

Js: Automatically populating data into various input fields

I've encountered an issue with form input value injection using a <script> and POST requests. When I attempt to create another form with the same input field (same name and id), the value injection doesn't work, and troubleshooting has bee ...

Alternate routing based on conditions in Angular

I've used the "$urlRouterProvider.otherwise('{route here}')" syntax in angular to create a catch-all route in Angular UI-Router. One thing I'm curious about is whether it's possible to have conditional "otherwise" routing based o ...

"Can you help me understand how to establish a character limit for the MUI autocomplete

Hey everyone, I have successfully created an auto-complete feature using Material UI and an API. Now, I am facing a challenge where I need to limit the suggestions returned by the autocomplete to only show matches when the user types at least 3 letters. Ca ...

Need to get an item from a collection at the library?

Is it possible to import and use an object from a library? For instance, suppose we have a file named data.js with the following content: return { "name": "Testing" } In the file index.js, could we do something like this: const data = require('. ...

Invoke a function or variable based on a string parameter within a JavaScript/React function dynamically

I am currently exploring ways to dynamically call a function based on a string or reference a variable using a string. For example: import React, {useState} from 'react' const array = [ { text: 'count1', setFunctionName: &apo ...

Tips for customizing the selection tip of a custom cursor using CSS

I have integrated a color picker jquery plugin on my website to allow users to pick colors from an image. I made a modification in the CSS to change the cursor to an eyedropper icon. However, currently when clicking on the image, the color pointed by the u ...

Error: Unable to locate module: Material-UI - Please check the path and try again

Encountering this error: Error message: Failed to compile ./node_modules/@material-ui/core/Modal/Modal.js Module not found: Can't resolve '@babel/runtime/helpers/builtin/assertThisInitialized' in 'C:\Users\rifat\ ...

Best method for reverting react-native to previous version

Here's the dilemma I'm facing: I had a functional version of a react-native project that was running smoothly and committed to my git repository. Deciding to upgrade from react-native 0.26.3 to 0.28 led me into a tangled web of dependencies, so ...

The "maxlength" attribute does not function with the input type "number" in an HTML textbox

The maxlength attribute does not seem to be functioning properly when using type="number" ...

Prevent automatic jumping to input fields

Can someone help me with a problem related to the html input tag or primefaces p:input? I am facing an issue where the cursor always automatically jumps into the input field. The height of my page is such that scrolling is required, and the input field i ...

"Combining MySQL queries with PDO and designing dynamic web pages with

I am currently developing an application using the Twig templating library. My PDO statement returns the following array: Array ( [0] => Array ( [id] => 1 [artist] => Dena ...