在JS中,可以使用Array.prototype.map创建一个新数组,以在每个元素上调用函数,例如:
const elements = [{ text: 'hi1' }, { text: 'hi2' }, { text: 'hihi3'}];
const map = elements.map(element => element.text);
console.log(map); // Return ["hi1", "hi2", "hi3"]
因此在c ++中,给定了自定义类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
}
是否有任何动态函数返回vector of A's Text
或An array of A's text
?
答案 0 :(得分:2)
与您显示的JS代码段最接近的内容是这样的:
#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
调用范围[elements.begin(), elements.end())
中每个元素的lambda,将其结果分配给输出迭代器(在这种情况下为std::back_inserter
),并递增输出迭代器。
后插入器是一种特殊的迭代器,它使用其赋值运算符在容器上调用push_back
。
如果您关心push_back
完成的分配数量,则可以使用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
或std::vector::resize
(请注意-在这种情况下,您不能使用后置插入器):
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
答案 1 :(得分:1)
我试图制作一个自定义地图功能。希望您可以修改
import { LOGGED_IN, LOGGED_OUT, BASE_URL } from "./types"
export const sessionStatus = () => {
return dispatch => {
return fetch(`${BASE_URL}/api/v1/session/status`, {
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"Allow-Control-Allow-Origin": 'https://lets-meetup-app.herokuapp.com',
"Access-Control-Allow-Credentials": "true"
},
credentials: "include",
})
.then(resp => resp.json())
.then(data => {
data.logged_in ? dispatch({ type: LOGGED_IN, user: data.user.data.attributes, interests: data.interests }) : dispatch({ type: LOGGED_OUT, payload: data })
})
}
}