如何在一个表达式(便携式)中将char []转换为向量

问题描述:

我正在编写一个C到C++分析器,我需要一种方法将字符串文字转换为单个表达式中的向量。如何在一个表达式(便携式)中将char []转换为向量<char>

我能够这样做,但我使用的是GCC扩展:

GCC's Statements and Declarations in Expressions

#include <vector> 
#include <iostream> 

using namespace std; 

int main() 
{ 
    cout << vector<int>({1, 2, 3, 4, 5})[0] << endl; 

    cout << vector<char>({'H', 'e', 'l', 'l', 'o', '\0'})[0] << endl; 

    cout << ({string temp("Hello"); vector<char>(temp.begin(), temp.end());})[0] << endl;  
} 

有没有办法这样做,而无需使用GCC的扩展?

+0

一个辅助函数吧? 'vector to_vector(string);' –

+0

是的,当然...请添加一个答案,我会投它。 –

事实证明,我所要做的就是使用一个辅助函数:

template <typename T, size_t S> 
    inline vector<T> to_vector(T const (& o)[S]) 
    { 
     return vector<T>(o, o + S); 
    } 

int main() 
{ 
    cout << to_vector({1, 2, 3, 4, 5})[4] << endl; 

    cout << to_vector({'H', 'e', 'l', 'l', 'o', '\0'})[4] << endl; 

    cout << to_vector("Hello")[4] << endl;  
}