【问题标题】:why I can use the string function length() when the <string> isn't included in C++? [duplicate]当 <string> 不包含在 C++ 中时,为什么我可以使用字符串函数 length()? [复制]
【发布时间】:2016-07-25 14:39:35
【问题描述】:

代码如下,字符串库已注释,但程序运行良好

#include<iostream>
//#include<string>   // the string library has been commented 
using namespace std;

int main(){
    int n;
    cin>>n;
    for(int i=0; i<n; i++){
        string str;
        int num = 0;
        cin>>str;
        int len = str.length();    //the function length is used here!
        for (int j =0; j< len; j++){
           if (str[j] >='0' && str[j] <='9')
               num ++;
        } 
    cout<<num<<endl;
    }
    return 0;
}

【问题讨论】:

  • 不包括库你怎么能使用string
  • This shows that it doesn't work。如果你想使用std::string,那么#include就可以了。如果你的编译器碰巧在编译器的#includes集合中的某个地方包含了在您的代码中使用。

标签: c++ string


【解决方案1】:

因为内部iostream 包含string

包含是传递性的,一些依赖可能依赖于编译器,而其他依赖在所有平台上都是相同的(一个这样的例子是,包括map 将使pair 可用,因为它直接依赖于它) .

stringiostream 之间的依赖关系没有在任何地方定义,因此虽然它可能适用于某些编译器,但您不应该依赖它。

【讨论】:

  • Visual C++ 是一种可能被许多甚至大多数程序员使用的著名编译器。代码将拒绝使用任何版本的 Visual C++ 编译,包括最新版本。
猜你喜欢
  • 1970-01-01
  • 2023-01-23
  • 1970-01-01
  • 2012-02-04
  • 2016-02-13
  • 1970-01-01
  • 1970-01-01
  • 2016-12-30
  • 2017-11-06
相关资源
最近更新 更多