如何将向量的char元素合并为字符串元素

How to merge char element of a vector into a string element

本文关键字:元素 合并 字符串 char 向量      更新时间:2024-09-26

我有两个向量。一个字符向量包含元素,每个元素都存储一个段落的字符(包括点。另一个是字符串向量,每个元素应该存储由第一个向量创建的单词。

这是我的代码:

#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string source = "Vectors are sequence containers representing arrays that can change in size!";
vector<char> buf(source.begin(),source.end());
vector<string> word;
size_t n = 0;
size_t l = 0;
for (size_t k = 0; k < buf.size(); k++) {
if (buf[k] == ' ' || buf[k] == '') { 
for (size_t i = n; i < k; i++) {
word[l] = word[l] + buf[i];
}
n = k + 1;
l++;
}
}
for (size_t m = 0; m < word.size(); m++) {
cout << word[m] << endl;
}
return 0;
}

然后系统说:

表达式:向量下标超出范围

"这个项目";已触发断点

当然,我已经尝试了很多方法将buf元素连接到单个word元素中(使用.push_back()to_string()…(,但它总是会出错。我不尝试使用普通数组或const char*数据类型,因为我的练习要求我只使用stringvector

如果问题是从字符串source创建单词向量,有更简单的方法。

例如,如果你记得输入提取运算符CCD_;单词";(空格分隔的字符串(,然后您可以将其用于可以从字符串中读取的输入流,如std::istringstream

如果您了解到有一个std::vector构造函数重载占用了两个迭代器,并且有一个用于输入流迭代器的类,那么您可以将其组合成一个简单的三语句程序:

std::string source = "Vectors are sequence containers representing arrays that can change in size!";
std::istringstream source_stream(source);
std::vector<std::string> words(
std::istream_iterator<std::string>(source_stream),
std::istream_iterator<std::string>());

现在矢量words将包含source字符串中的单词,并且可以逐个打印:

for (auto& w : words)
{
std::cout << w << 'n';
}

这里有一种方法:

#include <stdio.h>
#include <algorithm>
#include <string>
#include <vector>
int main() {
std::string const source =
"Vectors are sequence containers representing arrays that can change in size!";
std::vector<std::string> words;
for (auto ibeg = source.begin(), iend = ibeg;;) {
iend = std::find(ibeg, source.end(), ' ');
words.emplace_back(ibeg, iend);
if (iend == source.end()) break;
ibeg = iend + 1;
}
for (auto const& w : words) puts(w.c_str());
}