如何将char插入字符串向量

时间:2018-09-19 18:14:25

标签: c++ stdvector stdstring

这不是将字符插入字符串向量中的正确方法吗?

运行时,编译器返回-1073741819

以下是代码,稍后我想在其中添加更多字符,'A'旁。

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

using namespace std;

int main()
{
    vector <string> instruction;

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

    return 0;
}

2 个答案:

答案 0 :(得分:0)

在您声明模板类型为std::string的向量时,不能在其中插入char,而只能在其中包含一个字符串。

如果要将单个字符串作为矢量元素,请执行以下操作:

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

关于std::vector::operator[]的用法:这是错误的,因为它会返回对所请求索引处元素的引用。当您在代码中使用它时,没有可用的元素,因此它的用法会导致您 undefind behavior


您在评论中提到:

  

然后我将在A旁边添加更多字符

如果您打算将字符连接到矢量元素(字符串类型),则可以使用字符串的operator+=将新字符添加到已经存在的字符串元素中( 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

或您尝试过的push_back。但是在后一种情况下,您还需要在向量中存在一个字符串(空或非空)元素。

答案 1 :(得分:0)

您必须首先将第一个字符串添加到向量中,才能使用字符串对象的方法push_back

int main()
{
    vector <string> instruction;

    instruction.push_back("");
    instruction[0].push_back('A');
    return 0;
}

但是请记住,您可以简单地使用+=类的string运算符来获得相同的结果:

instruction[0] += 'A';