2つのアレイをC++で連結します
この投稿では、C++で2つのアレイを連結する方法について説明します。
1.使用する std::copy
推奨される解決策は、 std::copy
から <algorithm>
2つのアレイを連結するヘッダー。アイデアは、両方のアレイのすべての値を格納するのに十分な大きさのメモリを割り当ててから、値を新しいアレイにコピーすることです。 std::copy
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <iostream> using namespace std; int main() { int first[] = {1, 2, 3}; int second[] = {4, 5}; int m = sizeof(first) / sizeof(*first); int n = sizeof(second) / sizeof(*second); int result[m + n]; std::copy(first, first + m, result); std::copy(second, second + n, result + m); for (int &i: result) { std::cout << i << ' '; } return 0; } |
出力:
1 2 3 4 5
The std::copy
関数は、要素がコピーされた範囲の最後にイテレータを返します。したがって、コードは次のように短縮できます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <iostream> #include <algorithm> using namespace std; int main() { int first[] = {1, 2, 3}; int second[] = {4, 5}; int m = sizeof(first) / sizeof(*first); int n = sizeof(second) / sizeof(*second); int result[m + n]; std::copy(second, second + n, std::copy(first, first + m, result)); for (int &i: result) { std::cout << i << ' '; } return 0; } |
出力:
1 2 3 4 5
または、 std::copy_n
最初のアルゴリズムをコピーする標準アルゴリズム n
結果までの指定範囲の要素。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <iostream> #include <algorithm> using namespace std; int main() { int first[] = {1, 2, 3}; int second[] = {4, 5}; int m = sizeof(first) / sizeof(*first); int n = sizeof(second) / sizeof(*second); int result[m + n]; std::copy_n(second, n, std::copy_n(first, m, result)); for (int &i: result) { std::cout << i << ' '; } return 0; } |
出力:
1 2 3 4 5
2.使用する std::memcpy
The std::memcpy
のアレイのバイナリコピーを実行します POD(プレーンオールドデータ)タイプ int、charなどのように。これを使用して、PODタイプの2つのアレイを連結できます。ヘッダーで宣言されています <cstring>
。これを以下に示します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include <iostream> #include <cstring> using namespace std; int main() { int first[] = {1, 2, 3}; int second[] = {4, 5}; int m = sizeof(first) / sizeof(*first); int n = sizeof(second) / sizeof(*second); int result[m + n]; std::memcpy(result, first, sizeof(first)); std::memcpy(result + m, second, sizeof(second)); for (int &i: result) { std::cout << i << ' '; } return 0; } |
出力:
1 2 3 4 5
3.フォールド式の使用
C++ 17では、 折り畳み式 std::arraysのシーケンスを連結します。このエレガントで効率的なソリューションを以下に示します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
#include <iostream> #include <array> #include <algorithm> using namespace std; template <typename Type, std::size_t... sizes> auto concatenate(const std::array<Type, sizes>&... arrays) { std::array<Type, (sizes + ...)> result; std::size_t index{}; ((std::copy_n(arrays.begin(), sizes, result.begin() + index), index += sizes), ...); return result; } int main() { std::array<int, 3> first = {{1, 2, 3}}; std::array<int, 2> second = {{4, 5}}; auto result = concatenate(first, second); for (auto &i: result) { std::cout << i << ' '; } return 0; } |
出力:
1 2 3 4 5
これが、C++で2つのアレイを連結することです。