21xrx.com
2025-04-09 03:08:28 Wednesday
文章检索 我的文章 写文章
C++ 中 vector 的使用方法 - 输入字符串
2023-07-05 02:01:52 深夜i     47     0
C++ vector 使用方法 输入 字符串

在 C++ 中,vector 是一个非常常用的容器,它可以存储任何类型的数据,并且可以动态添加或删除元素。在这篇文章中,我们将学习如何使用 vector 来输入字符串。

在使用 vector 之前,我们需要包含 vector 的头文件:

#include <vector>

接下来,我们可以定义一个 vector 变量来存储字符串:

std::vector<std::string> myVector;

在这个例子中,我们定义了一个名为 myVector 的 vector 变量,它将存储字符串类型的数据。

要向 vector 中添加字符串,我们可以使用 push_back() 函数。这个函数将添加一个元素到 vector 的尾部。例如:

myVector.push_back("Hello");

这个例子将添加一个字符串 "Hello" 到 myVector 的尾部。

要从控制台输入字符串并将它们添加到 vector 中,我们可以使用 std::getline() 函数。这个函数将读取一行文本输入,并将其存储在一个字符串变量中。例如:

#include <iostream>
#include <string>
#include <vector>
int main() {
 // Define a vector to store strings.
 std::vector<std::string> myVector;
 
 // Read strings from the console and add them to the vector.
 std::string input;
 while (std::getline(std::cin, input)) {
  myVector.push_back(input);
 }
 
 // Print all the strings in the vector.
 for (int i = 0; i < myVector.size(); i++) {
  std::cout << myVector[i] << std::endl;
 }
 
 return 0;
}

在这个程序中,我们定义了一个 vector 名为 myVector,然后使用 while 循环来读取控制台输入,并将输入添加到 myVector 中。最后,我们使用一个循环来输出 myVector 中的所有字符串。

这就是使用 vector 来输入字符串的方法。现在你可以在 C++ 中轻松地处理字符串输入并将其存储在 vector 中了。

  
  

评论区

请求出错了