vector 与 map
std::vector 参数接受普通数组。C++ 返回的 vector 或 map 会变成一个带有自己方法的对象。
mean 接受 std::vector<double>,main.js 传给它一个数组。split 返回 std::vector<std::string>,m.toArray 会把它变成数组;m 是 initNative() 解析得到的模块。
countWords 返回 std::map<std::string, int>,用 get(key) 和 size() 读取。在 Web Worker 中,返回的 vector 本身已经是普通数组;toArray 两者都接受,所以同一行代码在那里也能运行。
试一试
按空格拆分一个句子,再查找一个不在 counts 中的单词。[■]native.h1#pragma once
#include <map>
#include <string>
#include <vector>
// A std::vector parameter takes a plain array.
double mean(const std::vector<double> &values);
// A returned vector or map arrives as an object of its own;
// the module's toArray makes an array of a vector.
std::vector<std::string> split(std::string text, char separator);
std::map<std::string, int> countWords(const std::string &text);
[■]main.js2import {
initNative, mean, split, countWords,
} from './native/native.h';
const m = await initNative();
console.log('mean:', await mean([3, 4, 8]));
const colors = await split('red,green,blue', ',');
console.log(await m.toArray(colors));
const counts = await countWords('the cat and the hat');
console.log('the:', await counts.get('the'));