std::basic_string::resize - cppreference.com

##### cppreference.com

##### Search

Create account

##### Namespaces

- Page
- Discussion

##### Variants

##### Views

- View
- Edit
- History

##### Actions

# std::basic_string::resize

From cppreference.com
< cpp‎ | string‎ | basic string

void resize( size_type count ); | (1) |
void resize( size_type count, CharT ch ); | (2) |

Resizes the string to contain `count` characters.

If the current size is less than `count`, additional characters are appended.

If the current size is greater than `count`, the string is reduced to its first `count` elements.

The first version initializes new characters to CharT(), the second version initializes new characters to `ch`.

### [edit] Parameters

count | - | new size of the string
ch | - | character to initialize the new characters with

### [edit] Return value

(none)

### [edit] Exceptions

std::length_error if count > max_size(). Any exceptions thrown by corresponding `Allocator`.

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

### [edit] Example

Run this code

    #include <iostream>
    #include <stdexcept>

    int main()
    {
        std::string s;

        try {
            // size is OK, no length_error
            // (may throw bad_alloc)
            s.resize(s.max_size() - 1, 'x');
        } catch (std::bad_alloc&) {
            std::cout << "1. bad alloc\n";
        }

        try {
            // size is OK, no length_error
            // (may throw bad_alloc)
            s.resize(s.max_size(), 'x');
        } catch (std::bad_alloc& exc) {
            std::cout << "2. bad alloc\n";
        }

        try {
            // size is BAD, throw length_error
            s.resize(s.max_size() + 1, 'x');
        } catch (std::length_error&) {
            std::cout << "3. length error\n";
        }
    }

Possible output:

    1. bad alloc
    2. bad alloc
    3. length error

### [edit] Complexity

Linear in the size of the string.

### [edit] See also

sizelength | returns the number of characters (public member function) [edit]

Retrieved from "http://en.cppreference.com/mwiki/index.php?title=cpp/string/basic_string/resize&oldid=66408"