C++で文字列を文字のvectorに変換します
この投稿では、C++で文字列を文字のvectorに変換する方法について説明します。
1.範囲コンストラクターの使用
アイデアは、vectorクラスによって提供される範囲コンストラクターを使用することです。これは、入力イテレーターを範囲の最初と最後の位置に移動します。文字列を文字のvectorに変換するには、以下に示すように、入力イテレータを文字列の最初と最後に渡す必要があります。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <string> #include <vector> int main() { std::string s = "Hello World!"; std::vector<char> v(s.begin(), s.end()); for (const char &c: v) { std::cout << c; } return 0; } |
出力:
Hello World!
2.使用する std::copy
関数
標準のアルゴリズムを使用することもできます std::copy
バックインサーターを使用して、vectorの最後にある文字列の文字をコピーします。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <string> #include <vector> int main() { std::string s = "Hello World!"; std::vector<char> v; std::copy(s.begin(), s.end(), std::back_inserter(v)); for (const char &c: v) { std::cout << c; } return 0; } |
出力:
Hello World!
The std::back_inserter
を呼び出します std::push_back
内部で機能し、文字列内のすべての文字に対応するためのメモリ要件を処理します。
vectorに文字列内のすべての文字を収容するのに十分なメモリがすでにある場合は、入力イテレータをvectorの先頭に渡して、 std::copy
以下に示すように、アルゴリズム:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <string> #include <vector> int main() { std::string s = "Hello World!"; std::vector<char> v(s.length()); std::copy(s.begin(), s.end(), v.begin()); for (const char &c: v) { std::cout << c; } return 0; } |
出力:
Hello World!
これで、C++で文字列をcharのvectorに変換できます。