0

我正在尝试做http://www.spoj.com/problems/SHLIGHTS/,为此我设计了一个解决方案。我对 C++ 很陌生(大约 14 天),我面临很多问题。之前我用过Python,没有出现这些错误,反正我写了这个..

#include <iostream>
#include <string>
#include <cstdio>
using namespace std;

//example is GBGBBB
//t=0, GBGBBB then t=1,BGBGBB then t=2 BBGBGB, then t=3 BBBGBG
//search for GB and replace it with BG

//we need a function that replaces things
string swapSEQ(string SEQ)
{
    unsigned int sizeSEQ=SEQ.size();
    unsigned int curr(0);
    while (curr<sizeSEQ-1)
    {
        if (SEQ[curr]=="G" and SEQ[curr+1]=="B")
        {
            SEQ[curr]="B";SEQ[curr+1]="G";curr+=2;
        }
        else {++curr;}
    }
    return SEQ;
}

int main()
{
    unsigned int numCases;
    scanf("%d",&numCases);
//  cin>>numCases;
    for (unsigned int currentCase=0;currentCase<numCases;++currentCase)
    {
        string SEQ;
        //scanf("%s",&SEQ);
        cin>>SEQ;
        string swapped=swapSEQ(SEQ);
        unsigned long long t=0;
        while (swapped!=SEQ)
        {
            swapped=swapSEQ(SEQ);++t;       
        }
        printf("%lld\n",t);

    }
    return 0;
}

我知道这是很多细节,但仅此而已。SPOJ 在输入和输出后显示空白行,但在阅读说明后,我知道我们必须在单行中执行操作。这是我使用 g++4.7 编译器(LINUX)得到的

SHLIGHTS.cpp: In function ‘std::string swapSEQ(std::string)’:
SHLIGHTS.cpp:17:18: error: comparison with string literal results in unspecified behaviour [-Werror=address]
SHLIGHTS.cpp:17:18: error: ISO C++ forbids comparison between pointer and integer [-fpermissive]
SHLIGHTS.cpp:17:37: error: comparison with string literal results in unspecified behaviour [-Werror=address]
SHLIGHTS.cpp:17:37: error: ISO C++ forbids comparison between pointer and integer [-fpermissive]
SHLIGHTS.cpp:17:52: error: invalid conversion from ‘const char*’ to ‘char’ [-fpermissive]
SHLIGHTS.cpp:17:66: error: invalid conversion from ‘const char*’ to ‘char’ [-fpermissive]
cc1plus: all warnings being treated as errors

*发生了什么?有一些关于指针、const char和未指定行为的东西。
**我知道指针是一种指向内存位置的变量,仅此而已。
**我在某些地方使用了 scanf,而在其他地方使用了 cin(如果我用 cin 替换 scanf,我会得到相同的错误)
**这是否与我返回一个作为参数的字符串有关?
**我在哪里使用了指针?
**我错了 - c++ 中的字符串是 char 数组吗?如果不是,那么无效转换在哪里?

在此先感谢,并为任何错误道歉。如果太长,请回答任何疑问。

4

2 回答 2

1
  1. 您需要SEQ[curr]'G'not进行比较,"G"因为它是 char 而不是字符串。
  2. 您应该使用运算符&&而不是and.
  3. 符合你逻辑的东西已经磨损了。在字符串的一个索引处,您只能有 1 个字符。所以写作if (SEQ[curr] == 'G' && SEQ[curr] == 'B'和写作一样if (false)
  4. 这不是错误,但请不要滥用您的代码,在一行中编写多个推荐。
  5. 如果您编写的是C++ ,请使用cin,而不是scanf.
  6. sizeSEQ如果你从不使用它,你为什么要创造它?不!
于 2013-07-19T10:32:04.523 回答
0

you should use 'G' instead of "G" and so on. When you access a char array (e.g. arr[5]) you obtain a char, which you can compare with a char literal (being: 'G') and not with a cstring (e.g. "G" or "Google").

The compiler is your friend, it points out that the problem is:

comparison with string literal

于 2013-07-19T10:27:27.270 回答