STL之set的应用

一个机器人在雪地上行走,按如下方式

1)向前行进随机的步数(每次步长想等),然后右转90度

2)如此重复6次

测试用例:2 3 5 5 4 2      true有交叉

                   1 3 4 2 6 2      true有交叉

                   1 6 5 4 3 2      false无交叉

set可以去重复,考虑把所有经过的端点都存入set,如果set的长度等于总节点数,就证明没有重复。

注意:对set进行应用,当typename为struct时,一直会报错,看错误提示必须对“<”进行重载例,如果不重载会报错如

struct location {
    int x, y;
};   

set<location> st;             //会报错

需要添加的函数为:

bool operator < (const location & a, const location & b) {
    return a.x < b.x;
}

如果还有更方便的能发出来大家交流交流

主程序:

// exam.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
#include<string>
#include<stdio.h>
#include<set>
#include<vector>
#include<algorithm>
using namespace std;


struct location {
    int x, y;
}loc;
bool operator < (const location & a, const location & b) {
    if(a.x!=b.x)  return a.x < b.x;
    else return a.y < b.y;
}
location a = { 0,0 };
void move(int flag) {
        if (flag % 4 == 1) {//上
            a.x = a.x;
            a.y = a.y + 1;
        }
        else if (flag % 4 == 2) {//右
            a.x = a.x + 1;
            a.y = a.y;
        }
        else if (flag % 4 == 3) {//下
            a.y = a.y - 1;
            a.x = a.x;
        }
        else if (flag % 4 == 0) {//左
            a.x = a.x - 1;
            a.y = a.y;
        }
    }

int main()
{    

    set<location> st;
    st.insert(a);
    int len[6],sum_d=1;
    for (int i = 0;i < 6;i++) {
        scanf_s("%d", &len[i]);
        for (int j = 1;j <= len[i];j++) {
            move(i+1);
            st.insert(a);
        }
        sum_d += len[i];
    }
    printf("%d  %d", sum_d, st.size());
    return 0;
}
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值