2013-09-23 39 views
0

我米試圖遍歷串的矢量,和在所述字符串的每一個字符:迭代向量串的字符(C++禁止指針和整數之間的比較)

但我得到一個錯誤:C++禁止比較指針和整數之間。

In member function ‘int LetterStrings::sum(std::vector<std::basic_string<char> >)’: 

error: ISO C++ forbids comparison between pointer and integer [-fpermissive]| 

以下是我的代碼:

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

using namespace std; 

class LetterStrings { 
    public: 
     int sum(vector <string> s) { 
      int i, j = 0; 
      int count = 0; 
      for(i=0;i<s.size();i++) { 
       for(j=0;j<s[i].length();j++) { 
        if(s[i][j] != "-") { 
         count ++; 
        } 
       } 
      } 
      return count; 
     } 
}; 

有人可以告訴我,什麼是錯我的代碼。

**我真的很陌生的C++。

+5

試一下[i] [j]!='-'' –

回答

7

你的問題是在這裏:

if(s[i][j] != "-") 

它應該是:

if(s[i][j] != '-') // note the single quotes - double quotes denote a character string 
+1

哦!那太容易了。謝謝! –

3

現在the other answer已經確定了你的聲明問題,這裏是一個現代化的方式來實現在一個相同的結果單行:

int count = accumulate(v.begin(), v.end(), 0, [](int p, string s) { 
    return p + count_if(s.begin(), s.end(), [](char c) {return c != '-';}); 
}); 

這個想法是使用C++ 11的lambdas來執行在兩個維度計數:

  • accumulate經歷一次矢量一個字符串,並調用頂級拉姆達
  • count_if經過你的字符串字符一個字符,計算非劃線的數量字符。

這是一個demo on ideone

相關問題