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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Image of DataStax

AI Agents Made Easy with Langflow

Connect models, vector stores, memory and other AI building blocks with the click of a button to build and deploy AI-powered agents.

Get started for free

👋 Kindness is contagious

Please show some love ❤️ or share a kind word in the comments if you found this useful!

Got it!