【问题标题】:"How do I return the first and last index of a string, into a vector, with C++?“如何使用 C++ 将字符串的第一个和最后一个索引返回到向量中?
【发布时间】:2020-01-28 01:04:46
【问题描述】:

这是 Edabit 的一个编码问题。我正试图专注于我在 C++ 中解决问题的技能。

问题是从字符串中返回字符的第一个和最后一个索引。对于std :: string word(第一个参数)中的char c(第二个参数)的每个实例,我认为我需要将(char c)与push_back一起推送到一个空字符串并从该空字符串返回第一个和最后一个索引。或者我可以简单地使用从原始字符串中提取字符的第一个和最后一个实例吗 (例如:std::string word.being())?

到目前为止,我已经在下面包含了一些代码。我只是坚持如何用语法实现我的想法。我认为我的想法是正确的,但不知道如何去做。我不想要一个确切的答案,只是一个关于下一步做什么的指南。

std::vector<int> charIndex(std::string word, char c) {
    std::string newWord = "";
    for(int i = 0; i < word.size(); ++i){
        std::string size.push_back[i] = newWord;
        //for every instance of char c in std::string word, I need to 
        //push that (char c) to empty string and return first and last index
        if(newWord[i] ==  )
    }
}

这些是预期结果的示例:

charIndex("circumlocution", "c") ➞ [0, 8]
The first "c" has index 0, the last "c" has index 8.
charIndex("happy", "h") ➞ [0, 0]
Only one "h" exists, so the first and last index is 0.

【问题讨论】:

  • 所以你知道std::find
  • 这个赋值实际上是两行 C++ 代码,使用std::find 并将[first, last] 结果放入类似std::pair&lt;int, int&gt; 的东西中。不需要循环、堆栈或任何类似的东西。
  • 我想您可能会发现std::string::find_first_of 很有用。如果您阅读链接文档页面的底部,您会找到其他有用实用程序的链接,这些实用程序可用于解决问题的其他部分。

标签: c++ arrays string vector


【解决方案1】:

知道了!!

vector<int> arr;
arr[0] = word.find_first_of(c);
arr[1] = word.find_last_of(c);
return arr;

谢谢大家!!

【讨论】:

  • 这是一个超出范围的索引(未定义的行为)。只需执行 return {a, b}; 其中 a 和 b 是您想要的值
  • std::vector&lt;int&gt; charIndex(std::string word, char c) {return {word.find_first_of(c), word.find_last_of(c)};}。但是vector&lt;int&gt; arr; arr[0] = word.find_first_of(c); 不正确。
  • 哦,我什至不知道什么是越界。我将其更改为返回 {a,b};
猜你喜欢
  • 2013-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-09
  • 2021-05-26
  • 1970-01-01
  • 2010-12-16
  • 2011-01-23
相关资源
最近更新 更多