2017-06-14 65 views
2

在C,我们能够做到这一点的指针:转移在C++字符串

char *str; 
scanf("%s", str); // lets say that we enter "Hello" 
str = str + 2; 
printf("%s", str); // and the answer would be "llo" 

有没有这样的事情在C++处理字符串数据类型在O(1)的时间?

编辑:这是给我这个错误 - >

error: invalid operands to binary expression ('string' (aka 'basic_string<char, 
    char_traits<char>, allocator<char> >') and 'int') 
str = str + 1; 

EDIT2:我跑这个代码,并得到了上面的错误 - >

string str = "Hello"; 
str = str + 1; 
cout << str << endl; 
+3

相同的代码会在C++中也有未定义的行为。 –

+0

@GAURANGVYAS是的,我一上传问题就意识到了。我想用字符串数据类型来做到这一点。 –

+0

@NeilButterworth不,字符串数据类型。对不起,我编辑了这个问题。 –

回答

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

int main() { 
    string s = "foobar"; 
    cout << &s[s.size() - 2] << endl; 
    cout << &s[3] << endl; 

} 
+1

人们还可以提到'at(...)'功能,它确保给定的索引位置是一个有效的位置,即使这没有明确要求。 – NOhs

+0

谢谢你,很多人都低估了这个问题。也许是因为我没有正确解释这个问题。我认为这个问题在我第一次编辑后很清楚,但至少我得到了答案。 –

+0

@MrZ你能解释更多吗?谢谢。 –