【问题标题】:How to merge char element of a vector into a string element如何将向量的char元素合并为字符串元素
【发布时间】:2021-05-17 17:27:38
【问题描述】:

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

这是我的代码:

#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] == '\0') { 
            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

【问题讨论】:

  • 请参阅herehere,了解将句子标记为单个单词的示例。
  • 你永远不会 push_backresize 向量 word 所以这样做 word[l] = ... 是写越界,因此是未定义的行为
  • 矢量buf 真的完全没用。您可以直接在 source 上以完全相同的方式进行迭代。

标签: c++ arrays string vector compiler-errors


【解决方案1】:

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

例如,如果您记得输入提取运算符 &gt;&gt; 读取“单词”(以空格分隔的字符串),那么您可以将它用于可以读取字符串的输入流,例如 std::istringstream

如果你知道有一个 std::vector constructor overload 有两个迭代器,并且有一个 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';
}

【讨论】:

    【解决方案2】:

    这是一种方法:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-27
      • 2016-02-01
      • 2021-11-25
      • 2016-08-30
      • 2016-12-22
      • 1970-01-01
      • 1970-01-01
      • 2014-09-27
      相关资源
      最近更新 更多