如何将向量的char元素合并为字符串元素
How to merge char element of a vector into a string element
我有两个向量。一个字符向量包含元素,每个元素都存储一个段落的字符(包括点。另一个是字符串向量,每个元素应该存储由第一个向量创建的单词。
这是我的代码:
#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*
数据类型,因为我的练习要求我只使用string
和vector
。
如果问题是从字符串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());
}
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用strcpy将char数组的元素复制到另一个数组
- 使用不带参数的函数访问结构元素
- 给定n个元素的m个集合.在C++中找到出现在最大集合数中的元素
- C++如何通过用户输入删除列表元素
- lower_bound()返回最后一个元素
- 基于多个条件处理地图中的所有元素
- 调整大小后指向元素值的指针unordered_map有效?
- 矢量是否<atomic_bool>涉及合并矢量元素?
- 就地合并,类似于 std::vector 中的元素
- 合并排序 - 仅对 2^n 个元素进行排序
- C++:合并两个以元组作为元素的向量
- 我们如何在 C++ 中合并数组的元素
- 在合并排序中选择中间元素
- 如何在不更改元素顺序的情况下合并两个unordered_maps
- 快速排序和合并排序坏内存分配(不对 32k 元素进行排序)
- 将多个集合元素合并为一个集合
- 合并共享一个共同元素的对
- c++成对合并列表元素