DEV Community

edo1z
edo1z

Posted on

c++23で順列を扱う

c++23にする

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

g++ -std=c++23 hoge.cpp -o hoge.out
Enter fullscreen mode Exit fullscreen mode

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

{
  "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
      }
    }
  ]
}

Enter fullscreen mode Exit fullscreen mode

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

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

順列

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);
}
Enter fullscreen mode Exit fullscreen mode

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

012
021
102
120
201
210
Enter fullscreen mode Exit fullscreen mode

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay