简体   繁体   English

如何在C ++中存储一对数字?

[英]How can I store a pair of numbers in C++?

I'm trying to learn C++ and right now I'm writing a program that needs to output a list of pairs of integers. 我正在尝试学习C ++,现在我正在编写一个需要输出整数对列表的程序。

What is the best way to handle this? 处理这个问题的最佳方法是什么? I don't have the boost library available on our linux computers at school, so I don't believe I can use boost::tuple. 我在学校的linux电脑上没有可用的升级库,所以我不相信我可以使用boost :: tuple。

Any suggestions? 有什么建议么?

Have a look at std::pair<object, object> 看看std::pair<object, object>

EDIT: 编辑:

It's standard C++ and part of what is known as the STL (Standard Template Library). 它是标准的C ++,也是所谓的STL(标准模板库)的一部分。 It's a collection of nice data structures that are generic (ie may be used to store any C++ object type). 它是一组通用的好数据结构(即可用于存储任何C ++对象类型)。 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. 它基本上是一个成员“first”和“second”的对象,它指的是你存储在它们中的第一个和第二个对象(任何类型!)。

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 of pair<int, int> : vector<pair<int, int> > myList . 因此,只需声明一个pair<int, int>或更好的数组,使用另一个名为“vector”的STL类型来生成动态大小的pair<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 a map<int, int> myMap !!! 使用它就像#include <map>一样简单,并声明一个map<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::mapstd::multimap

Use std::pair? 使用std :: pair?

#include <utility>
#include <iostream>

int main() {
    std::pair <int, int> p = std::make_pair( 1, 2 );
    std::cout << p.first << " " << p.second << std::endl;
}

You can make a vector of pairs: 你可以制作一对矢量:

typedef std::pair <int, int> IntPair;

...

std::vector <IntPair> pairs;
pairs.push_back( std::make_pair( 1, 2 ) );
pairs.push_back( std::make_pair( 3, 4 ) );

While std::pair is the best approach to use, I'm surprised nobody mentioned pre-stl solution: 虽然std :: pair是最好的使用方法,但我很惊讶没人提到pre-stl解决方案:

struct Pair {
    int first;
    int second;
};

It is worrying that people think that they need boost for such a trivial problem. 令人担忧的是,人们认为他们需要为这样一个微不足道的问题提供帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM