存储 (x, y) 与设置的坐标
Storing (x, y) Coordinates with set
我需要帮助将 (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});
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 在C++/Linux中设置单调时钟的一些技巧
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- QGraphicsPolygonItem在拖动时未更新QPolygonF坐标
- 嵌套在类中时无法设置成员数据
- 需要帮助设置在C++中使用的Potrace
- 如何在自删除后将对象设置为nullptr
- 将指针设置为"nullptr"并不能防止双重删除?
- 如何在Ubuntu中使用cmake设置qt4
- ld:bind_at_load和-bitcode_bundle(Xcode设置ENABLE_bitcode=YES)不能
- 我想制作设置鼠标回调函数,以便在仍然按下鼠标左键时连续传递坐标
- 如何设置GLFW窗口的(0,0)坐标位置
- 存储 (x, y) 与设置的坐标
- 如何在QLabel的特定坐标中设置QPixmap
- 我应该如何使用 X11、motif、绘图区域和 c++ 来设置绘图区域 (X,Y) 坐标 (0,0)
- 设置OpenGL绘图的坐标系统
- Qt:在Widget内设置QLabel坐标
- 如何在OpenCV中设置KMEANS_USE_INITIAL_LABELS的坐标
- 为带有3d对象的图形设置合适的坐标
- 如何在DirectX 9中设置左上角坐标