美文网首页
c++字符串比较

c++字符串比较

作者: loinliao | 来源:发表于2019-08-24 14:22 被阅读0次

这样一段代码:


#include <cstdio>
#include <vector>
#include <iostream>
#include <map>
#include <set>
#include <string>
#include <queue>
#include <stack>
#include <cmath>
#include <ctime>
using namespace std;


// len = 100
string s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
string t = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";


bool comp1() {
    for (int i=0;i<s.size();i++) {
        if (s[i] != t[i]) return false;
    }
    return true;
}

bool comp2() {
    return s == t;
}

int main() {
    int maxn = 10000000; // 1百万
    
    clock_t t1 = clock();
    for(int i=0;i<maxn;i++) {
        comp1();
    }
    cout << (clock() - t1) * 1.0 / CLOCKS_PER_SEC << "s" << endl;

    t1 = clock();
    for(int i=0;i<maxn;i++) {
        comp2();
    }
    cout << (clock() - t1) * 1.0 / CLOCKS_PER_SEC << "s" << endl;
}

1、两个长度为100的相等的字符串比较1百万次,两种比较方式会相差多少呢?

14.4658s
0.280318s
差距达100倍。。。

2、两个长度为100的最后一个字符不相等的字符串比较1百万次,两种比较方式会相差多少呢?

14.5281s
0.297259s

3、两个长度为100的第一个字符不相等的字符串比较1百万次,两种比较方式会相差多少呢?

0.16233s
0.263476s

显然应该使用==运算符,实现参考:https://stackoverflow.com/questions/4145840/the-way-to-compare-string-in-an-efficient-way-in-c

相关文章

  • Swift--原生字符串

    字符 创建字符串 字符串的拼接 字符串插入、删除和替换 字符串比较 字符 在Java、C、C++和Objectiv...

  • c++字符串比较

    这样一段代码: 1、两个长度为100的相等的字符串比较1百万次,两种比较方式会相差多少呢? 2、两个长度为100的...

  • HJ14 字符串排序

     重载less比较符号。  c++的字符串可以直接比较。可以直接调用,最终结果就是按照升序排列。

  • Android:Java语言字符串比较“==”形式和“equal

    一、熟悉C++的人对于两个字符串比较的代码一定很了解,可以用==直接比较字符串,例如(string1==strin...

  • C++ std::string 在一个字符串前插入一个字符串几种

    1、直接使用字符串相加 2、使用insert函数 比较:通过Quick C++ Benchmarks 可得到结果

  • C_C++ 字符串数字的转换

    C++ 字符串流 stringstream C++ stream library 中的 stringstream ...

  • C++<第十九篇>:字符串

    C++ 中的字符串有两种形式:(1)C风格的字符串 (2)C++引入的 string 类型的字符串。 (1)C风格...

  • 字符串

    字符串的实现(C++实现) 实现字符串的构造及其常用的接口函数,深入掌握理解字符串的实现 C++ / STL 中s...

  • C++字符串处理小结

    C++中的字符串类型 常用的C++的字符串类型主要是std::string。它是模板std::basic_stri...

  • c++传递字符串给c#使用问题

    C++里,字符串要占用内存的。C++创建字符串,并传给C#,就会造成内存泄露(因为C#不知道C++如何创建,也就不...

网友评论

      本文标题:c++字符串比较

      本文链接:https://www.haomeiwen.com/subject/xifqectx.html