0
votes

I want to insert a char which saved into a vector, to a string variable.

I'm using this code but I have get error:

result.insert(result.size(), G1[fromPos]);

in this code, G1 is a vector with char type and result is a string variable.

But I get this error:

no instance of overloaded function "std::basic_string<_Elem, _Traits, _Alloc>::insert [with _Elem=char, _Traits=std::char_traits, _Alloc=std::allocator]" matches the argument list argument types are: (size_t, char)

What I have to do to solve this problem?

2
possible duplicated ? - user1935024

2 Answers

2
votes

First of all, do not use result.size() as an index where a char should be placed, as it will result in a std::out_of_range exception:

If this (pos) is greater than the object's length, it throws out_of_range.

Secondly, according to the std::string::insert specification, to insert a single char you should use the following overload:

result.insert(index, 1, G1[fromPos]);

The best solution, if you want to append a single char to the end of a string, is to use:

result.push_back(G1[fromPos]);
1
votes

If you just want to append a char to a string, you can use the += operator.