簡體   English   中英

通過迭代器從字符串中刪除空格到C ++ 11基於范圍的for循環中的字符串

[英]Deleting whitespace from a string via an iterator to the string in a C++11 range-based for loop

我只是嘗試使用C ++ 11的基於范圍的for循環從字符串中刪除所有空格; 但是,我一直在basic_string::erase上獲得std::out_of_range

#include <iostream>
#include <string>
#include <typeinfo>

int main(){

  std::string str{"hello my name is sam"};

  //compiles, but throws an out_of_range exception
  for(auto i : str){
    std::cout << typeid(i).name();  //gcc outputs 'c' for 'char'
    if(isspace(i)){
      str.erase(i);
    }
  }
  std::cout << std::endl;

  //does not compile - "invalid type argument of unary '*' (have 'char')"
  for(auto i : str){
    if(isspace(*i)){
      str.erase(i);
    }
  }

  //works exactly as expected
  for(std::string::iterator i = begin(str); i != end(str); ++i){
    std::cout << typeid(*i).name();  //gcc outputs 'c' for 'char'
    if(isspace(*i)){
      str.erase(i);
    }
  }
  std::cout << std::endl;

}

所以我想知道:究竟什么是i的第一個兩個環? 為什么它看起來既是char (由typeid驗證)又是chariterator (與std::string::erase )? 為什么它不等同於最后一個循環中的iterator 在我看來,它們應該完全相同。

基於范圍的for循環中的i類型是char ,因為字符串的元素是字符(更正式地說, std::string::value_typechar的別名)。

為什么它似乎迭代器當你通過它來工作的原因erase()是一個過載erase()存在接受索引和計數,但后者有一個默認的說法:

basic_string& erase( size_type index = 0, size_type count = npos );

在您的實現上, char恰好可以隱式轉換為std::string::size_type 但是,這可能沒有達到預期效果。

要驗證i確實不是迭代器,請嘗試解除引用它,您將看到編譯器尖叫:

*i; // This will cause an error

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM