正文
在STL的使用中,大量需要判断某个值是否存在。在不同的场合下,判断某个值是否存在可能使用了不同的技术。比如在通用的非STL成员函数find底层,判断某个值是否存在使用的是“相等”,也即“operator==”。再比如,在STL成员函数find底层,判断某个值是否存在使用的是“等价”。再再比如,在set容器的insert底层,判断某个值是否存在使用的是“等价”。这篇博客对STL关联容器中“相等”和“等价”做了简单对比介绍。
测试程序简介
下文的一个简单的测试程序中,定义了一个set容器,并为其制定了一个比较判别式。关于这个比较判别式,平时需要自己指定的场景相对较少,但比较判别式本身是一直存在的,即便程序员不指定,也会有一个默认比较判别式起相同的作用,而对于set容器,默认比较判别式是less。在测试程序中比较判别式忽略值的大小写。
依次向set中添加两个元素,“Abcd”和“abcd”,这两个值在不指定上文提及的比较判别式的情况下,可以以两个不同的值insert到set中。但是在本测试程序中,在判断set中是否存在“abcd”时,由于忽略的大小写,“Abcd”被认为和“abcd”等价,”abcd“添加失败。
还有一点需要解释,find函数有两个版本,标准算法的find函数和容器的成员函数find,它们用的是不同的技术。标准算法的find函数基于相等来判断某个值是否存在,而容器的成员函数find基于容器实例的比较判别式来判断某个值是否存在,在测试程序中就是为set指定的Aastrcmp。
测试程序
//common.h
#ifndef _COMMON_H_
#define _COMMON_H_
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <utility>
#include <algorithm>
#include <vector>
#include <iterator>
#include <sys/time.h>
using namespace std;
#endif
//equality_vs_equivalence.cpp
#include "common.h"
struct Aastrcmp:public binary_function<string, string, bool>
{
bool operator()(const string& str1, const string& str2)
{
return strcasecmp(str1.c_str(), str2.c_str());
}
};
int main(void)
{
set<string, Aastrcmp> test_set;
test_set.insert("Abcd");
test_set.insert("abcd");
printf("test_set.size(): %lu\n", test_set.size());
if (find(test_set.begin(), test_set.end(), "Abcd") == test_set.end())
{
printf("Abcd not found by non-member find\n");
}
else
{
printf("Abcd found by non-member find\n");
}
if (find(test_set.begin(), test_set.end(), "abcd") == test_set.end())
{
printf("abcd not found by non-member find\n");
}
else
{
printf("abcd found by non-member find\n");
}
if (test_set.find("Abcd") == test_set.end())
{
printf("Abcd not found by member find\n");
}
else
{
printf("Abcd found by member find\n");
}
if (test_set.find("abcd") == test_set.end())
{
printf("abcd not found by member find\n");
}
else
{
printf("abcd found by member find\n");
}
return 0;
}
编译和执行结果
g++ -o equality_vs_equivalence equality_vs_equivalence.cpp -O0 -g -Wall -std=c++11
./equality_vs_equivalence
test_set.size(): 1
Abcd found by non-member find
abcd not found by non-member find
Abcd found by member find
abcd found by member find