Search code examples
c++stdvectorstdstring

How to insert a char to a vector of strings


Isn't this the correct way to insert a character into a vector of strings?

The compiler returns -1073741819 when I run it.

Following is the code, in which I want to add more chars next to 'A' later.

#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main()
{
    vector <string> instruction;

    instruction[0].push_back( 'A' );

    return 0;
}

Solution

  • As you declared a vector with template type as std::string you can not insert char to it, instead you can only have a string inside.

    If you want to have a single character string as vector element, do simply:

    std::vector <std::string> instruction;
    // instruction.reserve(/*some memory, if you know already the no. of strings*/);
    instruction.push_back("A");
    

    Regarding your usage of std::vector::operator[]: that is wrong, because, it returns the reference to the element at the index you requested. The moment when you use it(in your code), there is no element available and hence it's usage leads you undefind behavior


    In the comments you mentioned that:

    I will then add more chars next to A

    If you meant to concatenate characters to the vector elements(which is string type), you can either use operator+= of string to add a new character to the already existing string element(s).

    std::vector <std::string> instruction;
    
    instruction.push_back("");  // create an empty string first
    instruction[0] += 'A';      // add a character
    instruction[0] += 'B';      // add another character
    

    or simply push_back as you tried. But in the latter case also you need to have a string(empty or non-empty) element existing in the vector.