栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ 如何使用结构体作为map的key

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ 如何使用结构体作为map的key

#include 
#include 
#include 

using namespace std;

struct StructTest
{
	std::string str1;
	std::string str2;
	double diameter;
	double length;

	StructTest() : str1(""), str2(""), diameter(0.), length(0.) {}

	StructTest(const std::string& str1, const std::string& str2, double diameter,
		double length)
		: str1(str1), str2(str1), diameter(diameter), length(length)
	{
	}

	bool operator = (const StructTest& c) const
	{
		if (!str1.compare(c.str1) && !str2.compare(c.str2) &&  abs(diameter - c.diameter) < 0.0001
			&& abs(length - c.length) < 0.0001)
		{
			return true;
		}
		return false;
	}


	bool operator < (const StructTest& c) const
	{
		if (str1 < c.str1)
		{
			return str1 < c.str1;
		}
		if (str2 < c.str2)
		{
			return str2 < c.str2;
		}
		if (diameter < c.diameter)
		{
			return diameter < c.diameter;
		}
		if (length < c.length)
		{
			return length < c.length;
		}
		return false;
	}
};

int main()
{
	map test1;
	StructTest tag;
	tag.str1 = "chen";
	tag.str2 = "111"; 
	tag.diameter = 1;
	tag.length = 100;

	test1.insert(make_pair(tag, 22));

	std::cout << "find new onen";
	StructTest key;
	if (test1.find(key) == test1.end())
	{
		std::cout << "not findn";
	}
	else
	{
		std::cout << "findn";
	}

	std::cout << "nfind itself n";
	if (test1.find(tag) == test1.end())
	{
		std::cout << "not findn";
	}
	else
	{
		std::cout << "findn";
	}

	getchar();

	return 0;
	
}

输出

 

之前也没有使用map做过类似的功能,调BUG的过程中发现,如果在结构体中没有写 < 的重载,直接使用map的find会有问题。

当然这个和map本身的结构有关

<<<未完待续>>>

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/352673.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号