如何使用向量为字符串赋值

How to assign values to String using vector?

本文关键字:字符串 赋值 向量 何使用      更新时间:2023-10-16
struct Books{
std::string title;
std::string author;
std::string des;
int book_id = 0;
char identifier;
} ;
// book 0
book[0].title = "Programming Fundamentals"; // subscript out of range
book[0].author, "Robert Hanks";
book[0].des, "Programming Basics";
book[0].book_id = 101;
book[0].identifier = 'P';
// Struct Object
std::vector <Books> book;

当我尝试编译上面的代码时,它会给我一个超出范围的下标错误。

我做错了什么吗?

谢谢。

您创建了一个空向量并尝试通过语句访问book[0]其元素,这是不正确的。 在使用 book[0] 访问向量之前,您需要在向量中至少包含一个元素。

初始化向量

以在向量中至少包含一个元素。我在下面举一个例子来修复它。

  // Struct Object
  std::vector <Books> book(1);
  // book 0
  book[0].title = "Programming Fundamentals"; // subscript out of range
  ....
  ....