映射与查找
Coddy 面向 JavaScript 开发者的 C++ 课程的第 14 课,共 48 课。
JavaScript Map 会按照插入顺序遍历键,使用 get 查询不存在的键时会返回 undefined,且不会改变映射。C++ 的 std::map 则会对键进行排序。它的下标运算符 m[key] 会为不存在的键插入默认值,因此读取也可能使映射增大;find 和 count 则会进行不插入元素的查询。
JavaScript
const counts = new Map([["pens", 0], ["ink", 2]]);
console.log(counts.has("pens"), counts.get("pads"));
console.log([...counts.keys()].join(","), counts.size);
C++
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
int main(){
std::map<std::string,int> m{{"pens",0},{"ink",2}};
std::cout<<m.count("pads")<<" "<<m["pads"]<<" "<<m.size()<<" "<<m.begin()->first<<"\n";
}
分别跟踪每个程序。这些示例使用与任务不同的操作或数据来展示这个概念,不要假设源程序和目标程序的输出相同。
挑战
简单输入:以空格分隔的单词。返回按字典序排列的单词频次,用空格连接,格式为 word:count;如果没有单词,则返回 empty。
在 exercise.hpp 和 exercise.cpp 中实现已声明的 API。这两个文件都可以编辑;请保留公共签名。锁定的 main.cpp 会读取标准输入并直接调用 API。它还会在说明中注明的情况下独立检查公共 API 的行为。在 API 中返回值,不要打印。整数输入和结果都在有符号 int 的范围内;除非另有说明,文本均为 ASCII。
亲手试试
#include "exercise.hpp"
#include <iostream>
int main(){
std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);std::vector<std::string>v;std::string w;while(in>>w)v.push_back(w);std::cout<<frequencies(v)<<"\n";
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 JavaScript 开发者的 C++中的所有课
自己练习: C++ 在线编译器