为什么一般用vector<string> 而非 vector<char*>

    xiaoxiao2021-03-25  48

    为什么一般用vector<string> 而非 vector<char*>?

     

    A char* is a pointer, which may or may not point to valid string data.

    A std::string is a string class, encapsulating all the required data that makes up a string, along with allocation and deallocation functionality.

    If you store std::string's in a vector, or anywhere else, then everything will just work.

    If you store char pointers, you have to do all the hard work of allocating and freeing memory, and ensuring the pointers only ever point to meaningful string data, and determine the length of the strings and so on.

    And since char*'s are expected by a lot of C API's as well as part of the C++ standard library, the string class has the c_str() function which returns a char*.

     

    char*是一个指针,指向的地址有可能并不是合法的字符串数据

    string是一个封装好的类,里面不只包含数据,还集成了空间分配和释放的功能

    如果vector中存的是char*,空间分配和释放等复杂操作需要自己手动实现,同时还要保证指针指向有意义的字符串数据,另外还得自己统计字符串的长度

     

     

    http://stackoverflow.com/questions/550035/vectorstring-or-vectorchar

     

    转载请注明原文地址: https://ju.6miu.com/read-36644.html

    最新回复(0)