简体   繁体   中英

Append a char to a std::vector<string> at a specific location

I've looked everywhere and although I've found how to insert std::string into vector<char> , I can't find a way to insert a char into a std::vector<std::string>

In a text editor project, I'm restricted to using a vector of strings, while the thing that checks when a character is input to the text editor must take in a char and returns a char.

If I know where I am going to insert a character into this vector, what can I call to make this happen?

As a side note, I tried doing lines.push_back(&c) where I define lines as std::vector<std::string> , but it says:

candidate function not viable: no known
      conversion from 'char' to 'const value_type' (aka 'const std::__1::basic_string<char,
      std::__1::char_traits<char>, std::__1::allocator<char> >') for 1st argument
    _LIBCPP_INLINE_VISIBILITY void push_back(const_reference __x);

If you want to append the vector with a new element that will have only one character you can write

std::vector<std::string> v;

//...

v.push_back( { 1, 'A' } );

If you want to append a character to already existent element of the vector you can write

std::vector<std::string> v;

//...

v[i] += 'A';

or

std::vector<std::string> v;

//...

v[i].push_back( 'A' );

If you want to insert a character inside a string of some existent element of the vector you can write

std::vector<std::string> v;

//...

v[i].insert( position, 1, 'A' );

如果要在特定向量中的特定位置插入字符:

lines[i].insert(j, 1, c);

Hope below code snippet helps,

  std::vector<std::string> line;
  string s(1, c); 
  lines.push_back(s);

For vector of std::string. Then you have convert the c char to std::string and insert into vector.

You can't insert a char into a vector of strings. You'll have to convert that char into a string. You can do that with this roundabout way:

string s = "";
char c = 'a';
s += c;

or more directly:

string s(1,c);

Then just push the string into the vector:

lines.push_back(s);

If you want to insert this into a specific position, you'll have to calculate the position and then:

lines.insert(position, s);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM