Aditya Goel Aditya Goel - 1 year ago 65
C++ Question

Unexpected behavior when pushing a character to vector of strings

I'm trying to insert a character into vector of strings by converting it to a string first but case 1 is not working but case 2 is working. Can somebody explain the behavior. Any workaround to insert char directly into vector?

// vector of strings
vector lt; std::string gt; out;
// EDIT - stack overflow is not letting me post "less than" sign so using lt; and gt; instead

// a character
char ch;

// assign some value to ch and push to vector

// CASE 1: don't work
out.push_back("" + ch);

// CASE 2: works
string str = "";
out.push_back(str + ch);

PS - I'm using C++14

Answer Source

The term "" does not represent a std::string instance, rather it is a const char* literal therefore when you add ch to it you are performing pointer arithmetic and will likely receive a compiler warning along the lines of:

warning: array subscript is above array bounds

To push_back a char as a std::string to a std::vector<std::string> simply do:

std::vector<std::string> vec;
char ch = 'a';
vec.push_back(std::string()+ch); // construct empty std::string, add ch, push_back
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download