[英]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
驗證)又是char
的iterator
(與std::string::erase
)? 為什么它不等同於最后一個循環中的iterator
? 在我看來,它們應該完全相同。
基於范圍的for
循環中的i
類型是char
,因為字符串的元素是字符(更正式地說, std::string::value_type
是char
的別名)。
為什么它似乎迭代器當你通過它來工作的原因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.