如何将向量的字符元素合并到字符串元素中

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

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

这是我的代码:

#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] == '[=10=]') { 
            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;
}

然后系统说:

Expression: vector subscript out of range

"this project" has triggered a breakpoint

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

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

例如,如果您记得输入提取运算符 >> 读取“单词”(space 分隔字符串),那么您可以将它用于您喜欢的输入流,该输入流可以从字符串,例如 std::istringstream.

如果你知道有一个 std::vector constructor overload taking two iterators, and that there is a class for input stream iterators 你可以把它组合成一个简单的三语句程序:

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());
}