最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Any similar function like JS Array.prototype.map in c++? - Stack Overflow

programmeradmin5浏览0评论

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?

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?

Share Improve this question edited Dec 6, 2024 at 13:02 Donald Duck 8,89223 gold badges79 silver badges102 bronze badges asked Jun 28, 2018 at 3:35 Ray LiRay Li 1453 silver badges7 bronze badges 1
  • 1 A's constructor is private. I don't think you are showing us real code. – user2486888 Commented Jun 28, 2018 at 3:40
Add a ment  | 

2 Answers 2

Reset to default 9

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

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


发布评论

评论列表(0)

  1. 暂无评论