【问题标题】:Any faster way to calcuate the number of strings in a istringstream任何更快的方法来计算字符串流中的字符串数
【发布时间】:2013-02-24 23:34:51
【问题描述】:

我正在尝试检查一行是否正好有 10 个单词。我这样做的方式是复制该行,并逐个提取并增加计数器,如果它是10,我操纵该行。但我觉得这非常低效,因为我必须对每一行都这样做,而且大多数行都是 10 个单词。所以我正在寻找一种更有效的方法来做到这一点。

    while(getline(ifs, line)){
        istringstream iss (line);
        int s_counter = 0;
        istringstream iss_copy = iss;   //create a copy to test if there are 10 strings in a iss
        string s;
        while (iss_copy >> s){
            ++s_counter;
        }
        if (s_counter == 10){
            while(iss>>word){   
                ...//manipuate each word                
            }
        }
    }

【问题讨论】:

  • 可以只计算行中的空间吗?
  • 我不认为在考虑是否应该优化代码时应该考虑到感觉..
  • @billz 我想过,但本质上不是一样的想法吗?
  • @HoKy22 我的意思是:ideone.com/tOfybI,你保存 istringstream 操作
  • @billz 好主意,但实际代码如下所示:AH Ks Js AD Ac 6c 10s 9H 8s 7H //blah blah blah.. 我实际上只讨论之前的部分 //

标签: c++ string counter


【解决方案1】:

我是这样做的:

int main()
{
  std::string s1("hi hi hi hi //blah");
  size_t pos = s1.find('/');  
  std::cout << std::count(s1.begin(), s1.begin()+pos, ' ') << std::endl;
  return 0;
}

int countSpace(const std::string& s)
{
  int count = 0;

   for(size_t i=0; i<s.size()-1; i++)
   {
     if (s[i] == ' ')
     {
       count++;
     }
     if (s[i+1] == '/')
     {
       return count;
     }
   }
   return count;
}


int main()
{
  std::string s1("hi hi hi hi //blah");
  countSpace(s1);
  return 0;
}  

【讨论】:

  • 我喜欢 STL 算法的方式。它应该比你提供的其他方式更快吗?
  • 也许 STL 1 比较慢,因为它确实找到了两次。
【解决方案2】:

您可以更有效地使用 STL 算法。

template<typename charT>
struct CntSpaceFunctor {
    bool isEnd ;
    std::size_t value ;
    CntSpaceFunctor( ) : isEnd(false),value(0) {} 

    inline void operator()( charT ch ) const {
         if( ch == charT(' ') && !isEnd)  ++value ;
         else if( ch == charT('/') )      isEnd = true ;
         else ;
    }
};
int countSpace( const string& str ) {
    CntSpaceFunctor<char> result ;
    return for_each( str.begin() , str.end() , result ).value ;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-17
    • 1970-01-01
    • 1970-01-01
    • 2010-10-31
    • 1970-01-01
    • 1970-01-01
    • 2021-11-23
    相关资源
    最近更新 更多