【完全ガイド】C++の`std::string`クラスを操作する:`std::basic_string::push_back`の使い方


構文

void push_back(char ch);

引数

  • ch: 文字列に追加する単一の文字

戻り値

なし

動作

  1. std::string オブジェクトの内部ストレージに十分なスペースがあるかどうかを確認します。
  2. スペースがあれば、ch を末尾に追加します。
  3. スペースがない場合は、必要なスペースを確保するためにメモリを再割り当てします。
  4. 再割り当てが成功した場合、ch を末尾に追加します。
  5. 再割り当てが失敗した場合、length_error 例外をスローします。

#include <iostream>
#include <string>

int main() {
  std::string str = "Hello";

  str.push_back('!'); // 文字列の末尾に '!' を追加

  std::cout << str << std::endl; // 出力: Hello!

  return 0;
}

この例では、str という名前の std::string オブジェクトを作成し、"Hello" という文字列を初期化します。次に、push_back メンバー関数を使用して '!' という文字を末尾に追加します。最後に、変更された文字列の内容を std::cout に出力します。

  • push_back は、文字列の長さを 1 だけ増加させます。文字列の長さを変更するには、resize メンバー関数を使用する必要があります。
  • push_back は、文字列の末尾にのみ文字を追加します。文字列の任意の位置に文字を挿入するには、insert メンバー関数を使用する必要があります。
  • push_back は、単一の文字を追加するためにのみ使用できます。複数の文字を追加するには、append メンバー関数を使用する必要があります。


文字列の末尾に複数の文字を追加する

この例では、push_back をループ内で使用して、文字列の末尾に複数の文字を追加する方法を示します。

#include <iostream>
#include <string>

int main() {
  std::string str = "Hello";

  for (char ch : {'!', ' ', 'W', 'o', 'r', 'l', 'd'}) {
    str.push_back(ch);
  }

  std::cout << str << std::endl; // 出力: Hello! World

  return 0;
}

文字列を数値で構成する

この例では、push_back を使用して、数字を文字列に変換する方法を示します。

#include <iostream>
#include <string>

int main() {
  int n = 123;
  std::string str;

  while (n > 0) {
    str.push_back('0' + (n % 10));
    n /= 10;
  }

  std::string reversed_str = str; // 文字列を反転
  std::reverse(reversed_str.begin(), reversed_str.end());

  std::cout << "元の文字列: " << str << std::endl; // 出力: 321
  std::cout << "反転した文字列: " << reversed_str << std::endl; // 出力: 123

  return 0;
}

サロゲートペアを含む文字列を扱う

この例では、push_back を使用して、サロゲートペアを含む文字列を扱う方法を示します。

#include <iostream>
#include <string>

int main() {
  std::string str = "𝔘𝔫𝔦𝔠𝔬𝔡𝔢"; // サロゲートペアを含む文字列

  for (char ch : str) {
    std::cout << std::hex << static_cast<int>(ch) << " ";
  }

  std::cout << std::endl;

  return 0;
}

このコードは、各 Unicode コードポイントの 16 進数値を出力します。サロゲートペアは、2 つの 16 ビット UTF-16 コードユニットで構成されるため、2 つの値として表示されます。

これらの例は、std::basic_string::push_back の汎用性と、文字列操作の様々なタスクにどのように使用できるかを示しています。

上記の例では、可読性のために std::string オブジェクトの初期化に直接リテラル文字列を使用しています。しかし、実際のプログラムでは、ユーザー入力やファイルから文字列を読み込むなど、より動的な方法で文字列を初期化する方が一般的です。



std::string::append を使用する

std::string::append は、push_back と似ていますが、1 つ以上の文字 または 別の文字列 を末尾に追加することができます。

void append(const char* s);
void append(const char* s, size_t n);
void append(const std::string& str);

利点

  • push_back よりも汎用性が高い

欠点

  • 複数の文字列を追加する場合、パフォーマンスが低下する可能性がある
  • push_back よりも冗長になる場合がある


std::string str = "Hello";

str.append(", ");
str.append("World!");

std::cout << str << std::endl; // 出力: Hello, World!

イテレータを使用して直接文字を挿入する

std::string::iterator を使用して、文字列の末尾に直接文字を挿入することができます。

void insert(std::string::iterator it, char ch);

利点

  • 文字列の任意の位置に文字を挿入できる
  • push_back よりも効率的である場合がある

欠点

  • push_back よりも複雑でエラーが発生しやすい


std::string str = "Hello";

std::string::iterator it = str.end();
*it = '!';

std::cout << str << std::endl; // 出力: Hello!

文字列ストリームを使用して文字列を操作する

std::ostringstream を使用して、文字列をストリームとして操作し、末尾に文字を追加することができます。

std::ostringstream oss;

oss << "Hello" << ", " << "World!";

std::string str = oss.str();

std::cout << str << std::endl; // 出力: Hello, World!

利点

  • 読みやすく、理解しやすい

欠点

  • push_backappend よりもパフォーマンスが低下する可能性がある

Boost.C++ や STLport などのサードパーティ製ライブラリには、std::string を操作するための追加機能が含まれている場合があります。これらのライブラリには、push_back のより効率的な代替手段が含まれている場合があります。

利点

  • std::string の機能を拡張できる

欠点

  • 標準ライブラリの一部ではないため、すべての環境で使用できるわけではない

どの代替方法を使用するかは、特定の状況によって異なります。パフォーマンス、可読性、コードの複雑さのバランスを考慮する必要があります。