字符串相等性
Coddy 面向 Dart 开发者的 C++ 课程的第 7 课,共 48 课。
Dart 中的字符串 == 已经会比较内容,而 identical() 用于判断两个引用是否指向同一个对象。没有重写 operator == 的 Dart 类会退回到身份比较,而没有 operator== 的 C++ 类则完全不能使用 == 进行比较。C++ std::string 的相等比较会比较内容。原始指针的相等比较会比较地址;用户定义的类需要明确实现相等比较操作。
Dart
class Tag {
final String name;
Tag(this.name);
}
void main() {
var a = 'red';
var b = 'RED'.toLowerCase();
print('${a == b} ${Tag(a) == Tag(b)}');
}
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::string a="red",b="red";std::cout<<std::boolalpha<<(a==b)<<"\n";
}
分别跟踪每个程序。这些示例使用与任务不同的操作或数据来演示这一概念,不假设源代码和目标代码的输出相同。
挑战
简单输入:两行。返回这两个完整字符串是否相等,区分大小写。
在 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::cout<<std::boolalpha<<same(rows.size()>0?rows[0]:"",rows.size()>1?rows[1]:"")<<"\n";
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Dart 开发者的 C++中的所有课
自己练习: C++ 在线编译器