将数组复制到向量中

copying an array into a vector

本文关键字:向量 复制 数组      更新时间:2023-10-16

我写了一个小程序:

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();
}

我有一个字符串文字数组,我想把它们复制到一个向量中。我没有找到其他简单的方法:(。或者,如果有任何直接的方法可以在不使用数组的情况下初始化向量,那将非常有帮助。这是在我在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"};

但同样的代码在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

为什么是75?

更改

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

vector<std::string> fields(a, a + sizeof a / sizeof *a);

对于C++03,没有可以说是"更好"的方法来初始化向量,但对于C++0x,您可以使用更方便的语法,省去C数组:

std::vector<std::string> fields {
    "O_BILLABLE_ACCOUNT",
    // ...
};

尝试const char* a[]而不是char* a[]。字符串文字的类型是const char*,而不是char*,因此会收到警告。

这里有一个可能的解决方案,IMO更通用一点-使用可重复使用的函数,可以处理任何大小的字符串数组:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
template <typename Array, std::size_t Size>
std::vector<std::string> make_vector(Array (&ar)[Size])
{
    std::vector<std::string> v(ar, ar + Size);
    return v;
}
int main()
{
     char const* a[] = { "Aa","Bb", "Cc","Dd", "Ee","Ff" };
     // copy C-array to vector
     std::vector<std::string> fields = make_vector(a);
     // test
     std::copy(fields.begin(), fields.end(),
               std::ostream_iterator<std::string>(std::cout, "n"));
}