0

我正在尝试遍历字符串向量以及字符串的每个字符:

但我得到一个错误: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++ 真的很陌生。

4

2 回答 2

7

你的问题在这里:

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

它应该是:

if(s[i][j] != '-') // note the single quotes - double quotes denote a character string
于 2013-09-23T21:01:48.827 回答
3

现在另一个答案已经确定了您陈述中的问题,这是一种在一行中实现相同结果的现代化方法:

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 的 lambda 来执行二维计数:

  • accumulate一次遍历一个字符串,并调用顶级 lambda
  • count_if逐个字符地遍历您的字符串,计算非破折号字符的数量。

这是关于 ideone 的演示

于 2013-09-23T21:11:39.767 回答