首页 > 解决方案 > 如何将字符插入字符串向量

问题描述

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

编译器-1073741819在我运行时返回。

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

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

using namespace std;

int main()
{
    vector <string> instruction;

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

    return 0;
}

标签: c++stdvectorstdstring

解决方案


当您声明了一个模板类型的向量时,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[]的使用:这是错误的,因为它返回对您请求的索引处的元素的引用。当你使用它的那一刻(在你的代码中),没有可用的元素,因此它的使用会导致你不确定的行为


在您提到的评论中:

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

如果您打算将字符连接到向量元素(这是字符串类型),您可以使用字符串的operator+=将新字符添加到已经存在的字符串元素。

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就像你尝试的那样。但在后一种情况下,您还需要在向量中存在一个字符串(空或非空)元素。


推荐阅读