我正在调查地图如何处理自定义类型,我遇到了一些奇怪的行为。
我创建了一个自定义类型'ComplexType',它有一个成员,一个指向int的指针。 我首先使用此int的值进行比较,这给出了预期的行为。
#include <iostream>
#include <map>
struct ComplexType
{
ComplexType(int i): index(new int(i)){
};
ComplexType(const ComplexType& cT): index(new int(*cT.index)){
}
~ComplexType(){
if(index){
delete index;
}
}
bool operator<(const ComplexType cT) const
{
return *index < *cT.index;
}
int* index;
};
int main(){
int pi[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 8};
std::map< ComplexType , int > container;
for(int i = 0; i < 12; ++i){
container[ComplexType(i)] = pi[i];
}
std::cout << "Loop map, size: " << container.size() << std::endl;
for(auto it = container.begin();it != container.end(); it++){
std::cout << "Show index map, size: " << container.size() << std::endl;
std::cout << *it->first.index << std::endl;
}
return 0;
}
输出:
Loop map, size: 12
Show index map, size: 12
0
Show index map, size: 12
1
Show index map, size: 12
2
Show index map, size: 12
3
Show index map, size: 12
4
Show index map, size: 12
5
Show index map, size: 12
6
Show index map, size: 12
7
Show index map, size: 12
8
Show index map, size: 12
9
Show index map, size: 12
10
Show index map, size: 12
11
现在我改变了比较函数以比较指针的地址。
#include <iostream>
#include <map>
struct ComplexType
{
ComplexType(int i): index(new int(i)){
};
ComplexType(const ComplexType& cT): index(new int(*cT.index)){
}
~ComplexType(){
if(index){
delete index;
}
}
bool operator<(const ComplexType cT) const
{
return index < cT.index;
}
int* index;
};
int main(){
int pi[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 8};
std::map< ComplexType , int > container;
for(int i = 0; i < 12; ++i){
container[ComplexType(i)] = pi[i];
}
std::cout << "Loop map, size: " << container.size() << std::endl;
for(auto it = container.begin();it != container.end(); it++){
std::cout << "Show index map, size: " << container.size() << std::endl;
std::cout << *it->first.index << std::endl;
}
return 0;
}
我希望这会导致基于指针在堆上的地址的随机顺序。相反,我得到了以下内容:
Loop map, size: 12
Show index map, size: 12
1
Show index map, size: 12
0
我使用g ++(GCC)5.3.0编译
\randomness map>g++ -std=c++11 -o mapConstructionComplexType mapConstructionComplexType.cpp
\randomness map>g++ -std=c++11 -o mapConstructionComplexTypePointerCmp mapConstructionComplexTypePointerCmp.cpp
任何人都可以解释这种奇怪的行为吗?