diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/.clang-format" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/.clang-format" new file mode 100644 index 0000000000000000000000000000000000000000..8d709151f7012d4b1569304afb200af0ce97e47d --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/.clang-format" @@ -0,0 +1,24 @@ +--- +BasedOnStyle: Google +AlignAfterOpenBracket: 'AlwaysBreak' +AllowAllConstructorInitializersOnNextLine: 'false' +AllowAllParametersOfDeclarationOnNextLine: 'false' +AlignConsecutiveMacros: 'true' +AllowShortCaseLabelsOnASingleLine: 'true' +AllowShortFunctionsOnASingleLine: 'None' +AllowShortIfStatementsOnASingleLine: 'Never' +AllowShortLoopsOnASingleLine: 'false' +BreakBeforeBraces: Allman +BinPackArguments: 'false' +BinPackParameters: 'false' +Cpp11BracedListStyle: 'false' +ColumnLimit: 125 +NamespaceIndentation: All +SpaceAfterTemplateKeyword: 'false' +SpaceBeforeCtorInitializerColon: 'true' +SpaceBeforeInheritanceColon: 'true' +SpaceBeforeParens: ControlStatements +SpaceBeforeRangeBasedForLoopColon: 'true' +SpaceInEmptyBlock: true +Standard: 'Latest' +... diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/.clang-tidy" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/.clang-tidy" new file mode 100644 index 0000000000000000000000000000000000000000..d85b250a5e402bd6911755b0f44ac98dcc8aec4c --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/.clang-tidy" @@ -0,0 +1,6 @@ +--- +Checks: '*,-fuchsia-*,-google-*,-zircon-*,-abseil-*,-modernize-use-trailing-return-type,-llvm-*,-llvmlibc-*' +CheckOptions: [{ key: misc-non-private-member-variables-in-classes, value: IgnoreClassesWithAllMemberVariablesBeingPublic }] +WarningsAsErrors: '*' +HeaderFilterRegex: '' +FormatStyle: none diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/.github/ISSUE_TEMPLATE/bug_report.md" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/.github/ISSUE_TEMPLATE/bug_report.md" new file mode 100644 index 0000000000000000000000000000000000000000..7532789bdb4353ca0a42dcdfa23a38093f26f7b2 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/.github/ISSUE_TEMPLATE/bug_report.md" @@ -0,0 +1,33 @@ +--- +name: Bug report +about: Create a report to help me improve +title: "[BUG]" +labels: bug +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: + +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Desktop (please complete the following information):** + +* OS: [e.g. Windows] +* Version [e.g. 10] + +**Additional context** +Add any other context about the problem here. diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/.github/ISSUE_TEMPLATE/custom.md" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/.github/ISSUE_TEMPLATE/custom.md" new file mode 100644 index 0000000000000000000000000000000000000000..48d5f81fa422964dd1eea360efdecfc5dc9a6c87 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/.github/ISSUE_TEMPLATE/custom.md" @@ -0,0 +1,10 @@ +--- +name: Custom issue template +about: Describe this issue template's purpose here. +title: '' +labels: '' +assignees: '' + +--- + + diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/.github/ISSUE_TEMPLATE/feature_request.md" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/.github/ISSUE_TEMPLATE/feature_request.md" new file mode 100644 index 0000000000000000000000000000000000000000..e75a04b91982fd762ac1b841b1bcffc806cc442f --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/.github/ISSUE_TEMPLATE/feature_request.md" @@ -0,0 +1,25 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: "[FEATURE]" +labels: enhancement +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated +when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Provide usage examples** +A few examples of how the feature should be used. Please make sure they are clear +and concise. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/.github/workflows/macos.yml" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/.github/workflows/macos.yml" new file mode 100644 index 0000000000000000000000000000000000000000..e20fc40b3dd8b6ae6e9801a6e9bb35f97b4388ee --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/.github/workflows/macos.yml" @@ -0,0 +1,53 @@ +name: MacOS + +on: + push: + branches: [ master ] + pull_request: + branches: [ master ] + +env: + BUILD_TYPE: Release + INSTALL_LOCATION: .local + +jobs: + build: + + runs-on: macos-latest + if: "!contains(github.event.head_commit.message, '[skip ci]') && !contains(github.event.head_commit.message, '[ci skip]')" + + steps: + - uses: actions/checkout@v2 + + - name: cache dependencies + uses: actions/cache@v2 + id: cache + with: + path: ${{ github.workspace }}/${{ env.INSTALL_LOCATION }} + key: ${{ runner.os }}-dependencies + + - name: install GoogleTest + if: ${{ steps.cache.output.cache-hit != 'true' }} + run: | + cd .. + git clone https://github.com/google/googletest.git --branch release-1.10.0 + cd googletest + cmake -Bbuild -DCMAKE_INSTALL_PREFIX=$GITHUB_WORKSPACE/$INSTALL_LOCATION + cmake --build build --config Release + cmake --build build --target install --config Release + cd ../modern-cpp-template + + - name: configure + run: cmake -Bbuild -DCMAKE_INSTALL_PREFIX=$GITHUB_WORKSPACE/$INSTALL_LOCATION + + - name: build + run: cmake --build build --config $BUILD_TYPE -j4 + + - name: run tests + run: | + cd build + ctest -C $BUILD_TYPE -VV + + - name: install project + run: cmake --build build --target install --config Release + diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/.github/workflows/release.yml" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/.github/workflows/release.yml" new file mode 100644 index 0000000000000000000000000000000000000000..433c451c70012e7313d5fa387fe0fdfae800ac25 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/.github/workflows/release.yml" @@ -0,0 +1,189 @@ +name: Release + +on: + push: + tags: + - 'v*' + +env: + PROJECT_NAME: "modern-cpp-template" + BUILD_TYPE: Release + +jobs: + build: + name: ${{ matrix.config.name }} + runs-on: ${{ matrix.config.os }} + strategy: + fail-fast: false + matrix: + config: + - { + name: "Windows Latest MSVC", + artifact_ext: '.zip', + os: windows-latest, + cc: "cl", + cxx: "cl", + environment_script: "C:/Program Files (x86)/Microsoft Visual Studio/2019/Enterprise/VC/Auxiliary/Build/vcvars64.bat", + } + - { + name: "Ubuntu Latest GCC", + artifact_ext: '.tar.gz', + os: ubuntu-latest, + cc: "gcc", + cxx: "g++", + } + - { + name: "macOS Latest Clang", + artifact_ext: '.tar.gz', + os: macos-latest, + cc: "clang", + cxx: "clang++", + } + + steps: + - name: set version name (Windows) + id: version_win + if: ${{ runner.os == 'Windows' }} + run: | + $TAG = (${env:GITHUB_REF} -replace 'refs/tags/', '') + echo "::set-output name=name::$TAG" + + - name: set version name + id: version + if: ${{ runner.os != 'Windows' }} + run: echo ::set-output name=name::${GITHUB_REF#refs/tags/} + + - name: Checkout + uses: actions/checkout@v2 + with: + submodules: recursive + + - name: cache dependencies + uses: actions/cache@v2 + id: cache + with: + path: ${{ github.HOME }}/.local + key: ${{ runner.os }}-dependencies + + - name: install GoogleTest + if: ${{ steps.cache.output.cache-hit != 'true' }} + run: | + cd .. + git clone https://github.com/google/googletest.git --branch release-1.10.0 + cd googletest + cmake -Bbuild -DCMAKE_INSTALL_PREFIX="$HOME/.local" -Dgtest_force_shared_crt=1 + cmake --build build --config Release + cmake --build build --target install --config Release + cd ../modern-cpp-template + + - name: configure + run: cmake -Bbuild -DCMAKE_INSTALL_PREFIX="$HOME/.local" + + - name: build + run: cmake --build build --config "$env:BUILD_TYPE" -j4 + + - name: run tests + run: | + cd build + ctest -C "$env:BUILD_TYPE" -VV + + # for a release not containing directly the source code, replace the files archived + # with the actual files needed (i.e. *.lib/*.a and *.h(pp)) + + - name: generate archive (Windows) + if: ${{ runner.os == 'Windows' }} + run: | + rmdir -r -fo build + 7z a -tzip $HOME/artifact.zip * + + + - name: generate archive + if: ${{ runner.os != 'Windows' }} + run: | + rm -rf build + tar -cvzf $HOME/artifact.tar.gz . + + - name: upload artifacts + uses: actions/upload-artifact@v2 + if: ${{ runner.os == 'Windows' }} + with: + name: ${{ runner.os }}-${{ steps.version_win.outputs.name }} + path: '~/artifact.*' + + - name: upload artifacts + uses: actions/upload-artifact@v2 + if: ${{ runner.os != 'Windows' }} + with: + name: ${{ runner.os }}-${{ steps.version.outputs.name }} + path: '~/artifact.*' + + release: + if: contains(github.ref, 'tags/v') + runs-on: ubuntu-latest + needs: build + + steps: + - name: set version name + id: version + run: echo ::set-output name=name::${GITHUB_REF#refs/tags/} + + - name: create release + id: create_release + uses: actions/create-release@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # This token is provided by Actions, you do not need to create your own token + with: + tag_name: ${{ github.ref }} + release_name: Release ${{ steps.version.outputs.name }} + # if needed, you can set the release body here + #body: "Release notes" + draft: false + prerelease: false + + - name: download artifact + uses: actions/download-artifact@v2 + with: + name: "Linux-${{ steps.version.outputs.name }}" + path: ./ + + - name: upload ubuntu release asset + uses: actions/upload-release-asset@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ steps.create_release.outputs.upload_url }} + asset_path: "artifact.tar.gz" + asset_name: "${{ env.PROJECT_NAME }}-Linux-${{ steps.version.outputs.name }}.tar.gz" + asset_content_type: application/x-tar + + - name: download artifact + uses: actions/download-artifact@v2 + with: + name: "Windows-${{ steps.version.outputs.name }}" + path: ./ + + - name: upload windows release asset + uses: actions/upload-release-asset@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ steps.create_release.outputs.upload_url }} + asset_path: "artifact.zip" + asset_name: "${{ env.PROJECT_NAME }}-Windows-${{ steps.version.outputs.name }}.zip" + asset_content_type: application/zip + + - name: download artifact + uses: actions/download-artifact@v2 + with: + name: "macOS-${{ steps.version.outputs.name }}" + path: ./ + + - name: upload macos release asset + uses: actions/upload-release-asset@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ steps.create_release.outputs.upload_url }} + asset_path: "./artifact.tar.gz" + asset_name: "${{ env.PROJECT_NAME }}-macOS-${{ steps.version.outputs.name }}.tar.gz" + asset_content_type: application/x-tar diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/.github/workflows/ubuntu.yml" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/.github/workflows/ubuntu.yml" new file mode 100644 index 0000000000000000000000000000000000000000..2aa85426176babe9583805e400353bd23f9c6601 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/.github/workflows/ubuntu.yml" @@ -0,0 +1,55 @@ +name: Ubuntu + +on: + push: + branches: [ master ] + pull_request: + branches: [ master ] + +env: + BUILD_TYPE: Release + INSTALL_LOCATION: .local + +jobs: + build: + + runs-on: ubuntu-latest + if: "!contains(github.event.head_commit.message, '[skip ci]') && !contains(github.event.head_commit.message, '[ci skip]')" + + steps: + - uses: actions/checkout@v2 + + - name: cache dependencies + uses: actions/cache@v2 + id: cache + with: + path: ${{ github.workspace }}/${{ env.INSTALL_LOCATION }} + key: ${{ runner.os }}-dependencies + + - name: install GoogleTest + if: ${{ steps.cache.output.cache-hit != 'true' }} + run: | + cd .. + git clone https://github.com/google/googletest.git --branch release-1.10.0 + cd googletest + cmake -Bbuild -DCMAKE_INSTALL_PREFIX=$GITHUB_WORKSPACE/$INSTALL_LOCATION + cmake --build build --config Release + cmake --build build --target install --config Release + + - name: configure + run: cmake -Bbuild -DCMAKE_INSTALL_PREFIX=$GITHUB_WORKSPACE/$INSTALL_LOCATION -DProject_ENABLE_CODE_COVERAGE=1 + + - name: build + run: cmake --build build --config $BUILD_TYPE -j4 + + - name: run tests + run: | + cd build + ctest -C $BUILD_TYPE -VV + + - name: Code coverage using Codecov + run: bash <(curl -s https://codecov.io/bash) + + - name: install project + run: cmake --build build --target install --config Release + diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/.github/workflows/windows.yml" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/.github/workflows/windows.yml" new file mode 100644 index 0000000000000000000000000000000000000000..d2da57413294e8aca76bef2bec2f29cf196d5a5c --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/.github/workflows/windows.yml" @@ -0,0 +1,53 @@ +name: Windows + +on: + push: + branches: [ master ] + pull_request: + branches: [ master ] + +env: + BUILD_TYPE: Release + INSTALL_LOCATION: ".local" + +jobs: + build: + + runs-on: windows-latest + if: "!contains(github.event.head_commit.message, '[skip ci]') && !contains(github.event.head_commit.message, '[ci skip]')" + + steps: + - uses: actions/checkout@v2 + + - name: cache dependencies + uses: actions/cache@v2 + id: cache + with: + path: ${{env.INSTALL_LOCATION}} + key: ${{runner.os}}-dependencies + + - name: install GoogleTest + if: ${{steps.cache.output.cache-hit != 'true'}} + run: | + cd .. + git clone https://github.com/google/googletest.git --branch release-1.10.0 + cd googletest + cmake -Bbuild -DCMAKE_INSTALL_PREFIX="$HOME/$env:INSTALL_LOCATION" -Dgtest_force_shared_crt=1 + cmake --build build --config Release + cmake --build build --target install --config Release + cd ../modern-cpp-template + + - name: configure + run: cmake -Bbuild -DCMAKE_INSTALL_PREFIX="$HOME/$env:INSTALL_LOCATION" + + - name: build + run: cmake --build build --config "$env:BUILD_TYPE" -j4 + + - name: run tests + run: | + cd build + ctest -C "$env:BUILD_TYPE" -VV + + - name: install project + run: cmake --build build --target install --config Release + diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/.gitignore" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/.gitignore" new file mode 100644 index 0000000000000000000000000000000000000000..101c97f2e9233121a96810ccb600925b2c56d593 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/.gitignore" @@ -0,0 +1,368 @@ +[Bb]uild/* +[Dd]ocs/* +CMakeCache.* +CMakeFiles/* +[Tt]esting/* + +### VisualStudioCode ### +.vscode/* +.vscode/settings.json +.vscode/tasks.json +.vscode/launch.json +.vscode/extensions.json + +### VisualStudioCode Patch ### +# Ignore all local history of files +.history + +### VisualStudio ### +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +#KDevelop +*.kdev4 +.kdev4/* + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/CMakeLists.txt" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/CMakeLists.txt" new file mode 100644 index 0000000000000000000000000000000000000000..0e9fd930d03502bec230e561d24499cc38113258 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/CMakeLists.txt" @@ -0,0 +1,363 @@ +cmake_minimum_required(VERSION 3.15) + +# +# Project details +# + +project( + "Astar" + VERSION 0.1.0 + LANGUAGES CXX +) + +# +# Set project options +# + +include(cmake/StandardSettings.cmake) +include(cmake/StaticAnalyzers.cmake) +include(cmake/Utils.cmake) +if(NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE "Debug") +endif() +message(STATUS "Started CMake for ${PROJECT_NAME} v${PROJECT_VERSION}...\n") + +if (UNIX) + add_compile_options("$<$:-D_DEBUG>") #this will allow to use same _DEBUG macro available in both Linux as well as Windows - MSCV environment. Easy to put Debug specific code. +endif (UNIX) + + +# +# Setup alternative names +# + +if(${PROJECT_NAME}_USE_ALT_NAMES) + string(TOLOWER ${PROJECT_NAME} PROJECT_NAME_LOWERCASE) + string(TOUPPER ${PROJECT_NAME} PROJECT_NAME_UPPERCASE) +else() + set(PROJECT_NAME_LOWERCASE ${PROJECT_NAME}) + set(PROJECT_NAME_UPPERCASE ${PROJECT_NAME}) +endif() + +# +# Prevent building in the source directory +# + +if(PROJECT_SOURCE_DIR STREQUAL PROJECT_BINARY_DIR) + message(FATAL_ERROR "In-source builds not allowed. Please make a new directory (called a build directory) and run CMake from there.\n") +endif() + +# +# Enable package managers +# + +include(cmake/Conan.cmake) +include(cmake/Vcpkg.cmake) + +# +# Create library, setup header and source files +# + +# Find all headers and implementation files +include(cmake/SourcesAndHeaders.cmake) + +if(${PROJECT_NAME}_BUILD_EXECUTABLE) + add_executable(${PROJECT_NAME} ${exe_sources}) + + if(${PROJECT_NAME}_VERBOSE_OUTPUT) + verbose_message("Found the following sources:") + foreach(source IN LISTS exe_sources) + verbose_message("* ${source}") + endforeach() + endif() + + if(${PROJECT_NAME}_ENABLE_UNIT_TESTING) + add_library(${PROJECT_NAME}_LIB ${headers} ${sources}) + + if(${PROJECT_NAME}_VERBOSE_OUTPUT) + verbose_message("Found the following headers:") + foreach(header IN LISTS headers) + verbose_message("* ${header}") + endforeach() + endif() + endif() +elseif(${PROJECT_NAME}_BUILD_HEADERS_ONLY) + add_library(${PROJECT_NAME} INTERFACE) + + if(${PROJECT_NAME}_VERBOSE_OUTPUT) + verbose_message("Found the following headers:") + foreach(header IN LIST headers) + verbose_message("* ${header}") + endforeach() + endif() +else() + add_library( + ${PROJECT_NAME} + ${headers} + ${sources} + ) + + if(${PROJECT_NAME}_VERBOSE_OUTPUT) + verbose_message("Found the following sources:") + foreach(source IN LISTS sources) + verbose_message("* ${source}") + endforeach() + verbose_message("Found the following headers:") + foreach(header IN LISTS headers) + verbose_message("* ${header}") + endforeach() + endif() +endif() + +set_target_properties( + ${PROJECT_NAME} + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib/${CMAKE_BUILD_TYPE}" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib/${CMAKE_BUILD_TYPE}" + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin/${CMAKE_BUILD_TYPE}" +) +if(${PROJECT_NAME}_BUILD_EXECUTABLE AND ${PROJECT_NAME}_ENABLE_UNIT_TESTING) + set_target_properties( + ${PROJECT_NAME}_LIB + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib/${CMAKE_BUILD_TYPE}" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib/${CMAKE_BUILD_TYPE}" + OUTPUT_NAME ${PROJECT_NAME} + ) +endif() + +message(STATUS "Added all header and implementation files.\n") + +# +# Set the project standard and warnings +# + +if(${PROJECT_NAME}_BUILD_HEADERS_ONLY) + target_compile_features(${PROJECT_NAME} INTERFACE cxx_std_17) +else() + target_compile_features(${PROJECT_NAME} PUBLIC cxx_std_17) + + if(${PROJECT_NAME}_BUILD_EXECUTABLE AND ${PROJECT_NAME}_ENABLE_UNIT_TESTING) + target_compile_features(${PROJECT_NAME}_LIB PUBLIC cxx_std_17) + endif() +endif() +include(cmake/CompilerWarnings.cmake) +set_project_warnings(${PROJECT_NAME}) + +verbose_message("Applied compiler warnings. Using standard ${CMAKE_CXX_STANDARD}.\n") + +# +# Enable Doxygen +# + +include(cmake/Doxygen.cmake) + +# +# Model project dependencies +# + +# Identify and link with the specific "packages" the project uses +#find_package(package_name package_version REQUIRED package_type [other_options]) +#target_link_libraries( +# ${PROJECT_NAME} +# PUBLIC +# dependency1 ... +# PRIVATE +# dependency2 ... +# ${PROJECT_NAME}_PROJECT_OPTIONS +# ${PROJECT_NAME}_PROJECT_WARNINGS +#) +#if(${PROJECT_NAME}_BUILD_EXECUTABLE AND ${PROJECT_NAME}_ENABLE_UNIT_TESTING) +# target_link_libraries( +# ${PROJECT_NAME}_LIB +# PUBLIC +# dependency1 ... +# ) +#endif() + +# For Windows, it is necessary to link with the MultiThreaded library. +# Depending on how the rest of the project's dependencies are linked, it might be necessary +# to change the line to statically link with the library. +# +# This is done as follows: +# +# set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") +# +# On Linux and Mac this variable is ignored. If any issues rise from it, try commenting it out +# and letting CMake decide how to link with it. +set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>DLL") + +verbose_message("Successfully added all dependencies and linked against them.") + +# +# Set the build/user include directories +# + +# Allow usage of header files in the `src` directory, but only for utilities +if(${PROJECT_NAME}_BUILD_HEADERS_ONLY) + target_include_directories( + ${PROJECT_NAME} + INTERFACE + $ + $ + ) +else() + target_include_directories( + ${PROJECT_NAME} + PUBLIC + $ + $ + PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/src + ) + if(${PROJECT_NAME}_BUILD_EXECUTABLE AND ${PROJECT_NAME}_ENABLE_UNIT_TESTING) + target_include_directories( + ${PROJECT_NAME}_LIB + PUBLIC + $ + $ + PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/src + ) + endif() +endif() + +message(STATUS "Finished setting up include directories.") + +# +# Provide alias to library for +# + +if(${PROJECT_NAME}_BUILD_EXECUTABLE) + add_executable(${PROJECT_NAME}::${PROJECT_NAME} ALIAS ${PROJECT_NAME}) +else() + add_library(${PROJECT_NAME}::${PROJECT_NAME} ALIAS ${PROJECT_NAME}) +endif() + +verbose_message("Project is now aliased as ${PROJECT_NAME}::${PROJECT_NAME}.\n") + +# +# Format the project using the `clang-format` target (i.e: cmake --build build --target clang-format) +# + +add_clang_format_target() + +# +# Install library for easy downstream inclusion +# + +include(GNUInstallDirs) +install( + TARGETS + ${PROJECT_NAME} + EXPORT + ${PROJECT_NAME}Targets + LIBRARY DESTINATION + ${CMAKE_INSTALL_LIBDIR} + RUNTIME DESTINATION + ${CMAKE_INSTALL_BINDIR} + ARCHIVE DESTINATION + ${CMAKE_INSTALL_LIBDIR} + INCLUDES DESTINATION + include + PUBLIC_HEADER DESTINATION + include +) + +install( + EXPORT + ${PROJECT_NAME}Targets + FILE + ${PROJECT_NAME}Targets.cmake + NAMESPACE + ${PROJECT_NAME}:: + DESTINATION + ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME} +) + +# +# Add version header +# + +configure_file( + ${CMAKE_CURRENT_LIST_DIR}/cmake/version.hpp.in + include/${PROJECT_NAME_LOWERCASE}/version.hpp + @ONLY +) + +install( + FILES + ${CMAKE_CURRENT_BINARY_DIR}/include/${PROJECT_NAME_LOWERCASE}/version.hpp + DESTINATION + include/${PROJECT_NAME_LOWERCASE} +) + +# +# Install the `include` directory +# + +install( + DIRECTORY + include/${PROJECT_NAME_LOWERCASE} + DESTINATION + include +) + +verbose_message("Install targets successfully built. Install with `cmake --build --target install --config `.") + +# +# Quick `ConfigVersion.cmake` creation +# + +include(CMakePackageConfigHelpers) +write_basic_package_version_file( + ${PROJECT_NAME}ConfigVersion.cmake + VERSION + ${PROJECT_VERSION} + COMPATIBILITY + SameMajorVersion +) + +configure_package_config_file( + ${CMAKE_CURRENT_LIST_DIR}/cmake/${PROJECT_NAME}Config.cmake.in + ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake + INSTALL_DESTINATION + ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME} +) + +install( + FILES + ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake + ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake + DESTINATION + ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME} +) + +# +# Generate export header if specified +# + +if(${PROJECT_NAME}_GENERATE_EXPORT_HEADER) + include(GenerateExportHeader) + generate_export_header(${PROJECT_NAME}) + install( + FILES + ${PROJECT_BINARY_DIR}/${PROJECT_NAME_LOWERCASE}_export.h + DESTINATION + include + ) + + message(STATUS "Generated the export header `${PROJECT_NAME_LOWERCASE}_export.h` and installed it.") +endif() + +message(STATUS "Finished building requirements for installing the package.\n") + +# +# Unit testing setup +# + +if(${PROJECT_NAME}_ENABLE_UNIT_TESTING) + enable_testing() + message(STATUS "Build unit tests for the project. Tests should always be found in the test folder\n") + add_subdirectory(test) +endif() diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/Dockerfile" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/Dockerfile" new file mode 100644 index 0000000000000000000000000000000000000000..44076e54f4314649babe435b9ec0158fb34eb3d5 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/Dockerfile" @@ -0,0 +1,52 @@ +FROM ubuntu:18.04 + +RUN echo "Updating Ubuntu" +RUN apt-get update && apt-get upgrade -y + +RUN echo "Installing dependencies..." +RUN apt install -y \ + ccache \ + clang \ + clang-format \ + clang-tidy \ + cppcheck \ + curl \ + doxygen \ + gcc \ + git \ + graphviz \ + make \ + ninja-build \ + python3 \ + python3-pip \ + tar \ + unzip \ + vim + +RUN echo "Installing dependencies not found in the package repos..." + +RUN apt install -y wget tar build-essential libssl-dev && \ + wget https://github.com/Kitware/CMake/releases/download/v3.15.0/cmake-3.15.0.tar.gz && \ + tar -zxvf cmake-3.15.0.tar.gz && \ + cd cmake-3.15.0 && \ + ./bootstrap && \ + make && \ + make install + +RUN pip3 install conan + +RUN git clone https://github.com/catchorg/Catch2.git && \ + cd Catch2 && \ + cmake -Bbuild -H. -DBUILD_TESTING=OFF && \ + cmake --build build/ --target install + +# Disabled pthread support for GTest due to linking errors +RUN git clone https://github.com/google/googletest.git --branch release-1.10.0 && \ + cd googletest && \ + cmake -Bbuild -Dgtest_disable_pthreads=1 && \ + cmake --build build --config Release && \ + cmake --build build --target install --config Release + +RUN git clone https://github.com/microsoft/vcpkg -b 2020.06 && \ + cd vcpkg && \ + ./bootstrap-vcpkg.sh -disableMetrics -useSystemBinaries diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/LICENSE" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/LICENSE" new file mode 100644 index 0000000000000000000000000000000000000000..471f09f4cfb55e0f1eada17d06022eccead0c747 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/LICENSE" @@ -0,0 +1,25 @@ +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +For more information, please refer to + diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/Makefile" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/Makefile" new file mode 100644 index 0000000000000000000000000000000000000000..d2bdaefdfe4a176a55de809abfbcf76565f9f5e7 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/Makefile" @@ -0,0 +1,63 @@ +.PHONY: install coverage test docs help +.DEFAULT_GOAL := help + +define BROWSER_PYSCRIPT +import os, webbrowser, sys + +try: + from urllib import pathname2url +except: + from urllib.request import pathname2url + +webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1]))) +endef +export BROWSER_PYSCRIPT + +define PRINT_HELP_PYSCRIPT +import re, sys + +for line in sys.stdin: + match = re.match(r'^([a-zA-Z_-]+):.*?## (.*)$$', line) + if match: + target, help = match.groups() + print("%-20s %s" % (target, help)) +endef +export PRINT_HELP_PYSCRIPT + +BROWSER := python -c "$$BROWSER_PYSCRIPT" +INSTALL_LOCATION := ~/.local + +help: + @python -c "$$PRINT_HELP_PYSCRIPT" < $(MAKEFILE_LIST) + +test: ## run tests quickly with ctest + rm -rf build/ + cmake -Bbuild -DCMAKE_INSTALL_PREFIX=$(INSTALL_LOCATION) -Dmodern-cpp-template_ENABLE_UNIT_TESTING=1 -DCMAKE_BUILD_TYPE="Release" + cmake --build build --config Release + cd build/ && ctest -C Release -VV + +coverage: ## check code coverage quickly GCC + rm -rf build/ + cmake -Bbuild -DCMAKE_INSTALL_PREFIX=$(INSTALL_LOCATION) -Dmodern-cpp-template_ENABLE_CODE_COVERAGE=1 + cmake --build build --config Release + cd build/ && ctest -C Release -VV + cd .. && (bash -c "find . -type f -name '*.gcno' -exec gcov -pb {} +" || true) + +docs: ## generate Doxygen HTML documentation, including API docs + rm -rf docs/ + rm -rf build/ + cmake -Bbuild -DCMAKE_INSTALL_PREFIX=$(INSTALL_LOCATION) -DProject_ENABLE_DOXYGEN=1 + cmake --build build --config Release + cmake --build build --target doxygen-docs + $(BROWSER) docs/html/index.html + +install: ## install the package to the `INSTALL_LOCATION` + rm -rf build/ + cmake -Bbuild -DCMAKE_INSTALL_PREFIX=$(INSTALL_LOCATION) + cmake --build build --config Release + cmake --build build --target install --config Release + +format: ## format the project sources + rm -rf build/ + cmake -Bbuild -DCMAKE_INSTALL_PREFIX=$(INSTALL_LOCATION) + cmake --build build --target clang-format diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/README.md" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/README.md" new file mode 100644 index 0000000000000000000000000000000000000000..4b3de39fa0e261db86df3fe173b108c55d8c200b --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/README.md" @@ -0,0 +1,179 @@ +# 题目 +## 题目描述 +![](./images/question.png) + +# 数据结构设计 +## 1. Point类 + +**Point类表示地图上的一个点,并包含以下私有成员和公有方法:** + +#### 私有成员: + +* _x 和 _y:表示点的坐标。 +* _F:该点的 F 值,即 G 值和 H 值的和,用于 A* 算法中的优先级判断。 +* _G:从起点到该点的代价。 +* _H:从该点到终点的估计代价。 +* _parent:指向该点的父节点的指针,用于路径回溯。 +#### 公有方法: +* 各种 getter 和 setter 函数:用于获取和修改私有成员的值。 +* operator==:重载运算符以便比较两个点是否相同。 +## 2. Map类 + +**Map类表示搜索空间,用于封装地图,并包含地图的长度、宽度等信息** + +#### 私有成员: +* _length: 表示地图的长度。 +* _width:表示地图的宽度。 +* _graph:表示地图的实际网格,用一个二维向量存储。(其中0表示可通过,1表示障碍)。 +* _dir:表示移动方向的数组,用于找到相邻点 + +#### 公有方法: + +* 构造函数:用于初始化地图; +* 各种 getter 和 setter 函数:用于获取和修改私有成员的值。 +* visitGraph:访问地图上的某个点。 +* showMap:打印地图。 +* randomizeGraph:随机生成地图。 + +## 3. Astar类 + +**Astar 类实现了 AStar 算法,并包含以下成员变量和方法:** + + +#### 私有成员: + +* _openList:打开列表,用于存储待检查的点,按 F 值排序。 +* _closeList:关闭列表,用于存储已检查的点。 + +#### 公有方法: + +* findPath:主函数,用于找到从起点到终点的路径。 +* calcF、calcG 和 calcH:用于计算 F、G 和 H 值的辅助函数。 +* isUseful:判断某点是否可用。 +* isInOpenList 和 isInCloseList:判断某点是否在打开列表或关闭列表中。 +* findSurround:找到当前点的所有相邻点。 +* showPath:打印找到的路径。 +# 输入和输出描述 +## 输入流程: +``` +//初始化起点和终点: +Point *start=new Point(0, 0); +Point *end=new Point(9, 9); + +//初始化地图 +Map map(10, 10); //生成包含10*10大小的二维数组的Map对象,表示地图 +map.randomizeGraph(); //随机初始化地图上每个点可通过或不可通过; + + +//调用A*算法,得到路径 +//Astar astar; +auto path=astar.findPath(start,end,map); +``` +## 输出流程: +``` +auto path=astar.findPath(start, end,map); +for (auto p : path){ + cout << p->getX() << " " << p->getY() << endl; +} + +system("pause"); +``` + + +## 输入和输出样例: +#### 1. 样例1 + +![](./images/input1.png) +![](./images/output1.png) +#### 2. 样例2 + +![](./images/input2.png) +![](./images/output2.png) + + +# 主要算法思想 +## 描述: + A*(A-star)算法是一种启发式搜索算法, + 用于在图中找到从起点到终点的最短路径。 + 结合了 Dijkstra 算法的优点(最短路径, + 贪婪最佳优先搜索的优点(启发式搜索), + 以有效地找到最优路径。 + +## 算法流程: +``` +function Astar(start, end, map): + openList ← new PriorityQueue + closedList ← new Set + openList.push(start) + start.G ← 0 + start.H ← heuristic(start, end) + start.F ← start.G + start.H + + while not openList.isEmpty(): + current ← openList.pop() + if current == end: + return reconstruct_path(current) + + closedList.add(current) + + for neighbor in current.neighbors(): + if neighbor in closedList: + continue + + tentative_g = current.G + distance(current, neighbor) + + if neighbor not in openList: + openList.push(neighbor) + else if tentative_g >= neighbor.G: + continue + + neighbor.parent = current + neighbor.G = tentative_g + neighbor.H = heuristic(neighbor, end) + neighbor.F = neighbor.G + neighbor.H + + return failure +``` + +# 总结: +### 关于数据结构的选择: +在算法中,openlist列表要存放待选择的节点、判断节点是否在列表中,且需要弹出列表中F值最小的节点并返回。刚开始选择list,但是每次都要手动遍历一遍找到f值最小的元素,时间复杂度较高; +后面考虑使用能自动保存最小值的数据结构,multiset和priorityqueue;但是priorityqueue基于堆实现,不支持遍历, +很难判断节点是否在列表中。而multiset基于红黑树实现,可以高效查找元素,最后采用了multiset作为openlist的数据结构。 +### 遇到的问题: +定义std::multiset openlist时,不能直接在 Point 类中定义比较运算符,原因是multiset 存储的是指向 Point 对象的指针, +而不是 Point 对象本身。 +因此,需要一个函数对象(或函数指针)来比较这些指针所指向的对象,而不是比较指针本身。 +需要为 std::multiset 定义比较函数对象: +``` +struct ComparePoints { + bool operator()(const Point* p1, const Point* p2) const { + return p1->getF() < p2->getF(); + } +}; + +std::multiset _openList; + +``` +### 使用的C++新特性: +- lambda表达式 +``` +bool Astar::isInOpenList(Point * now) +{ + //使用lambda表达式 + return std::any_of(_openList.begin(), _openList.end(), [now](Point* point) { + return point->getX() == now->getX() && point->getY() == now->getY(); + }); +} +``` + +- 智能指针 +``` +bool Astar::isUseful(int x, int y, Map &map) +{ + //使用 std::unique_ptr 代替裸指针,以避免手动管理内存。 + auto point = std::make_unique(x, y); + return !(x < 0 || x >= map.getLength() || y < 0 || y >= map.getWidth() || map.visitGraph(x, y) == 1 || isInCloseList(point.get())); +} +``` +- 区间for循环 diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/cmake/AstarConfig.cmake.in" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/cmake/AstarConfig.cmake.in" new file mode 100644 index 0000000000000000000000000000000000000000..2ac739c90b98ca8689ad4610652a9b10373675f7 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/cmake/AstarConfig.cmake.in" @@ -0,0 +1,9 @@ +set(@PROJECT_NAME@_VERSION @PROJECT_VERSION@) + +@PACKAGE_INIT@ + +set_and_check(@PROJECT_NAME@_INCLUDE_DIR "@CMAKE_INSTALL_FULL_INCLUDEDIR@") + +include("${CMAKE_CURRENT_LIST_DIR}/@PROJECT_NAME@Targets.cmake") + +check_required_components(@PROJECT_NAME@) diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/cmake/CompilerWarnings.cmake" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/cmake/CompilerWarnings.cmake" new file mode 100644 index 0000000000000000000000000000000000000000..2b5d58eff36aff6b9e120fc084fa413ce2ff1736 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/cmake/CompilerWarnings.cmake" @@ -0,0 +1,99 @@ +# from here: +# +# https://github.com/lefticus/cppbestpractices/blob/master/02-Use_the_Tools_Avai +# lable.md +# Courtesy of Jason Turner + +function(set_project_warnings project_name) + set(MSVC_WARNINGS + /W4 # Baseline reasonable warnings + /w14242 # 'identifier': conversion from 'type1' to 'type1', possible loss + # of data + /w14254 # 'operator': conversion from 'type1:field_bits' to + # 'type2:field_bits', possible loss of data + /w14263 # 'function': member function does not override any base class + # virtual member function + /w14265 # 'classname': class has virtual functions, but destructor is not + # virtual instances of this class may not be destructed correctly + /w14287 # 'operator': unsigned/negative constant mismatch + /we4289 # nonstandard extension used: 'variable': loop control variable + # declared in the for-loop is used outside the for-loop scope + /w14296 # 'operator': expression is always 'boolean_value' + /w14311 # 'variable': pointer truncation from 'type1' to 'type2' + /w14545 # expression before comma evaluates to a function which is missing + # an argument list + /w14546 # function call before comma missing argument list + /w14547 # 'operator': operator before comma has no effect; expected + # operator with side-effect + /w14549 # 'operator': operator before comma has no effect; did you intend + # 'operator'? + /w14555 # expression has no effect; expected expression with side- effect + /w14619 # pragma warning: there is no warning number 'number' + /w14640 # Enable warning on thread un-safe static member initialization + /w14826 # Conversion from 'type1' to 'type_2' is sign-extended. This may + # cause unexpected runtime behavior. + /w14905 # wide string literal cast to 'LPSTR' + /w14906 # string literal cast to 'LPWSTR' + /w14928 # illegal copy-initialization; more than one user-defined + # conversion has been implicitly applied + /permissive- # standards conformance mode for MSVC compiler. + ) + + set(CLANG_WARNINGS + -Wall + -Wextra # reasonable and standard + -Wshadow # warn the user if a variable declaration shadows one from a + # parent context + -Wnon-virtual-dtor # warn the user if a class with virtual functions has a + # non-virtual destructor. This helps catch hard to + # track down memory errors + -Wold-style-cast # warn for c-style casts + -Wcast-align # warn for potential performance problem casts + -Wunused # warn on anything being unused + -Woverloaded-virtual # warn if you overload (not override) a virtual + # function + -Wpedantic # warn if non-standard C++ is used + -Wconversion # warn on type conversions that may lose data + -Wsign-conversion # warn on sign conversions + -Wnull-dereference # warn if a null dereference is detected + -Wdouble-promotion # warn if float is implicit promoted to double + -Wformat=2 # warn on security issues around functions that format output + # (ie printf) + ) + + if (${PROJECT_NAME}_WARNINGS_AS_ERRORS) + set(CLANG_WARNINGS ${CLANG_WARNINGS} -Werror) + set(MSVC_WARNINGS ${MSVC_WARNINGS} /WX) + endif() + + set(GCC_WARNINGS + ${CLANG_WARNINGS} + -Wmisleading-indentation # warn if indentation implies blocks where blocks + # do not exist + -Wduplicated-cond # warn if if / else chain has duplicated conditions + -Wduplicated-branches # warn if if / else branches have duplicated code + -Wlogical-op # warn about logical operations being used where bitwise were + # probably wanted + -Wuseless-cast # warn if you perform a cast to the same type + ) + + if(MSVC) + set(PROJECT_WARNINGS ${MSVC_WARNINGS}) + elseif(CMAKE_CXX_COMPILER_ID MATCHES ".*Clang") + set(PROJECT_WARNINGS ${CLANG_WARNINGS}) + elseif(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") + set(PROJECT_WARNINGS ${GCC_WARNINGS}) + else() + message(AUTHOR_WARNING "No compiler warnings set for '${CMAKE_CXX_COMPILER_ID}' compiler.") + endif() + + if(${PROJECT_NAME}_BUILD_HEADERS_ONLY) + target_compile_options(${project_name} INTERFACE ${PROJECT_WARNINGS}) + else() + target_compile_options(${project_name} PUBLIC ${PROJECT_WARNINGS}) + endif() + + if(NOT TARGET ${project_name}) + message(AUTHOR_WARNING "${project_name} is not a target, thus no compiler warning were added.") + endif() +endfunction() diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/cmake/Conan.cmake" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/cmake/Conan.cmake" new file mode 100644 index 0000000000000000000000000000000000000000..b844e2a5758b013389a709f3cfb9be1dbf05426f --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/cmake/Conan.cmake" @@ -0,0 +1,46 @@ +if(${PROJECT_NAME}_ENABLE_CONAN) + # + # Setup Conan requires and options here: + # + + set(${PROJECT_NAME}_CONAN_REQUIRES "") + set(${PROJECT_NAME}_CONAN_OPTIONS "") + + # + # If `conan.cmake` (from https://github.com/conan-io/cmake-conan) does not exist, download it. + # + if(NOT EXISTS "${CMAKE_BINARY_DIR}/conan.cmake") + message( + STATUS + "Downloading conan.cmake from https://github.com/conan-io/cmake-conan..." + ) + file( + DOWNLOAD "https://github.com/conan-io/cmake-conan/raw/v0.15/conan.cmake" + "${CMAKE_BINARY_DIR}/conan.cmake" + ) + message(STATUS "Cmake-Conan downloaded succesfully.") + endif() + + include(${CMAKE_BINARY_DIR}/conan.cmake) + + conan_add_remote( + NAME bincrafters + URL + https://api.bintray.com/conan/bincrafters/public-conan + ) + + conan_cmake_run( + REQUIRES + ${${PROJECT_NAME}_CONAN_REQUIRES} + OPTIONS + ${${PROJECT_NAME}_CONAN_OPTIONS} + BASIC_SETUP + CMAKE_TARGETS # Individual targets to link to + BUILD + missing + ) + + conan_basic_setup() + + verbose_message("Conan is setup and all requires have been installed.") +endif() diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/cmake/Doxygen.cmake" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/cmake/Doxygen.cmake" new file mode 100644 index 0000000000000000000000000000000000000000..bd6fe45ba73aec15141dda4a6c6a906adc3e1d40 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/cmake/Doxygen.cmake" @@ -0,0 +1,11 @@ +if(${PROJECT_NAME}_ENABLE_DOXYGEN) + set(DOXYGEN_CALLER_GRAPH YES) + set(DOXYGEN_CALL_GRAPH YES) + set(DOXYGEN_EXTRACT_ALL YES) + set(DOXYGEN_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/docs) + + find_package(Doxygen REQUIRED dot) + doxygen_add_docs(doxygen-docs ${PROJECT_SOURCE_DIR}) + + verbose_message("Doxygen has been setup and documentation is now available.") +endif() diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/cmake/SourcesAndHeaders.cmake" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/cmake/SourcesAndHeaders.cmake" new file mode 100644 index 0000000000000000000000000000000000000000..d83214dedfc1a7cfcbf6a08a0327169c42d5aba1 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/cmake/SourcesAndHeaders.cmake" @@ -0,0 +1,20 @@ +set(sources + src/Astar.cpp + src/Map.cpp + src/Point.cpp +) + +set(exe_sources + src/main.cpp + ${sources} +) + +set(headers + include/Astar/Astar.hpp + include/Astar/Map.hpp + include/Astar/Point.hpp +) + +set(test_sources + src/tmp_test.cpp +) diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/cmake/StandardSettings.cmake" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/cmake/StandardSettings.cmake" new file mode 100644 index 0000000000000000000000000000000000000000..fd77929987949942b3470fd44b401660baba4e4d --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/cmake/StandardSettings.cmake" @@ -0,0 +1,95 @@ +# +# Project settings +# + +option(${PROJECT_NAME}_BUILD_EXECUTABLE "Build the project as an executable, rather than a library." OFF) +option(${PROJECT_NAME}_BUILD_HEADERS_ONLY "Build the project as a header-only library." OFF) +option(${PROJECT_NAME}_USE_ALT_NAMES "Use alternative names for the project, such as naming the include directory all lowercase." ON) + +# +# Compiler options +# + +option(${PROJECT_NAME}_WARNINGS_AS_ERRORS "Treat compiler warnings as errors." OFF) + +# +# Package managers +# +# Currently supporting: Conan, Vcpkg. + +option(${PROJECT_NAME}_ENABLE_CONAN "Enable the Conan package manager for this project." OFF) +option(${PROJECT_NAME}_ENABLE_VCPKG "Enable the Vcpkg package manager for this project." OFF) + +# +# Unit testing +# +# Currently supporting: GoogleTest, Catch2. + +option(${PROJECT_NAME}_ENABLE_UNIT_TESTING "Enable unit tests for the projects (from the `test` subfolder)." ON) + +option(${PROJECT_NAME}_USE_GTEST "Use the GoogleTest project for creating unit tests." ON) +option(${PROJECT_NAME}_USE_GOOGLE_MOCK "Use the GoogleMock project for extending the unit tests." OFF) + +option(${PROJECT_NAME}_USE_CATCH2 "Use the Catch2 project for creating unit tests." OFF) + +# +# Static analyzers +# +# Currently supporting: Clang-Tidy, Cppcheck. + +option(${PROJECT_NAME}_ENABLE_CLANG_TIDY "Enable static analysis with Clang-Tidy." OFF) +option(${PROJECT_NAME}_ENABLE_CPPCHECK "Enable static analysis with Cppcheck." OFF) + +# +# Code coverage +# + +option(${PROJECT_NAME}_ENABLE_CODE_COVERAGE "Enable code coverage through GCC." OFF) + +# +# Doxygen +# + +option(${PROJECT_NAME}_ENABLE_DOXYGEN "Enable Doxygen documentation builds of source." OFF) + +# +# Miscelanious options +# + +# Generate compile_commands.json for clang based tools +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) + +option(${PROJECT_NAME}_VERBOSE_OUTPUT "Enable verbose output, allowing for a better understanding of each step taken." ON) +option(${PROJECT_NAME}_GENERATE_EXPORT_HEADER "Create a `project_export.h` file containing all exported symbols." OFF) + +# Export all symbols when building a shared library +if(BUILD_SHARED_LIBS) + set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS OFF) + set(CMAKE_CXX_VISIBILITY_PRESET hidden) + set(CMAKE_VISIBILITY_INLINES_HIDDEN 1) +endif() + +option(${PROJECT_NAME}_ENABLE_LTO "Enable Interprocedural Optimization, aka Link Time Optimization (LTO)." OFF) +if(${PROJECT_NAME}_ENABLE_LTO) + include(CheckIPOSupported) + check_ipo_supported(RESULT result OUTPUT output) + if(result) + set(CMAKE_INTERPROCEDURAL_OPTIMIZATION TRUE) + else() + message(SEND_ERROR "IPO is not supported: ${output}.") + endif() +endif() + + +option(${PROJECT_NAME}_ENABLE_CCACHE "Enable the usage of Ccache, in order to speed up rebuild times." ON) +find_program(CCACHE_FOUND ccache) +if(CCACHE_FOUND) + set_property(GLOBAL PROPERTY RULE_LAUNCH_COMPILE ccache) + set_property(GLOBAL PROPERTY RULE_LAUNCH_LINK ccache) +endif() + +option(${PROJECT_NAME}_ENABLE_ASAN "Enable Address Sanitize to detect memory error." OFF) +if(${PROJECT_NAME}_ENABLE_ASAN) + add_compile_options(-fsanitize=address) + add_link_options(-fsanitize=address) +endif() diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/cmake/StaticAnalyzers.cmake" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/cmake/StaticAnalyzers.cmake" new file mode 100644 index 0000000000000000000000000000000000000000..10e4da4947ec036b1309d29681d1cb28811484d7 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/cmake/StaticAnalyzers.cmake" @@ -0,0 +1,20 @@ +if(${PROJECT_NAME}_ENABLE_CLANG_TIDY) + find_program(CLANGTIDY clang-tidy) + if(CLANGTIDY) + set(CMAKE_CXX_CLANG_TIDY ${CLANGTIDY} -extra-arg=-Wno-unknown-warning-option) + message("Clang-Tidy finished setting up.") + else() + message(SEND_ERROR "Clang-Tidy requested but executable not found.") + endif() +endif() + +if(${PROJECT_NAME}_ENABLE_CPPCHECK) + find_program(CPPCHECK cppcheck) + if(CPPCHECK) + set(CMAKE_CXX_CPPCHECK ${CPPCHECK} --suppress=missingInclude --enable=all + --inline-suppr --inconclusive -i ${CMAKE_SOURCE_DIR}/imgui/lib) + message("Cppcheck finished setting up.") + else() + message(SEND_ERROR "Cppcheck requested but executable not found.") + endif() +endif() diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/cmake/Utils.cmake" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/cmake/Utils.cmake" new file mode 100644 index 0000000000000000000000000000000000000000..754c7cdf63d19ca710d28994ac7ded233fdc6885 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/cmake/Utils.cmake" @@ -0,0 +1,40 @@ +# +# Print a message only if the `VERBOSE_OUTPUT` option is on +# + +function(verbose_message content) + if(${PROJECT_NAME}_VERBOSE_OUTPUT) + message(STATUS ${content}) + endif() +endfunction() + +# +# Add a target for formating the project using `clang-format` (i.e: cmake --build build --target clang-format) +# + +function(add_clang_format_target) + if(NOT ${PROJECT_NAME}_CLANG_FORMAT_BINARY) + find_program(${PROJECT_NAME}_CLANG_FORMAT_BINARY clang-format) + endif() + + if(${PROJECT_NAME}_CLANG_FORMAT_BINARY) + if(${PROJECT_NAME}_BUILD_EXECUTABLE) + add_custom_target(clang-format + COMMAND ${${PROJECT_NAME}_CLANG_FORMAT_BINARY} + -i ${exe_sources} ${headers} + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}) + elseif(${PROJECT_NAME}_BUILD_HEADERS_ONLY) + add_custom_target(clang-format + COMMAND ${${PROJECT_NAME}_CLANG_FORMAT_BINARY} + -i ${headers} + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}) + else() + add_custom_target(clang-format + COMMAND ${${PROJECT_NAME}_CLANG_FORMAT_BINARY} + -i ${sources} ${headers} + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}) + endif() + + message(STATUS "Format the project using the `clang-format` target (i.e: cmake --build build --target clang-format).\n") + endif() +endfunction() diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/cmake/Vcpkg.cmake" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/cmake/Vcpkg.cmake" new file mode 100644 index 0000000000000000000000000000000000000000..1c13e386a405d05f852ff69ace9abfffaaa30384 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/cmake/Vcpkg.cmake" @@ -0,0 +1,20 @@ +if(${PROJECT_NAME}_ENABLE_VCPKG) + # + # If `vcpkg.cmake` (from https://github.com/microsoft/vcpkg) does not exist, download it. + # + if(NOT EXISTS "${CMAKE_BINARY_DIR}/vcpkg.cmake") + message( + STATUS + "Downloading `vcpkg.cmake` from https://github.com/microsoft/vcpkg..." + ) + file(DOWNLOAD "https://github.com/microsoft/vcpkg/raw/master/scripts/buildsystems/vcpkg.cmake" + "${CMAKE_BINARY_DIR}/vcpkg.cmake" + ) + message(STATUS "Vcpkg config downloaded succesfully.") + endif() + + if(${PROJECT_NAME}_VERBOSE_OUTPUT) + set(VCPKG_VERBOSE ON) + endif() + set(CMAKE_TOOLCHAIN_FILE "${CMAKE_TOOLCHAIN_FILE}" "${CMAKE_BINARY_DIR}/vcpkg.cmake") +endif() diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/cmake/version.hpp.in" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/cmake/version.hpp.in" new file mode 100644 index 0000000000000000000000000000000000000000..985bad67f624c392b8e6f40e594948b12a9b7eb8 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/cmake/version.hpp.in" @@ -0,0 +1,11 @@ +#ifndef @PROJECT_NAME_UPPERCASE@_VERSION_H_ +#define @PROJECT_NAME_UPPERCASE@_VERSION_H_ + +#define @PROJECT_NAME_UPPERCASE@_VERSION "@PROJECT_VERSION@" + +#define @PROJECT_NAME_UPPERCASE@_MAJOR_VERSION @PROJECT_VERSION_MAJOR@ +#define @PROJECT_NAME_UPPERCASE@_MINOR_VERSION @PROJECT_VERSION_MINOR@ +#define @PROJECT_NAME_UPPERCASE@_PATCH_VERSION @PROJECT_VERSION_PATCH@ + +#endif // @PROJECT_NAME_UPPERCASE@_VERSION_H_ + diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/codecov.yaml" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/codecov.yaml" new file mode 100644 index 0000000000000000000000000000000000000000..b2c991fbb617bd03755cd2f09bc18c66efdafca1 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/codecov.yaml" @@ -0,0 +1,5 @@ +ignore: + - "test" + +comment: + require_changes: true diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/images/input1.png" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/images/input1.png" new file mode 100644 index 0000000000000000000000000000000000000000..3cee38b251eaaaea8e6ecb1a04264d0f1f464e1c Binary files /dev/null and "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/images/input1.png" differ diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/images/input2.png" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/images/input2.png" new file mode 100644 index 0000000000000000000000000000000000000000..25b5d0b985c223ddd155ba3ec54387b2935ea477 Binary files /dev/null and "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/images/input2.png" differ diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/images/output1.png" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/images/output1.png" new file mode 100644 index 0000000000000000000000000000000000000000..4c0e3f69078e3191e43de94eafc6649f43f7306a Binary files /dev/null and "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/images/output1.png" differ diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/images/output2.png" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/images/output2.png" new file mode 100644 index 0000000000000000000000000000000000000000..201d80ee659327f46a58074b5b74f72b03ccab3a Binary files /dev/null and "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/images/output2.png" differ diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/images/question.png" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/images/question.png" new file mode 100644 index 0000000000000000000000000000000000000000..d2fbdd0990817cea3cf12e2e873d0212c8951281 Binary files /dev/null and "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/images/question.png" differ diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/include/Astar/Astar.hpp" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/include/Astar/Astar.hpp" new file mode 100644 index 0000000000000000000000000000000000000000..79514436ed4c8758fdc83652ce9ad25b72179390 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/include/Astar/Astar.hpp" @@ -0,0 +1,48 @@ +/** + * @file Astar.hpp + * @author lizichao () + * @brief Header file for the A* algorithm class declarations. + * @version 0.1 + * @date 2024-07-24 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef ASTAR_H_ +#define ASTAR_H_ + +#include "Astar/Point.hpp" +#include "Astar/Map.hpp" +#include +#include +#include + +const int kCost1 = 10; +const int kCost2 = 14; + +struct ComparePoints { + bool operator()(const Point* p1, const Point* p2) const { + return p1->getF() < p2->getF(); + } +}; + +class Astar { +public: + std::list findPath(Point* start, Point* end, Map& map); + +private: + int calcF(Point* now) const; + int calcG(Point* temp_start, Point* point); + int calcH(Point* now, Point* end) const; + bool isUseful(int x, int y, Map& map); + bool isInOpenList(Point* now); + bool isInCloseList(Point* now); + std::vector findSurround(Point* now, Map& map); + std::list showPath() const; + +private: + std::multiset _openList; + std::list _closeList; +}; + +#endif // ASTAR_H_ \ No newline at end of file diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/include/Astar/Map.hpp" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/include/Astar/Map.hpp" new file mode 100644 index 0000000000000000000000000000000000000000..831c6636726b8163791b5d7d4c80d0316864d009 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/include/Astar/Map.hpp" @@ -0,0 +1,44 @@ +/** + * @file Map.hpp + * @author lizichao () + * @brief Header file for the Map class declarations, used in the A* algorithm. + * @version 0.1 + * @date 2024-07-24 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef MAP_H_ +#define MAP_H_ + +#include +#include +#include +#include +#include "Astar/Point.hpp" + +class Map { +public: + Map() : _length(0), _width(0) {} + Map(int length, int weight): _length(length), _width(weight), _graph(static_cast::size_type>(length), std::vector(static_cast::size_type>(weight))) {} + Map(int length, int weight, std::vector> g) : _length(length), _width(weight), _graph(g) {} + + int getDir(int i, int j); + int getLength() const; + void setLength(int length); + int getWidth() const; + void setWidth(int weight); + void setGraph(std::vector> g); + int visitGraph(int i, int j); + void showMap() const; + void showPath(std::list path); + void randomizeGraph(); + +private: + int _dir[8][2] = { {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}, {-1, -1}, {-1, 0}, {-1, 1} }; + int _length; + int _width; + std::vector> _graph; +}; + +#endif // MAP_H_ \ No newline at end of file diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/include/Astar/Point.hpp" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/include/Astar/Point.hpp" new file mode 100644 index 0000000000000000000000000000000000000000..4258e085973c2968f79ca139c1cf9d1693020097 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/include/Astar/Point.hpp" @@ -0,0 +1,43 @@ +/** + * @file Point.hpp + * @brief Header file for the Point class declarations, representing points in the map. + * @version 0.1 + * @date 2024-07-24 + * + * @copyright Copyright (c) 2024 + * + */ +#ifndef POINT_H_ +#define POINT_H_ + +class Point { +public: + Point(int x, int y) : _x(x), _y(y), _F(0), _G(0), _H(0), _parent(nullptr) {} + + int getX() const; + void setX(int x); + int getY() const; + void setY(int y); + int getF() const; + void setF(int F); + int getG() const; + void setG(int G); + int getH() const; + void setH(int H); + Point* getParent() const; + void setParent(Point* parent); + + bool operator==(const Point& other) const { + return _x == other._x && _y == other._y; + } + +private: + int _x; + int _y; + int _F; + int _G; + int _H; + Point* _parent; +}; + +#endif // POINT_H_ \ No newline at end of file diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/src/Astar.cpp" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/src/Astar.cpp" new file mode 100644 index 0000000000000000000000000000000000000000..0af112141f950cbe46ca6f9e50ee08300bab7e4d --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/src/Astar.cpp" @@ -0,0 +1,132 @@ +/** + * @file Astar.cpp + * @author lizichao () + * @brief Implementation file for the A* algorithm. + * @version 0.1 + * @date 2024-07-24 + * + * @copyright Copyright (c) 2024 + * + */ +#include "Astar/Astar.hpp" +#include +#include +#include +#include + +int Astar::calcF(Point * now) const +{ + return now->getG() + now->getH(); +} + +int Astar::calcG(Point *temp_start, Point *point) +{ + int extraG = (abs(point->getX() - temp_start->getX()) + abs(point->getY() - temp_start->getY())) == 1 ? kCost1 : kCost2; + int parentG = point->getParent() == NULL ? 0 : point->getParent()->getG(); + return parentG + extraG; +} +int Astar::calcH(Point * now, Point * end) const +{ + int dx = end->getX() - now->getX(); + int dy = end->getY() - now->getY(); + return static_cast(sqrt(dx * dx + dy * dy) * kCost1); +} + + +bool Astar::isUseful(int x, int y, Map &map) +{ + //ʹ�� std::unique_ptr ������ָ�룬�Ա����ֶ������ڴ档 + auto point = std::make_unique(x, y); + return !(x < 0 || x >= map.getLength() || y < 0 || y >= map.getWidth() || map.visitGraph(x, y) == 1 || isInCloseList(point.get())); +} + +bool Astar::isInOpenList(Point * now) +{ + //ʹ��lambda����ʽ + return std::any_of(_openList.begin(), _openList.end(), [now](Point* point) { + return point->getX() == now->getX() && point->getY() == now->getY(); + }); +} + +bool Astar::isInCloseList(Point * now) +{ + return std::any_of(_closeList.begin(), _closeList.end(), [now](Point* point) { + return point->getX() == now->getX() && point->getY() == now->getY(); + }); +} + +std::vector Astar::findSurround(Point * now, Map &map) +{ + std::vector surroundings; + int newx=0,newy = 0; + for (int i = 0; i < 8; i++) { + newx = now->getX() + map.getDir(i,0); + newy = now->getY() + map.getDir(i,1); + if (isUseful(newx, newy,map)) { + surroundings.push_back(new Point(newx, newy)); + } + + } + return surroundings; +} + +std::list Astar::findPath(Point * start, Point * end, Map &map) +{ + _openList.insert(start); + while (!_openList.empty()) { + auto it = _openList.begin(); + Point* now = *it; + _openList.erase(it); + _closeList.push_back(now); + auto surrounds = findSurround(now, map); + + for (auto &target : surrounds) { + if (!isInOpenList(target)) { + target->setParent(now); + target->setG(calcG(now, target)); + target->setH(calcH(target, end)); + target->setF(calcF(target)); + _openList.insert(target); + } + else { + int tempG = calcG(now, target); + if (tempG < target->getG()) { + target->setParent(now); + target->setG(tempG); + target->setF(calcF(target)); + } + } + } + if (isInCloseList(end)) { + auto List = showPath(); + map.showPath(List); + return List; + } + } + std::cout << "path no found" << std::endl; + return std::list(); +} + +std::list Astar::showPath() const +{ + std::list showlist; + auto end = _closeList.back(); + while (end != nullptr) { + showlist.push_front(end); + end = end->getParent(); + } + std::cout << "the path is:" << std::endl; + + for (const auto& point : showlist) { + if (point != showlist.back()) { + std::cout << "(" << point->getX() << "," << point->getY() << ") -> "; + } + else { + std::cout << "(" << point->getX() << "," << point->getY() << ")"; + } + } + std::cout << std::endl << std::endl; + return showlist;; +} + + diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/src/Map.cpp" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/src/Map.cpp" new file mode 100644 index 0000000000000000000000000000000000000000..746b1555619e36dff59a57941ee175468c0b85db --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/src/Map.cpp" @@ -0,0 +1,88 @@ +/** + * @file Map.cpp + * @author lizichao () + * @brief Implementation file for the Map class. + * @version 0.1 + * @date 2024-07-24 + * + * @copyright Copyright (c) 2024 + * + */ +#include "Astar/Map.hpp" + +int Map::getDir(int i, int j) +{ + return _dir[i][j]; +} + +int Map::getLength() const +{ + return this->_length; +} + +void Map::setLength(int length) +{ + this->_length = length; +} + +int Map::getWidth() const +{ + return this->_width; +} + +void Map::setWidth(int weight) +{ + this->_width = weight; +} + +void Map::setGraph(std::vector> g) +{ + _graph = g; +} + + + +int Map::visitGraph(int i, int j) +{ + return _graph[i][j]; +} + +void Map::showMap() const +{ + for (int i = 0; i < _length; i++) { + for (int j = 0; j < _width; j++) { + if (_graph[i][j] == 0) std::cout << "o"<<" "; + else std::cout << "x"<<" "; + } + std::cout << std::endl<< std::endl; + } +} + +void Map::showPath(std::list path) +{ + std::vector> result_graph = _graph; + for (auto it : path) { + result_graph[it->getX()][it->getY()] = 2; + } + for (int i = 0; i < _length; i++) { + for (int j = 0; j < _width; j++) { + if (result_graph[i][j] == 0) std::cout << "o" << " "; + else if (result_graph[i][j] == 1) std::cout << "x" << " "; + else std::cout << "#" << " "; + } + std::cout << std::endl << std::endl; + } +} + +void Map::randomizeGraph() +{ + std::random_device rd; + std::mt19937 gen(rd()); + std::uniform_int_distribution<> dis(0, 1); + + for (auto& row : _graph) { + for (auto& elem : row) { + elem = dis(gen); + } + } +} diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/src/Point.cpp" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/src/Point.cpp" new file mode 100644 index 0000000000000000000000000000000000000000..c97bd30a0bff0dedf3d218ad1e4e8a75b5ba81c6 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/src/Point.cpp" @@ -0,0 +1,71 @@ +/** + * @file Point.cpp + * @author lizichao () + * @brief Implementation file for the Point class. + * @version 0.1 + * @date 2024-07-24 + * + * @copyright Copyright (c) 2024 + * + */ +#include "Astar/Point.hpp" + +int Point::getX() const +{ + return this->_x; +} + +void Point::setX(int x) +{ + this->_x = x; +} + +int Point::getY() const +{ + return this->_y; +} + +void Point::setY(int y) +{ + this->_y = y; +} + +int Point::getF() const +{ + return this->_F; +} + +void Point::setF(int F) +{ + this->_F =F; +} + +int Point::getG() const +{ + return this->_G; +} + +void Point::setG(int G) +{ + this->_G = G; +} + +int Point::getH() const +{ + return this->_H; +} + +void Point::setH(int H) +{ + this->_H = H; +} + +Point* Point::getParent() const +{ + return this->_parent; +} + +void Point::setParent(Point * parent) +{ + this->_parent = parent; +} diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/test/CMakeLists.txt" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/test/CMakeLists.txt" new file mode 100644 index 0000000000000000000000000000000000000000..71f07af2a353861b4faab9979b35de8918a70c22 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/test/CMakeLists.txt" @@ -0,0 +1,84 @@ +cmake_minimum_required(VERSION 3.15) + +# +# Project details +# + +project( + ${CMAKE_PROJECT_NAME}Tests + LANGUAGES CXX +) + +verbose_message("Adding tests under ${CMAKE_PROJECT_NAME}Tests...") + +foreach(file ${test_sources}) + string(REGEX REPLACE "(.*/)([a-zA-Z0-9_ ]+)(\.cpp)" "\\2" test_name ${file}) + add_executable(${test_name}_Tests ${file}) + + # + # Set the compiler standard + # + + target_compile_features(${test_name}_Tests PUBLIC cxx_std_17) + + # + # Setup code coverage if enabled + # + + if (${CMAKE_PROJECT_NAME}_ENABLE_CODE_COVERAGE) + target_compile_options(${CMAKE_PROJECT_NAME} PUBLIC -O0 -g -fprofile-arcs -ftest-coverage) + target_link_options(${CMAKE_PROJECT_NAME} PUBLIC -fprofile-arcs -ftest-coverage) + verbose_message("Code coverage is enabled and provided with GCC.") + endif() + + # + # Load the desired unit testing framework + # + # Currently supported: GoogleTest (and GoogleMock), Catch2. + + if(${CMAKE_PROJECT_NAME}_BUILD_EXECUTABLE) + set(${CMAKE_PROJECT_NAME}_TEST_LIB ${CMAKE_PROJECT_NAME}_LIB) + else() + set(${CMAKE_PROJECT_NAME}_TEST_LIB ${CMAKE_PROJECT_NAME}) + endif() + + if(${CMAKE_PROJECT_NAME}_USE_GTEST) + find_package(GTest REQUIRED) + + if(${CMAKE_PROJECT_NAME}_USE_GOOGLE_MOCK) + set(GOOGLE_MOCK_LIBRARIES GTest::gmock GTest::gmock_main) + endif() + + target_link_libraries( + ${test_name}_Tests + PUBLIC + GTest::GTest + GTest::Main + ${GOOGLE_MOCK_LIBRARIES} + ${${CMAKE_PROJECT_NAME}_TEST_LIB} + ) + elseif(${CMAKE_PROJECT_NAME}_USE_CATCH2) + find_package(Catch2 REQUIRED) + target_link_libraries( + ${test_name}_Tests + PUBLIC + Catch2::Catch2 + ${${CMAKE_PROJECT_NAME}_TEST_LIB} + ) + else() + message(FATAL_ERROR "Unknown testing library. Please setup your desired unit testing library by using `target_link_libraries`.") + endif() + + # + # Add the unit tests + # + + add_test( + NAME + ${test_name} + COMMAND + ${test_name}_Tests + ) +endforeach() + +verbose_message("Finished adding unit tests for ${CMAKE_PROJECT_NAME}.") diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/test/src/tmp_test.cpp" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/test/src/tmp_test.cpp" new file mode 100644 index 0000000000000000000000000000000000000000..1efa87de66088adf9df60d9c4cbf7206e3a0b264 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/Astar/test/src/tmp_test.cpp" @@ -0,0 +1,50 @@ +#include "Astar/Astar.hpp" +#include "Astar/Point.hpp" +#include +#include +#include + + +TEST(AstarTest, CheckPath) { + + std::vector> g = { + {0,0,0,0,1,1,1,1}, + {0,0,0,0,0,1,1,1}, + {1,1,0,1,1,0,0,0}, + {1,0,0,0,0,0,0,0}, + }; + Map map(4, 8, g); + map.showMap(); + + Astar astar; + // 设置起始和结束点 + Point *start = new Point(0, 0); + Point *end = new Point(3, 7); + + // A*算法 + auto path=astar.findPath(start, end, map); + std::list resultpath; + resultpath.push_back(new Point(0,0)); + resultpath.push_back(new Point(0,1)); + resultpath.push_back(new Point(1,2)); + resultpath.push_back(new Point(1,3)); + resultpath.push_back(new Point(1,4)); + resultpath.push_back(new Point(2,5)); + resultpath.push_back(new Point(2,6)); + resultpath.push_back(new Point(3,7)); + + auto it1 = path.begin(); + auto it2 = resultpath.begin(); + + for (; it1 != path.end() && it2 != resultpath.end(); ++it1, ++it2) { + EXPECT_EQ((*it1)->getX(),(*it2)->getX()); + EXPECT_EQ((*it1)->getY(),(*it2)->getY()); + } + + system("pause"); +} + +int main(int argc, char **argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/.vscode/settings.json" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/.vscode/settings.json" new file mode 100644 index 0000000000000000000000000000000000000000..24dd5a1981d8de2df5f5a31eda8025a61b918b33 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/.vscode/settings.json" @@ -0,0 +1,44 @@ +{ + "files.associations": { + "iostream": "cpp", + "ostream": "cpp", + "array": "cpp", + "atomic": "cpp", + "*.tcc": "cpp", + "cctype": "cpp", + "clocale": "cpp", + "cmath": "cpp", + "cstdarg": "cpp", + "cstddef": "cpp", + "cstdint": "cpp", + "cstdio": "cpp", + "cstdlib": "cpp", + "cstring": "cpp", + "cwchar": "cpp", + "cwctype": "cpp", + "deque": "cpp", + "unordered_map": "cpp", + "vector": "cpp", + "exception": "cpp", + "algorithm": "cpp", + "memory": "cpp", + "memory_resource": "cpp", + "optional": "cpp", + "string": "cpp", + "string_view": "cpp", + "system_error": "cpp", + "tuple": "cpp", + "type_traits": "cpp", + "utility": "cpp", + "fstream": "cpp", + "initializer_list": "cpp", + "iosfwd": "cpp", + "istream": "cpp", + "limits": "cpp", + "new": "cpp", + "sstream": "cpp", + "stdexcept": "cpp", + "streambuf": "cpp", + "typeinfo": "cpp" + } +} \ No newline at end of file diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter10/10-1/10-1.cpp" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter10/10-1/10-1.cpp" new file mode 100644 index 0000000000000000000000000000000000000000..937229d7fa9e19ad3ec5e4e9c99f5c6ab8f9692f --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter10/10-1/10-1.cpp" @@ -0,0 +1,51 @@ +#include +#include +using namespace std; +class BankAccount { +private: + string name; + string account; + int money; +public: + BankAccount(const string& n="",const string& a="",const int &m=0); + void show() const; + void save(const int& m); + void withdraw(const int& m); +}; + +BankAccount::BankAccount(const string & n, const string & a, const int & m):name(n),account(a),money(m) +{ +} + +void BankAccount::show() const +{ + cout << "BanAccount:" << endl; + cout << "name:" << name << endl; + cout << "account:" << account << endl; + cout << "money:" << money << endl; + cout << endl; +} + +void BankAccount::save(const int& m) +{ + money += m; +} + +void BankAccount::withdraw(const int& m) +{ + if (money < m) + cout << "money no enough" << endl << endl; + else + money -= m; +} +int main() +{ + BankAccount test("lzc", "135", 100); + test.show(); + test.save(50); + test.show(); + test.withdraw(200); + test.withdraw(120); + test.show(); + +} diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter10/10-8/10-8-list.cpp" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter10/10-8/10-8-list.cpp" new file mode 100644 index 0000000000000000000000000000000000000000..4fd0d436215efc45d9d0980a1f0628353c9cc201 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter10/10-8/10-8-list.cpp" @@ -0,0 +1,25 @@ +#include "10-8-list.h" +#include +List::List() +{ + count = 0; +}; +void List::add(const Item&item) { + if (isFull()) + std::cout << "the list is full!" << std::endl; + else { + list[count++] = item; + } + +}; +bool List::isEmpty()const { + return count == 0; +}; + +bool List::isFull() const { + return count == MAX_SIZE; +}; +void List::visit(void(*pf)(Item &)) { + for (int i = 0; i < count; i++) + pf(list[i]); +}; diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter10/10-8/10-8-list.h" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter10/10-8/10-8-list.h" new file mode 100644 index 0000000000000000000000000000000000000000..64acb0a879613bd6694101aabb7812afe0ab4d7a --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter10/10-8/10-8-list.h" @@ -0,0 +1,14 @@ +#pragma once +typedef int Item; +class List { +private: + enum {MAX_SIZE = 10}; + Item list[MAX_SIZE]; + int count; +public: + List(); + void add(const Item&item); + bool isEmpty() const; + bool isFull() const; + void visit(void (*pf)(Item &)); +}; \ No newline at end of file diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter10/10-8/10-8-main.cpp" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter10/10-8/10-8-main.cpp" new file mode 100644 index 0000000000000000000000000000000000000000..40e8014ae26cc9a86192611565867e9cd3f9b7b9 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter10/10-8/10-8-main.cpp" @@ -0,0 +1,19 @@ +#include +#include "10-8-list.h" +void show(Item &item) { + std::cout << item << std::endl; +} +void add(Item &item) { + item++; +} +int main() +{ + List test; + test.add(10); + test.add(20); + test.add(30); + + test.visit(show); + test.visit(add); + test.visit(show); +} \ No newline at end of file diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter11/11-4/mytime3.cpp" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter11/11-4/mytime3.cpp" new file mode 100644 index 0000000000000000000000000000000000000000..31767702722cecb6da471ed5a48fb98a1eb89aec --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter11/11-4/mytime3.cpp" @@ -0,0 +1,66 @@ +#include "mytime3.h" + +Time::Time() +{ + hours = minutes = 0; +} + +Time::Time(int h, int m) +{ + hours = h; + minutes = m; +} + +void Time::AddMin(int m) +{ + minutes += m; + hours += minutes / 60; + minutes %= 60; +} + +void Time::AddHr(int h) +{ + hours += h; +} + +void Time::Reset(int h, int m) +{ + hours = h; + minutes = m; +} + + +Time operator+(const Time &t1, const Time &t2) +{ + Time sum; + sum.minutes = t1.minutes + t2.minutes; + sum.hours = t1.hours + t2.hours + sum.minutes / 60; + sum.minutes %= 60; + return sum; +} + +Time operator-(const Time &t1, const Time &t2) +{ + Time diff; + int tot1, tot2; + tot1 = t2.minutes + 60 * t2.hours; + tot2 = t1.minutes + 60 * t1.hours; + diff.minutes = (tot2 - tot1) % 60; + diff.hours = (tot2 - tot1) / 60; + return diff; +} + +Time operator*(const Time &t, double m) +{ + Time result; + long totalminutes = t.hours * m * 60 + t.minutes * m; + result.hours = totalminutes / 60; + result.minutes = totalminutes % 60; + return result; +} + +std::ostream &operator<<(std::ostream &os, const Time &t) +{ + os << t.hours << " hours, " << t.minutes << " minutes"; + return os; +} diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter11/11-4/mytime3.h" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter11/11-4/mytime3.h" new file mode 100644 index 0000000000000000000000000000000000000000..7873c28e422e9f4c36e5bf6cffa6ebf264e96bb8 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter11/11-4/mytime3.h" @@ -0,0 +1,27 @@ +// mytime3.h -- Time class with friends +#ifndef MYTIME3_H_ +#define MYTIME3_H_ +#include + +class Time +{ +private: + int hours; + int minutes; +public: + Time(); + Time(int h, int m = 0); + void AddMin(int m); + void AddHr(int h); + void Reset(int h = 0, int m = 0); + friend Time operator+(const Time & t1,const Time & t2); + friend Time operator-(const Time & t1,const Time & t2); + friend Time operator*(const Time & t,double n); + friend Time operator*(double m, const Time & t) + { + return t * m; + } + friend std::ostream & operator<<(std::ostream & os, const Time & t); +}; + +#endif diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter11/11-4/usetime3.cpp" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter11/11-4/usetime3.cpp" new file mode 100644 index 0000000000000000000000000000000000000000..9b939e89c204b6a52062929218eeae822c9d8588 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter11/11-4/usetime3.cpp" @@ -0,0 +1,22 @@ +// usetime3.cpp -- using the fourth draft of the Time class +// compile usetime3.cpp and mytime3.cpp together +#include +#include "mytime3.h" + +int main() +{ + + Time aida(3, 35); + Time tosca(2, 48); + Time temp; + + std::cout << "Aida and Tosca:\n"; + std::cout << aida << "; " << tosca << std::endl; + temp = aida + tosca; // operator+() + std::cout << "Aida + Tosca: " << temp << std::endl; + temp = aida * 1.17; // member operator*() + std::cout << "Aida * 1.17: " << temp << std::endl; + std::cout << "10.0 * Tosca: " << 10.0 * tosca << std::endl; + + return 0; +} diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter11/11-7/11-7-1.cpp" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter11/11-7/11-7-1.cpp" new file mode 100644 index 0000000000000000000000000000000000000000..43c427e2372165030cb37f98440292bbf4325897 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter11/11-7/11-7-1.cpp" @@ -0,0 +1,35 @@ +#include +#include "11-7-complex0.h" +using std::cin; +using std::cout; +using std::endl; +complex complex::operator+(const complex& c) { + return complex(this->realnum+c.realnum, this->imagnum+c.imagnum); +} +complex complex::operator-(const complex& c) { + return complex(this->realnum - c.realnum, this->imagnum - c.imagnum); +} +complex complex::operator*(const complex& c) { + double a = this->realnum*c.realnum - this->imagnum*c.imagnum; + double b = this->realnum*c.imagnum + this->imagnum*c.realnum; + return complex(a, b); +} +complex complex::operator*(const double& x) { + return complex(this->realnum*x, this->imagnum*x); +} + +complex operator*( const double& x, const complex& c) { + return complex(x*c.realnum, x*c.imagnum); +} +ostream& operator<<(ostream& os, const complex& c) { + os << c.realnum << "+" << c.imagnum << "i" << endl; + return os; +} + +istream& operator>>(istream& is, complex& c) { + cout << "read:"; + is >> c.realnum; + cout << "imaginary:"; + is>> c.imagnum; + return is; +} \ No newline at end of file diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter11/11-7/11-7-complex0.h" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter11/11-7/11-7-complex0.h" new file mode 100644 index 0000000000000000000000000000000000000000..f1c7d476cda1dcf46a0cc39408119cd132abe6b1 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter11/11-7/11-7-complex0.h" @@ -0,0 +1,19 @@ +#pragma once +#include +using std::ostream; +using std::istream; +class complex { +private: + double realnum; + double imagnum; +public: + complex() :realnum(0.0), imagnum(0.0) {}; + complex(const double& a, const double& b) :realnum(a), imagnum(b) {}; + complex operator+(const complex& c); + complex operator-(const complex& c); + complex operator*(const complex& c); + complex operator*(const double& x); + friend complex operator*(const double& x, const complex& c); + friend ostream& operator<<( ostream&os, const complex& c); + friend istream& operator>>( istream&is, complex& c); +}; diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter11/11-7/11-7-main .cpp" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter11/11-7/11-7-main .cpp" new file mode 100644 index 0000000000000000000000000000000000000000..21760f589e9ac3007c89f767e593cae9eb108f98 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter11/11-7/11-7-main .cpp" @@ -0,0 +1,22 @@ +#include +using namespace std; +#include "11-7-complex0.h" // to avoid confusion with complex.h +int main() +{ + complex a(3.0, 4.0); // initialize to (3, 4i) + complex c; + cout << "Enter a complex number (q to quit):\n"; + while (cin >> c) + { + cout << "c is " << c << '\n'; + //cout << "complex conjugate is " << ~c << '\n'; + cout << "a is " << a << '\n'; + cout << "a + c is " << a + c << '\n'; + cout << "a - c is " << a - c << '\n'; + cout << "a * c is " << a * c << '\n'; + cout << "2 * c is " << 2 * c << '\n'; + cout << "Enter a complex number (q to quit):\n"; + } + cout << "Done!\n"; + return 0; +} diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter12/12-1/cow.cpp" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter12/12-1/cow.cpp" new file mode 100644 index 0000000000000000000000000000000000000000..c1b7a07934336da022b84b2405f72929ad4ab1cc --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter12/12-1/cow.cpp" @@ -0,0 +1,57 @@ +#include "cow.h" +#include +#include + +Cow::Cow() +{ + name[0]='\0'; + hobby=new char[1]; + hobby[0]='\0'; + weight=0.0; +} + +Cow::Cow(const char *nm, const char *ho, double wt) +{ + + strncpy(name,nm,19); + name[19]='\0'; + hobby=new char[strlen(ho)+1]; + strcpy(hobby,ho); + weight=wt; +} + +Cow &Cow::operator=(const Cow &c) +{ + if(this==&c) + return *this; + strncpy(name,c.name,19); + delete[] hobby; + hobby=new char[strlen(c.hobby)+1]; + strcpy(hobby,c.hobby); + weight=c.weight; + return *this; +} + +Cow::Cow(const Cow &c) +{ + strncpy(name, c.name, 19); + name[19] = '\0'; + hobby = new char[strlen(c.hobby) + 1]; + strcpy(hobby, c.hobby); + weight = c.weight; +} + +Cow::~Cow() +{ + delete []hobby; +} + + + +void Cow::ShowCow() const +{ + std::cout<<"cow message:"< +#include "cow.h" +int main(int argc, char *argv[]) +{ + Cow cow1; + Cow cow2("777","ball",80); + cow1.ShowCow(); + cow2.ShowCow(); + cow1=cow2; + cow1.ShowCow(); + Cow cow3=cow2; + cow3.ShowCow(); +} diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter12/12-2/main.cpp" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter12/12-2/main.cpp" new file mode 100644 index 0000000000000000000000000000000000000000..b484808cea88c029346d17521e40ab90a86e89fb --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter12/12-2/main.cpp" @@ -0,0 +1,40 @@ +// pel2_2.cpp +#include +#include "string2.h" + +int main() { + String s1(" and I am a C++ student."); + String s2 = "Please enter your name: "; + String s3; + + std::cout << s2; // overloaded << operator + std::cin >> s3; // overloaded >> operator + s2 = "My name is " + s3; // overloaded =, + operators + std::cout << s2 << ".\n"; + s2 = s2 + s1; + s2.stringup(); // converts string to uppercase + std::cout << "The string\n" << s2 << "\ncontains " << s2.has('A') + << " 'A' characters in it.\n"; + s1 = "red"; // String(const char *), then String & operator=(const String&) + String rgb[3] = { String(s1), String("green"), String("blue") }; + std::cout << "Enter the name of a primary color for mixing light: "; + String ans; + bool success = false; + while (std::cin >> ans) { + ans.stringlow(); // converts string to lowercase + for (int i = 0; i < 3; i++) { + if (ans == rgb[i]) // overloaded == operator + { + std::cout << "That's right!\n"; + success = true; + break; + } + } + if (success) + break; + else + std::cout << "Try again!\n"; + } + std::cout << "Bye\n"; + return 0; +} diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter12/12-2/string2.cpp" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter12/12-2/string2.cpp" new file mode 100644 index 0000000000000000000000000000000000000000..010afe9114742e4f328919c8a047cbc17ac74dd2 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter12/12-2/string2.cpp" @@ -0,0 +1,134 @@ +// string1.cpp -- String class methods +#include // string.h for some +#include "string2.h" +#include // includes + +// initializing static class member +int String::num_strings = 0; + +// static method +int String::HowMany() { + return num_strings; +} + +// class methods +String::String(const char * s) { // construct String from C string + len = std::strlen(s); // set size + str = new char[len + 1]; // allot storage + std::strcpy(str, s); // initialize pointer + num_strings++; // set object count +} + +String::String() { // default constructor + len = 4; + str = new char[1]; + str[0] = '\0'; // default string + num_strings++; +} + +String::String(const String & st) { // copy constructor + num_strings++; // handle static member update + len = st.len; // same length + str = new char[len + 1]; // allot space + std::strcpy(str, st.str); // copy string to new location +} + +String::~String() { // necessary destructor + --num_strings; // required + delete[] str; // required +} + +void String::stringup() +{ + for(int i=0;i(const String &st1, const String &st2) { + return st2 < st1; +} + +bool operator==(const String &st1, const String &st2) { + return (std::strcmp(st1.str, st2.str) == 0); +} + +String operator+(const String &st1, const String &st2) +{ + String res; + res.len=st1.len+st2.len; + res.str=new char[res.len+1]; + strcpy(res.str,st1.str); + strcat(res.str,st2.str); + return res; + +} + +// simple String output +ostream & operator<<(ostream & os, const String & st) { + os << st.str; + return os; +} + +// quick and dirty String input +istream & operator>>(istream & is, String & st) { + char temp[String::CINLIM]; + is.get(temp, String::CINLIM); + if (is) + st = temp; + while (is && is.get() != '\n') + continue; + return is; +} diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter12/12-2/string2.h" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter12/12-2/string2.h" new file mode 100644 index 0000000000000000000000000000000000000000..99fd932e0476f607286f7c2095fe652b54c15f3c --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter12/12-2/string2.h" @@ -0,0 +1,43 @@ +#ifndef STRING1_H_ +#define STRING1_H_ +#include +using std::ostream; +using std::istream; + +class String { +private: + char * str; // pointer to string + int len; // length of string + static int num_strings; // number of objects + static const int CINLIM = 80; // cin input limit + +public: + // constructors and other methods + String(const char * s); // constructor + String(); // default constructor + String(const String &); // copy constructor + ~String(); // destructor + int length() const { return len; } + void stringup();// converts string to uppercase + void stringlow(); // converts string to lowercase + int has(const char ch) const; + + // overloaded operator methods + String & operator=(const String &); + String & operator=(const char *); + char & operator[](int i); + const char & operator[](int i) const; + + // overloaded operator friends + friend bool operator<(const String &st, const String &st2); + friend bool operator>(const String &st1, const String &st2); + friend bool operator==(const String &st, const String &st2); + friend String operator+(const String &st1,const String &st2); + friend ostream & operator<<(ostream & os, const String & st); + friend istream & operator>>(istream & is, String & st); + + // static function + static int HowMany(); +}; + +#endif diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter13/13-1/cd.cpp" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter13/13-1/cd.cpp" new file mode 100644 index 0000000000000000000000000000000000000000..a18e61f1dd27e15c66b9515d6bb82d5ed87400eb --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter13/13-1/cd.cpp" @@ -0,0 +1,95 @@ +#include "cd.h" +#include +#include + +Cd::Cd(char *s1, char *s2, int n, double x) +{ + strncpy(performers,s1,49); + performers[49]='\0'; + strncpy(label,s2,19); + label[19]='\0'; + selections=n; + playtime=x; +} + +Cd::Cd(const Cd &d) +{ + strcpy(performers,d.performers); + strcpy(label,d.label); + selections=d.selections; + playtime=d.playtime; +} + +Cd::Cd() +{ + performers[0]='\0'; + label[0]='\0'; + selections=0; + playtime=0; +} + +Cd::~Cd() +{ +} + +void Cd::Report() const +{ + std::cout<<"performers:"< +#include "cd.h" // which will contain #include cd.h + +void Bravo(const Cd & disk); + +int main() +{ + Cd c1("Beatles", "Capitol", 14, 35.5); + Classic c2 = Classic("Piano Sonata in B flat, Fantasia in C", "Alfred Brendel", "Philips", 2, 57.17); + + Cd *pcd = &c1; + + std::cout << "Using object directly:\n"; + c1.Report(); // use Cd method + c2.Report(); // use Classic method + + std::cout << "Using type cd * pointer to objects:\n"; + pcd->Report(); // use Cd method for cd object + pcd = &c2; + pcd->Report(); // use Classic method for classic object + + std::cout << "Calling a function with a Cd reference argument:\n"; + Bravo(c1); + Bravo(c2); + + std::cout << "Testing assignment: "; + Classic copy; + copy = c2; + copy.Report(); + + return 0; +} + +void Bravo(const Cd & disk) +{ + disk.Report(); +} diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter13/13-4/port.cpp" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter13/13-4/port.cpp" new file mode 100644 index 0000000000000000000000000000000000000000..cc17fe72874809401aefbc8293c4fec4687e98c7 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter13/13-4/port.cpp" @@ -0,0 +1,98 @@ +#include "port.h" +#include +#include +using namespace std; +Port::Port() +{ + brand=new char[1]; + brand[0]='\0'; + style[0]='\0'; + bottles=0; +} +Port::Port(const char *br, const char *st, int b) +{ + brand=new char[strlen(br)+1]; + strcpy(brand,br); + strcpy(style,st); + bottles=b; +} + +Port::Port(const Port &p) +{ + brand=new char[strlen(p.brand)+1]; + strcpy(brand,p.brand); + strcpy(style,p.style); + bottles=p.bottles; +} + +Port &Port::operator=(const Port &p) +{ + if(this==&p) + return *this; + delete []brand; + brand=new char[strlen(p.brand)+1]; + strcpy(brand,p.brand); + strcpy(style,p.style); + bottles=p.bottles; + return *this; +} + +Port &Port::operator+=(int b) +{ + bottles+=b; + return *this; +} + +Port &Port::operator-=(int b) +{ + bottles-=b; + return *this; +} + +void Port::Show() const +{ + cout<<"Brand:"< +using namespace std; + +class Port +{ +private: + char * brand; + char style[20]; // i.e., tawny, ruby, vintage + int bottles; + +public: + Port(); + Port(const char * br , const char * st , int b); + Port(const Port & p); // copy constructor + virtual ~Port() { delete [] brand; } + Port & operator=(const Port & p); + Port & operator+=(int b); // adds b to bottles + Port & operator-=(int b); // subtracts b from bottles, if available + int BottleCount() const { return bottles; } + virtual void Show() const; + friend ostream & operator<<(ostream & os, const Port & p); +}; + + +class VintagePort : public Port // style necessarily = "vintage" +{ +private: + char * nickname; // i.e., "The Noble" or "Old Velvet", etc. + int year; // vintage year + +public: + VintagePort(); + VintagePort(const char * br, int b, const char * nn, int y); + VintagePort(const VintagePort & vp); + ~VintagePort() { delete [] nickname; } + VintagePort & operator=(const VintagePort & vp); + void Show() const; + friend ostream & operator<<(ostream & os, const VintagePort & vp); +}; diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter7/.vscode/launch.json" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter7/.vscode/launch.json" new file mode 100644 index 0000000000000000000000000000000000000000..87d9011ce86625193d2eb0b63a2da4c8d54a1208 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter7/.vscode/launch.json" @@ -0,0 +1,31 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Debug", + "type": "cppdbg", + "request": "launch", + "args": [], + "stopAtEntry": false, + "cwd": "${workspaceFolder}", + "environment": [], + "externalConsole": false, + "linux": { + "MIMode": "gdb", + "miDebuggerPath": "gdb", + "program": "${workspaceFolder}/output/main" + }, + "osx": { + "MIMode": "lldb", + "miDebuggerPath": "lldb-mi", + "program": "${workspaceFolder}/output/main" + }, + "windows": { + "MIMode": "gdb", + "miDebuggerPath": "gdb.exe", + "program": "${workspaceFolder}/output/main.exe" + }, + "preLaunchTask": "build" + } + ] +} diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter7/.vscode/tasks.json" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter7/.vscode/tasks.json" new file mode 100644 index 0000000000000000000000000000000000000000..a367b6d715525d68c352f18f5c7158058860768f --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter7/.vscode/tasks.json" @@ -0,0 +1,84 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "build", + "type": "shell", + "group": { + "kind": "build", + "isDefault": true + }, + "windows": { + "command": "powershell", + "args": [ + "-c", + "mingw32-make" + ] + }, + "linux": { + "command": "bash", + "args": [ + "-c", + "make" + ] + }, + "osx": { + "command": "bash", + "args": [ + "-c", + "make" + ] + } + }, + { + "label": "build & run", + "type": "shell", + "windows": { + "command": "powershell", + "args": [ + "-c", + "'mingw32-make run'" + ] + }, + "linux": { + "command": "bash", + "args": [ + "-c", + "'make run'" + ] + }, + "osx": { + "command": "bash", + "args": [ + "-c", + "'make run'" + ] + } + }, + { + "label": "clean", + "type": "shell", + "windows": { + "command": "powershell", + "args": [ + "-c", + "'mingw32-make clean'" + ] + }, + "linux": { + "command": "bash", + "args": [ + "-c", + "'make clean'" + ] + }, + "osx": { + "command": "bash", + "args": [ + "-c", + "'make clean'" + ] + } + } + ] +} \ No newline at end of file diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter7/Makefile" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter7/Makefile" new file mode 100644 index 0000000000000000000000000000000000000000..227f3ba72d357a7ce77388293a61e735d9fafce4 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter7/Makefile" @@ -0,0 +1,99 @@ +# +# 'make' build executable file 'main' +# 'make clean' removes all .o and executable files +# + +# define the Cpp compiler to use +CXX = g++ + +# define any compile-time flags +CXXFLAGS := -std=c++17 -Wall -Wextra -g + +# define library paths in addition to /usr/lib +# if I wanted to include libraries not in /usr/lib I'd specify +# their path using -Lpath, something like: +LFLAGS = + +# define output directory +OUTPUT := output + +# define source directory +SRC := src + +# define include directory +INCLUDE := include + +# define lib directory +LIB := lib + +ifeq ($(OS),Windows_NT) +MAIN := main.exe +SOURCEDIRS := $(SRC) +INCLUDEDIRS := $(INCLUDE) +LIBDIRS := $(LIB) +FIXPATH = $(subst /,\,$1) +RM := del /q /f +MD := mkdir +else +MAIN := main +SOURCEDIRS := $(shell find $(SRC) -type d) +INCLUDEDIRS := $(shell find $(INCLUDE) -type d) +LIBDIRS := $(shell find $(LIB) -type d) +FIXPATH = $1 +RM = rm -f +MD := mkdir -p +endif + +# define any directories containing header files other than /usr/include +INCLUDES := $(patsubst %,-I%, $(INCLUDEDIRS:%/=%)) + +# define the C libs +LIBS := $(patsubst %,-L%, $(LIBDIRS:%/=%)) + +# define the C source files +SOURCES := $(wildcard $(patsubst %,%/*.cpp, $(SOURCEDIRS))) + +# define the C object files +OBJECTS := $(SOURCES:.cpp=.o) + +# define the dependency output files +DEPS := $(OBJECTS:.o=.d) + +# +# The following part of the makefile is generic; it can be used to +# build any executable just by changing the definitions above and by +# deleting dependencies appended to the file from 'make depend' +# + +OUTPUTMAIN := $(call FIXPATH,$(OUTPUT)/$(MAIN)) + +all: $(OUTPUT) $(MAIN) + @echo Executing 'all' complete! + +$(OUTPUT): + $(MD) $(OUTPUT) + +$(MAIN): $(OBJECTS) + $(CXX) $(CXXFLAGS) $(INCLUDES) -o $(OUTPUTMAIN) $(OBJECTS) $(LFLAGS) $(LIBS) + +# include all .d files +-include $(DEPS) + +# this is a suffix replacement rule for building .o's and .d's from .c's +# it uses automatic variables $<: the name of the prerequisite of +# the rule(a .c file) and $@: the name of the target of the rule (a .o file) +# -MMD generates dependency output files same name as the .o file +# (see the gnu make manual section about automatic variables) +.cpp.o: + $(CXX) $(CXXFLAGS) $(INCLUDES) -c -MMD $< -o $@ + +.PHONY: clean +clean: + $(RM) $(OUTPUTMAIN) + $(RM) $(call FIXPATH,$(OBJECTS)) + $(RM) $(call FIXPATH,$(DEPS)) + @echo Cleanup complete! + +run: all + ./$(OUTPUTMAIN) + @echo Executing 'run: all' complete! diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter7/src/main.cpp" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter7/src/main.cpp" new file mode 100644 index 0000000000000000000000000000000000000000..5b2bd96306034feebd18ca62e05c27b997588de3 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter7/src/main.cpp" @@ -0,0 +1,6 @@ +#include + +int main(int argc, char *argv[]) +{ + std::cout << "Hello world!" << std::endl; +} diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter9/9-1/9-1-golf.cpp" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter9/9-1/9-1-golf.cpp" new file mode 100644 index 0000000000000000000000000000000000000000..098fc1ea7f8c27af74db2fe145fbdb2287afc6bf --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter9/9-1/9-1-golf.cpp" @@ -0,0 +1,37 @@ +#include "golf.h" +#include +#include +#include +void setGolf(golf & g, const char * name, int hc) +{ + strncpy_s(g.fullname, name,Len-1); + g.fullname[Len - 1] = '\0'; + g.handicap = hc; +} + +int setGolf(golf & g) +{ + std::cout << "Enter fullname: "; + std::cin.getline(g.fullname, Len); + if (strlen(g.fullname) == 0) { + return 0; + std::cout << "no name" << std::endl; + } + std::cout << "Enter handicap: "; + std::cin >> g.handicap; + std::cin.ignore(); + return 1; +} + +void handicap(golf & g, int hc) +{ + g.handicap = hc; +} + +void showGolf(const golf & g) +{ + std::cout << "golf message:" << std::endl; + std::cout << "fullname:" << g.fullname << std::endl; + std::cout << "handicap:" << g.handicap << std::endl; +} + diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter9/9-1/9-1-main.cpp" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter9/9-1/9-1-main.cpp" new file mode 100644 index 0000000000000000000000000000000000000000..df18c3fc1bd6a9a147223c2765c05acdc99267eb --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter9/9-1/9-1-main.cpp" @@ -0,0 +1,17 @@ +#include +#include "golf.h" +int main() +{ + golf garray[5]; + int size = 0; + for (int i = 0; i < 5; i++) { + if (setGolf(garray[i])) { + size++; + std::cout << "next input:" << std::endl; + } + else break; + } + for (int i = 0; i < size; i++) { + showGolf(garray[i]); + } +} \ No newline at end of file diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter9/9-1/golf.h" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter9/9-1/golf.h" new file mode 100644 index 0000000000000000000000000000000000000000..b1be5b2a57553177f7b29eab7f3d45bbbb6d24ae --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter9/9-1/golf.h" @@ -0,0 +1,26 @@ +// golf.h -- for pe9-1.cpp + +const int Len = 40; +struct golf +{ + char fullname[Len]; + int handicap; +}; + +// non-interactive version: +// function sets golf structure to provided name, handicap +// using values passed as arguments to the function +void setGolf(golf & g, const char * name, int hc); + +// interactive version: +// function solicits name and handicap from user +// and sets the members of g to the values entered +// returns 1 if name is entered, 0 if name is empty string +int setGolf(golf & g); + +// function resets handicap to new value +void handicap(golf & g, int hc); + +// function displays contents of golf structure +void showGolf(const golf & g); +#pragma once diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter9/9-4/9-4-1.cpp" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter9/9-4/9-4-1.cpp" new file mode 100644 index 0000000000000000000000000000000000000000..77aa207735fef6108af297bcf5d8f2eb79cdab4f --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter9/9-4/9-4-1.cpp" @@ -0,0 +1,64 @@ +#include "9-4-sales.h" +#include +using std::cin; +using std::cout; +using std::endl; +namespace SALES +{ + void setSales(Sales & s, const double ar[], int n) + { + double sum = 0.0; + s.max = ar[0]; + s.min = ar[0]; + for (int i = 0; i < QUARTERS; i++) { + if (i < n) { + s.sales[i] = ar[i]; + sum += ar[i]; + s.max = s.max > ar[i] ? s.max : ar[i]; + s.min = s.min < ar[i] ? s.min : ar[i]; + } + else { + s.sales[i] = 0.0; + } + s.average = sum / QUARTERS; + } + } + + + void setSales(Sales & s) + { + double total = 0.0; + std::cout << "Enter sales for 4 quarters" << endl; + for (int i = 0; i < QUARTERS; i++) + { + std::cout << "Quarter " << (i + 1) << ": "; + std::cin >> s.sales[i]; + total += s.sales[i]; + + if (i == 0) + { + s.max = s.min = s.sales[i]; + } + else + { + if (s.sales[i] > s.max) + s.max = s.sales[i]; + if (s.sales[i] < s.min) + s.min = s.sales[i]; + } + } + + s.average = total / QUARTERS; + } + + void showSales(const Sales & s) + { + cout << "Sales:" << endl; + for (int i = 0; i < 4; i++) { + cout << "Quarter" << i + 1 << ":" << s.sales[i] << endl; + } + cout << "max:" << s.max << endl; + cout << "min:" << s.min << endl; + cout << "average:" << s.average << endl; + } +} \ No newline at end of file diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter9/9-4/9-4-2.cpp" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter9/9-4/9-4-2.cpp" new file mode 100644 index 0000000000000000000000000000000000000000..daeefe82c426c0b05ffd45f71904866db50eb524 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter9/9-4/9-4-2.cpp" @@ -0,0 +1,17 @@ +#include +#include "9-4-sales.h" +using namespace SALES; +using std::cin; +using std::cout; +using std::endl; +int main() +{ + Sales s1; + Sales s2; + const double arr[3] = { 2.1,3.2,6.5 }; + setSales(s1, arr, 3); + showSales(s1); + setSales(s2); + showSales(s2); + +} \ No newline at end of file diff --git "a/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter9/9-4/9-4-sales.h" "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter9/9-4/9-4-sales.h" new file mode 100644 index 0000000000000000000000000000000000000000..66e326909012d6008f7326d718f284c362fe57b3 --- /dev/null +++ "b/C++/codes/2024-07/\346\235\216\345\255\220\350\266\205/C++PrimerPlus\350\257\276\345\220\216\344\271\240\351\242\230/Chapter9/9-4/9-4-sales.h" @@ -0,0 +1,26 @@ +#pragma once +namespace SALES +{ + const int QUARTERS = 4; + struct Sales + { + double sales[QUARTERS]; + double average; + double max; + double min; + }; + + // copies the lesser of 4 or n items from the array ar + // to the sales member of s and computes and stores the + // average, maximum, and minimum values of the entered items; + // remaining elements of sales, if any, set to 0 + void setSales(Sales & s, const double ar[], int n); + + // gathers sales for 4 quarters interactively, stores them + // in the sales member of s and computes and stores the + // average, maximum, and minimum values + void setSales(Sales & s); + + // display all information in structure s + void showSales(const Sales & s); +}