2016-03-21 6 views
0

私はこのプログラムの次のブロックでこのエラーが頻繁に発生していますが、イテレータではありませんポインタこのような文字列データ型を使用すると、なぜ私は、関数strcatの引数として文字列にイテレータを渡すことができませんか()?

error: cannot convert 'std::basic_string<char>::iterator 
{aka __gnu_cxx::__normal_iterator<char*, std::basic_string<char> >}' 
to 'const char*' for argument '2' to 'char* strcat(char*, const char*)' 
strcat(temp, str1.begin()); 
         ^





      int areRotations(string str1, string str2) 
      { 
       int size1 = str1.length(); 
       int size2 = str2.length(); 
       char* temp= new char[size1+size2+1]; 
       void *ptr; 
       if (size1 != size2) 
       return 0; 


       strcat(temp, str1.begin()); 
       strcat(temp, str1.begin()); 

       /* Now check if str2 is a substring of temp */ 
       ptr = strstr(temp, str2); 


       if (ptr != NULL) 
       return 1; 
       else 
       return 0; 
      } 
+0

なぜ 'std :: string'で' strcat'を使用しますか?あるいは、なぜ、 'temp'が' std :: string'ではないのですか? –

+0

イテレータはポインタではありません。ポインタはイテレータです。 – Simple

+1

'str1.begin()'と 'C'ですか?どのくらい正確に? –

答えて

4
あなたが尋ねる

、このような文字列データ型を使用するときに必ずしもありません、

もポインタイテレータではありません。 std::stringそうポインタをインクリメントする緩衝液中で前方に移動し、保証連続バッファを有するので

std::stringためには、ポインタとすることができます。しかし、私は現存するC++標準ライブラリの実装がポインタであるかどうかわかりません。

空の文字列のためにも働くバッファへのポインタを取得する簡単な方法は、dataメンバ関数を使用することです。文字列が空でないことがわかったら、&s[0]を使用することもできます。修正不可能ゼロで終わる文字列へのポインタを取得する簡単な方法は、c_strメンバ関数を使用することです。


代わりのstrcat

std::stringであなただけ +または +=を使用することができます。

3

ポインタはイテレータです。それ以外の方法は常に真実ではありません。ここをクリックして詳細を見つけることができます: How are iterators and pointers related?

しかし、あなたはかなりのものを混ぜています... C、C++。単純にstd :: stringを使用する単純なC++ソリューションは、次のようになります。

#include <iostream> 

using namespace std; 
bool areRotations(const string& str1, const string& str2) 
{ 
    const string temp = str1 + str1; 
    return ((temp.find(str2)!=std::string::npos) && (str1.size()==str2.size())); 
} 

int main() 
{ 
    const std::string str1 = "hello"; 
    const std::string str2 = "lohel"; 
    cout << areRotations(str1,str2) << endl; 
} 
+2

元のstr1とstr2の長さが同じであるというテストがありました。それを追加したいかもしれません。 –

関連する問題