存储 (x, y) 与设置的坐标

Storing (x, y) Coordinates with set

本文关键字:设置 坐标 存储      更新时间:2023-10-16

我需要帮助将 (x, y) 坐标组存储在一个集合中。 我存储它的方式是

set<int> s;
s.insert( (1, 1) );
s.insert( (1, 3) );
s.insert( (3, 1) );
s.insert( (3, 3) );
for (auto x: s) {
cout << x << endl;
}

但它没有打印出 (1, 1), (1, 3).... 并打印出 1、3。

我对 c++ 很陌生,所以如果有人能给我关于如何使用集合存储这些值的建议,我将不胜感激!

代码发生的情况如下:

s属于std::set<int>类型,因此适用于存储int类型的变量。

调用函数std::set<int>::insert需要一个类型int的参数。如果你这样做s.insert((1, 3))你实际上不会插入一对,而是使用逗号运算符。它的工作原理是这样的:在表达式a, b中,计算表达式a,然后计算表达式b,并将表达式b的结果作为整个表达式的结果返回。您可以在此处阅读有关它的更多信息:逗号运算符如何工作。

因此,s.insert((1, 3))结果s.insert(3)3入到s中。

要实现所需的行为,您可以使用std::pair,在标头utility中定义。一种可能的方法如下:

std::set<std::pair<int, int>> s;
s.insert(std::make_pair(1, 1));
s.insert(std::make_pair(1, 3));
s.insert(std::make_pair(3, 1));
s.insert(std::make_pair(3, 3));
for (const auto& e : s) 
std::cout << "(" << e.first << ", " << e.second << ") ";

输出:

(1, 1) (1, 3) (3,

1) (3, 3)

使用初始值设定项列表插入对的另一种语法如下:

s.insert({1, 3});

如果要就地构造对而不是构造和插入它们,则可以按如下方式使用std::set::emplace

s.emplace(1, 3);

我想你的意思是使用对,pair是一个类将一对值耦合在一起,可以转换为坐标x,y

set<std::pair<int,int>> s;
s.insert({ 1, 1 });
s.insert({ 1, 3 });
s.insert({ 3, 1 });
s.insert({ 3, 3 });
for (auto x : s) {
std::cout << x.first<< " "<<x.second << std::endl;
}
// to print the first & the last element
auto start = s.begin();
auto last=s.rbegin();
std::cout << start->first << " " << start->second << " " << last->first << " " << last->second<<'n';
// for the nth element
int n=2;
auto nelement=std::next(s.begin(), n);
std::cout<<nelement->first<<" "<<nelement->second;
set<int>

只能存储一个int,而不能存储两个(在单个insert操作中)。如果你写s.insert( (1, 3) );你显然是在尝试插入 2,这行不通。它似乎以某种方式起作用,但实际上语法正在对你玩一个讨厌的把戏!

在这种情况下(1, 3)表达式是使用逗号运算符,它的作用是:计算 1(它是,嗯,1),扔掉它,然后计算 3,这显然是 3,这就是返回的内容: 3.所以你的陈述实际上等同于s.insert(3);.Taht是为什么你不会得到编译错误。但显然这不是你想要的。

要解决此问题,您必须使用一次存储两个值的集合。有一种数据类型,叫做std::p air!

所以你可以像这样声明它

set<std::pair<int,int>> s;

并将数据插入其中,例如

s.insert({1, 3});