c++23で順列を扱う

2023/09/27

目次

c++23 にする

下記で c++23 でコンパイルできる。

g++ -std=c++23 hoge.cpp -o hoge.out

vscode のコンパイルするタスクも下記で c++23 でコンパイルできる。

.vscode/tasks.json
{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "c++ build for AtCoder",
      "type": "shell",
      "command": "g++",
      "args": [
        "-g",
        "-O0",
        "-std=c++23",
        "${file}",
        "-o",
        "${fileDirname}/${fileBasenameNoExtension}.out"
      ],
      "options": {
        "cwd": "${fileDirname}"
      },
      "group": {
        "kind": "build",
        "isDefault": true
      }
    }
  ]
}

VSCode の C/C++拡張機能は、デフォルトで C++17 までの機能をサポートしているらしく、c++20 以上を利用する際にエディタでエラーが出る場合がある。.vscode/c_cpp_properties.jsonに下記を設定することで、拡張機能の c++バージョンを変更できるらしい。(実際エラー消えた)

.vscode/c_cpp_properties.json
{
    "configurations": [
        {
            "name": "Linux",
            "includePath": ["${workspaceFolder}/**"],
            "defines": [],
            "compilerPath": "/usr/bin/g++",
            "cStandard": "c17",
            "cppStandard": "c++23",
            "intelliSenseMode": "gcc-x64",
            "compilerArgs": ["-std=c++23"]
        }
    ],
    "version": 4
}

順列

ranges::next_permutation(hoge)を使うと、引数 hoge の vector に対する、順列のパターンの次を出してくれる。[0,1,2]を入れると、[0,2,1]を返す。[0,2,1]を入れると[1,0,2]を返す。多分。要するに、全パターンを順番に取得する場合は、しっかりと昇順にソートしてから渡す必要がある。iota(hoge.begin(), hoge.end(), 0)は、hoge の最初から最後までを 0 から始まる連続する数値で埋める関数。

#include <bits/stdc++.h>

using namespace std;

int main()
{
  vector<int> cells(3);
  iota(cells.begin(), cells.end(), 0);
  do
  {
    for (auto &&c : cells)
    {
      cout << c;
    }
    cout << endl;
  } while (ranges::next_permutation(cells).found);
}

上記の実行結果は下記になる。

012
021
102
120
201
210
Rust🦀, Network⚡, PostgreSQL🐘, Unity🎮

Tags

rust  (9)
rocket  (7)
svelte  (5)
c++  (4)
ethereum  (3)
solidity  (3)
vscode  (3)
sqlx  (3)
glfw  (2)
opengl  (2)
nestjs  (2)
graphql  (2)
render  (2)
wsl2  (2)
truffle  (1)
goerli  (1)
geth  (1)
hardhat  (1)
nft  (1)
gui  (1)
tetris  (1)
next.js  (1)
jwt  (1)
nextauth  (1)
node.js  (1)
prisma  (1)
passport  (1)
urql  (1)
codegen  (1)
mdsvex  (1)
markdown  (1)
tmux  (1)
nvim  (1)
axum  (1)
atcoder  (1)
vim  (1)
pacman  (1)
tracing  (1)
Cursor  (1)
VSCode  (1)
PHP  (1)
Laravel  (1)