C++ vector of char array

后端 未结 7 896
梦谈多话
梦谈多话 2020-12-09 16:06

I am trying to write a program that has a vector of char arrays and am have some problems.

char test [] = { \'a\', \'b\', \'c\', \'d\', \'e\' };

vector

        
7条回答
  •  -上瘾入骨i
    2020-12-09 16:47

    FFWD to 2019. Although this code worketh in 2011 too.

    // g++ prog.cc -Wall -std=c++11
    #include 
    #include 
    
     using namespace std;
    
     template
        inline 
          constexpr /* compile time */
          array string_literal_to_array ( char const (&charrar)[N] )
     {
        return std::to_array( charrar) ;
     }
    
     template
        inline 
          /* run time */
          vector string_literal_to_vector ( char const (&charrar)[N] )
     {
        return { charrar, charrar + N };
     }
    
    
    int main()
    {
       constexpr auto arr = string_literal_to_array("Compile Time");
       auto cv = string_literal_to_vector ("Run Time") ;
       return 42;
    }
    

    Advice: try optimizing the use of std::string. For char buffering std::array is the fastest, std::vector is faster.

    https://wandbox.org/permlink/wcasstoY56MWbHqd

提交回复
热议问题