c++vectorinitializer-list

Could not convert from ‘<brace-enclosed initializer list>’ to vector


The following vector declaration:

vector<string> valid_escape = {'n', 't', 'r', '0', '\\'};  

Causes the error:

error: could not convert ‘{'n', 't', 'r', '0', '\\'}’ from ‘<brace-enclosed initializer list>’ to ‘std::vector<std::__cxx11::basic_string<char> >’

Other SO posts about this issue came to the conclusion that its a bug in 4.7 version of gcc or that an -std=c++11 flag wasn't mentioned in compilation.

My gcc version is 7.3.0 and I compiled with the above flag.

Just out of curiosity and narrow hope I tried to replace vector with list and got a similar error.


Solution

  • The std::string container has no constructor that takes a single character, to use single characters in this initialization you'd need an initializer list.

    string x = 'a';   // not possible, no constructor exists
    string x = "a";   // possible, string(const char* s)
    string x = {'a'}; // possible, string(initializer_list<char> il)
    

    If you need a std::vector of std::strings intialized with a single std::string composed by those characters, you need an extra brace initializer:

    vector<string> valid_escape = {{'n', 't', 'r', '0', '\\'}};
    

    The inner brace will initialize a string with the given characters, the outer brace will construct a vector with that string at index 0.

    Which, may not be worth the complication as you could simply use:

    vector<string> valid_escape = {"ntr0\\"};
    

    If you want a std::vector containing several std::strings each one initialized with a single character you would need:

    vector<string> valid_escape = {{'n'}, {'t'}, {'r'}, {'0'}, {'\\'}};
    

    But again, you could use a simpler construct to achieve the same result:

    vector<string> valid = {"n", "t", "r", "0", "\\"};