Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/139.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 无法在正确循环时获得秒数_C++ - Fatal编程技术网

C++ 无法在正确循环时获得秒数

C++ 无法在正确循环时获得秒数,c++,C++,我正在制作一个从字符串中删除元素的函数。然而,我似乎无法让我的两个循环一起工作。第一个while循环完美地工作。我研究了它,我相信这可能是因为当“find_last_of”没有找到时,它仍然返回一个值(这将抛出我的循环)。我还没弄明白怎么才能修好它。多谢各位 #include <iostream> #include <string> using namespace std; string foo(string word) { string compa

我正在制作一个从字符串中删除元素的函数。然而,我似乎无法让我的两个循环一起工作。第一个while循环完美地工作。我研究了它,我相信这可能是因为当“find_last_of”没有找到时,它仍然返回一个值(这将抛出我的循环)。我还没弄明白怎么才能修好它。多谢各位

#include <iostream>
#include <string>

using namespace std;

   string foo(string word) {
      string compare = "!@#$";
      string alphabet = "abcdefghijklmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    while(word.find_first_of(compare) < word.find_first_of(alphabet)) {
        int position = word.find_first_of(compare);
        word = word.substr(++position);
    }
           while(word.find_last_of(compare) > word.find_last_of(alphabet)){
              int size = word.length();
              word = word.substr(0, --size);
         }  
    return word;
}

int main() {
    cout << foo("!!hi!!");

    return 0;
}
#包括
#包括
使用名称空间std;
字符串foo(字符串字){
字符串比较=“!@#$”;
字符串字母表=“abcdefghijklmnopqrstuvxyzabcdefghijklmnopqrstuvxyz”;
while(word.find_first_of(compare)word.find_last_of(字母表)){
int size=word.length();
word=word.substr(0,--大小);
}  
返回词;
}
int main(){

cout还不完全清楚您想做什么,但是用以下内容替换第二个循环如何:

string::size_type p = word.find_last_not_of(compare);
if(p != string::npos)
  word = word.substr(0, ++p);

现在还不清楚您是否只想从
word
的前面和后面修剪某些字符,或者您是否想从
word
中删除某组字符中的每一个,无论它们位于何处。根据您问题的第一句话,我假设您想执行后一种操作:删除
compare来自
word

更好的策略是更直接地检查每个字符是否需要删除,如果需要,则一次通过
word
。由于
compare
非常短,类似这样的方法可能就足够了:

// Rewrite word by removing all characters in compare (and then erasing the
// leftover space, if any, at the end).  See std::remove_if() docs.
word.erase(std::remove_if(word.begin(), 
                          word.end(),
                          // Returns true if a character is to be removed.
                          [&](const char ch) {
                            return compare.find(ch) != compare.npos;
                          }),
           word.end());

顺便说一句,我不知道为什么在您的示例中既有
compare
字符串又有
alphabet
字符串。似乎您只需要定义一个或另一个,而不是两个。一个字符要么保留一个,要么删除一个。

如果找不到匹配项,则
find_last_
返回的值称为
npos
和未签名,值为
-1
(它将转换为
size\u type
的最大值。请专门检查它,然后进行比较,或者进行一点重构。抱歉,我要查找的结果是“hi”(没有任何额外字符)。@user2780598:这样就可以了。非常感谢!