簡體   English   中英

c ++字符串迭代器

[英]c++ string iterator

我試圖在循環中使用迭代器在字符串上執行if語句,但無法弄清楚如何獲取if語句的當前字符:

for (std::string::iterator i=buffer.end()-1; i>=buffer.begin(); --i) {
    if (!isalpha(*i) && !isdigit(*i)) {
        if(i != "-") { // obviously this is wrong
            buffer.erase(i);
        }
    }
}

有人可以幫助我獲取當前字符,以便我可以做一些額外的if語句嗎?

我無法弄清楚如何獲得當前角色

你在這里做了兩次:

if (!isalpha(*i) && !isdigit(*i))

當您取消引用迭代器( *i )時,您將獲得它指向的元素。

"-"

這是一個字符串文字,而不是字符。 字符常量使用單引號,例如'-'

for (std::string::iterator i=buffer.end()-1; i>=buffer.begin(); --i)

使用反向迭代器會更簡單:

for (std::string::reverse_iterator i = buffer.rbegin(); i != buffer.rend(); ++i)
if(i != "-")

應該

if(*i != '-')

要讓角色只說*i ,但這還不夠。 你的循環不合法,因為它不允許在begin之前遞減。 您應該使用反向迭代器或remove_if算法。

其他答案已經解決了您遇到的特定問題,但您應該知道有不同的方法來解決您的實際問題: 擦除滿足條件的元素 這可以通過刪除/擦除習慣用法輕松解決:

// C++0x enabled compiler
str.erase( 
    std::remove_if( str.begin(), str.end(), 
                  [](char ch) { return !isalpha(ch) && !isdigit(ch) && ch != '-' } ),
    str.end() );

雖然這看起來可能看起來很麻煩,但是一旦你看到它幾次就不再令人驚訝了,它是從向量或字符串中刪除元素的有效方法。

如果您的編譯器沒有lambda支持,那么您可以創建一個仿函數並將其作為remove_if的第三個參數傳遞:

// at namespace level, sadly c++03 does not allow you to use local classes in templates
struct mycondition {
   bool operator()( char ch ) const {
      return !isalpha(ch) && !isdigit(ch) && ch != '-';
   }
};
// call:
str.erase( 
    std::remove_if( str.begin(), str.end(), mycondition() ),
    str.end() );

你在前面的if語句中就已經有了它: i是一個迭代器,所以*i給出了迭代器引用的字符。

請注意,如果您要向后迭代集合,通常更容易使用帶有rbeginrendreverse_iterator 我可能會使用預先打包的算法。

暫無
暫無

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

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