简介:读入一段文本到 vector 对象,每个单词存储为 vector 中的一个元素
读入一段文本到 vector 对象,每个单词存储为 vector 中的一个元素
在C++中,std::vector是一种非常有用的数据结构,它能够动态地存储多个元素。当我们需要处理一段文本,例如一个句子或一篇文章,并且需要将每个单词存储为一个独立的元素时,我们可以使用std::vector来完成这项任务。下面是一个简单的例子,展示如何从一段文本中读取单词,并将它们存储在std::vector中。
首先,我们需要包含一些必要的头文件。这里我们使用了<iostream>用于输入输出,<vector>用于使用std::vector,以及<string>用于处理字符串。
#include <iostream>#include <vector>#include <string>
接下来,我们定义一个函数,该函数接受一个字符串(代表一段文本)和一个std::vector<std::string>对象。该函数将读取文本中的每个单词,并将它们添加到std::vector中。
void readTextIntoVector(const std::string& text, std::vector<std::string>& words) {std::string word;std::istringstream iss(text); // 将输入流从 string 创建到这个 streamwhile (iss >> word) { // 从这个 stream 中读取每个单词words.push_back(word); // 将每个单词添加到 vector 中}}
这个函数使用了std::istringstream类,它是一个输入流,可以从字符串中读取数据。我们通过将输入流与文本关联起来,然后使用输入流运算符(>>)来读取每个单词。每次读取一个单词后,我们使用push_back方法将其添加到std::vector中。
现在我们可以测试这个函数了。首先,我们创建一个包含一些文本的字符串,并初始化一个空的std::vector<std::string>对象。然后我们调用函数,将文本中的每个单词添加到std::vector中。
int main() {std::string text = "这是一段测试文本。它包含一些单词和标点符号。";std::vector<std::string> words;readTextIntoVector(text, words);// 输出 vector 中的每个单词for (const auto& word : words) {std::cout << word << std::endl;}return 0;}
在这个例子中,我们使用了C++11的for each循环(也称为范围for循环),它允许我们遍历std::vector中的每个元素。对于每个单词,我们使用std::cout将其打印到控制台。