Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/string/basic string/push back"

From cppreference.com
< cpp‎ | string‎ | basic string
m (Exceptions: fmt)
m (Add simple example)
Line 28: Line 28:
  
 
If the operation would result in {{c|size() > max_size()}}, throws {{lc|std::length_error}}.
 
If the operation would result in {{c|size() > max_size()}}, throws {{lc|std::length_error}}.
 +
 +
===Example===
 +
{{example
 +
| code=
 +
#include <cassert>
 +
#include <string>
 +
#include <iostream>
 +
 +
int main()
 +
{
 +
    std::string str("Short string");
 +
    std::cout << "before='" << str << "'\n";
 +
    assert(str.size() == 12);
 +
 +
    str.push_back('X');
 +
    std::cout << " after='" << str << "'\n";
 +
    assert(str.size() == 13);
 +
}
 +
| output=
 +
before='Short string'
 +
after='Short stringX'
 +
}}
  
 
===See also===
 
===See also===

Revision as of 14:35, 18 January 2022

 
 
 
std::basic_string
Member functions
Element access
Iterators
Capacity
Modifiers
basic_string::push_back
Search
Operations
Constants
Non-member functions
I/O
Comparison
(until C++20)(until C++20)(until C++20)(until C++20)(until C++20)(C++20)
Numeric conversions
(C++11)(C++11)(C++11)
(C++11)(C++11)
(C++11)(C++11)(C++11)
(C++11)
(C++11)
Literals
Helper classes
Deduction guides (C++17)

 
void push_back( CharT ch );
(until C++20)
constexpr void push_back( CharT ch );
(since C++20)

Appends the given character ch to the end of the string.

Contents

Parameters

ch - the character to append

Return value

(none)

Complexity

Amortized constant.

Exceptions

If an exception is thrown for any reason, this function has no effect (strong exception guarantee).(since C++11)

If the operation would result in size() > max_size(), throws std::length_error.

Example

#include <cassert>
#include <string>
#include <iostream>
 
int main()
{
    std::string str("Short string");
    std::cout << "before='" << str << "'\n";
    assert(str.size() == 12);
 
    str.push_back('X');
    std::cout << " after='" << str << "'\n";
    assert(str.size() == 13);
}

Output:

before='Short string'
 after='Short stringX'

See also

removes the last character
(public member function) [edit]