如何在 C++ 中存储一对数字?
我正在尝试学习 C++,现在我正在编写一个需要输出整数对列表的程序。
处理这个问题的最佳方法是什么?我在学校的 Linux 计算机上没有可用的 boost 库,所以我不相信我可以使用 boost::tuple。
有什么建议吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看看
std::pair
< /a>编辑:
它是标准 C++,也是 STL(标准模板库)的一部分。它是通用的良好数据结构的集合(即可用于存储任何 C++ 对象类型)。这种特殊的结构用于将“元组”或一对数字存储在一起。它基本上是一个具有成员“first”和“second”的对象,它们引用您存储在其中的第一个和第二个对象(任何类型!)。
因此,只需声明一个
pair
数组,或者更好的是,使用另一种称为“向量”的 STL 类型来创建一个动态大小的pair 列表。
:向量 > myList
.嘿你知道什么!动态大小的对列表已经存在,它被称为映射!使用它就像
#include
并声明一个
map 一样简单。我的地图!!!
编辑:
是的,正如所指出的,地图很好地将一个对象“映射”到另一个对象,因此您不能有重复的左侧值。如果没问题,那么地图就是您要寻找的,否则坚持对向量......或者看看多重地图。
std::map
,std::multimap
Have a look at
std::pair<object, object>
EDIT:
It's standard C++ and part of what is known as the STL (Standard Template Library). It's a collection of nice data structures that are generic (i.e. may be used to store any C++ object type). This particular structure is used to store a "tuple" or a pair of numbers together. It's basically an object with members "first" and "second" that refer to the first and second objects (of any type!) that you store in them.
So just declare an array of
pair<int, int>
, or better yet, use another STL type called the "vector" to make a dynamically-sized list ofpair<int, int>
:vector<pair<int, int> > myList
.Hey what do you know! A dynamically-sized list of pairs already exists and it's called a map! Using it is as simple as
#include <map>
and declaring amap<int, int> myMap
!!!EDIT:
Yes, as pointed out, a map well "maps" one object to another, so you cannot have repeated lefthand-side values. If that's fine then a map is what you're looking for, otherwise stick to the vector of pair.... or take a look at multimaps.
std::map
,std::multimap
使用 std::pair?
您可以创建一个向量对:
Use std::pair?
You can make a vector of pairs:
虽然 std::pair 是最好的使用方法,但我很惊讶没有人提到 pre-stl 解决方案:
令人担忧的是,人们认为他们需要 boost 来解决这样一个微不足道的问题。
While std::pair is the best approach to use, I'm surprised nobody mentioned pre-stl solution:
It is worrying that people think that they need boost for such a trivial problem.