将数组复制到向量中

Vij*_*jay 4 c++ vector stdvector

我写了一个小程序:

void showrecord()
{
     char *a[]={ "O_BILLABLE_ACCOUNT","O_CUSTOMER_TYPE_INDICATOR",
                 "O_A_PARTY_MSISDN_ID","O_A_PARTY_EQUIPMENT_NUMBER",
                 "O_A_PARTY_IMSI","O_A_PARTY_LOCATION_INFO_CELL_ID",
                 ...  
               };

     vector<std::string> fields(a,a+75);

     cout<<"done!!!"<<endl;
}

int main()
{
     showrecord();
}
Run Code Online (Sandbox Code Playgroud)

我有一些字符串文字,我希望它们被复制到一个向量中.我没有找到任何其他简单的方法:(.或者如果有任何直接的方法来初始化矢量而不使用数组,那将非常有用.这是在我在unix上运行可执行文件后转储核心.它给了我一个警告,但是:

Warning 829: "test.cpp", line 12 
# Implicit conversion of string literal to 'char *' is deprecated.
D_TYPE","O_VARCHAR_5","O_VARCHAR_6","O_VARCHAR_7","O_VARCHAR_8","O_VARCHAR_9"};
Run Code Online (Sandbox Code Playgroud)

但是相同的代码在Windows上正常运行没有任何问题.我在HPUX上使用编译器aCC.

请帮忙! 下面的编辑是转储的堆栈跟踪.

(gdb) where
#0  0x6800ad94 in strlen+0xc () from /usr/lib/libc.2
#1  0xabc0 in std::basic_string<char,std::char_traits<char>,std::allocator<char>>::basic_string<char,std::char_traits<char>,std::allocator<char>>+0x20 ()
#2  0xae9c in std<char const **,std::basic_string<char,std::char_traits<char>,std::allocator<char>> *,std::allocator<std::basic_string<char,std::char_traits<char>,std::allocator<char>>>>::uninitialized_copy+0x60 ()
#3  0x9ccc in _C_init_aux__Q2_3std6vectorXTQ2_3std12basic_stringXTcTQ2_3std11char_traitsXTc_TQ2_3std9allocatorXTc__TQ2_3std9allocatorXTQ2_3std12basic_stringXTcTQ2_3std11char_traitsXTc_TQ2_3std9allocatorXTc____XTPPCc_FPPCcT118_RW_is_not_integer+0x2d8
    ()
#4  0x9624 in showrecord () at test.cpp:13
#5  0xdbd8 in main () at test.cpp:21
Run Code Online (Sandbox Code Playgroud)

Luc*_*ton 5

为什么75?

更改

vector<std::string> fields(a,a+75);
Run Code Online (Sandbox Code Playgroud)

vector<std::string> fields(a, a + sizeof a / sizeof *a);
Run Code Online (Sandbox Code Playgroud)

没有可能为"C++ 03"初始化矢量的"更好"的方法,但对于C++ 0x,您可以访问更方便的语法,省去了C数组:

std::vector<std::string> fields {
    "O_BILLABLE_ACCOUNT",
    // ...
};
Run Code Online (Sandbox Code Playgroud)

  • @Rahul:永远不要说"从不" (3认同)
  • @Kay:我认为`&a [sizeof(a)/ sizeof(a [0])]`会产生未定义的行为,因为你取消引用指向无效对象的指针. (3认同)
  • @Luc:不,这只是C99中的一个特例.在C++中,[技术上是未定义的行为](http://stackoverflow.com/questions/3144904/). (2认同)