将数组复制到向量中
copying an array into a vector
我写了一个小程序:
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"));
}
相关文章:
- 将指向给定子类的指针从一个向量复制到另一个向量
- 将字符向量复制到另一个向量
- 将shared_ptr的向量复制到抽象基的派生类
- 将一种数据类型的向量复制到同一数据类型的结构向量中的有效方法是什么
- 自定义类对象的C++向量 - 复制构造函数已删除 - std::ifstream
- 如何在C++中将一个对象从一个向量复制到另一个向量?
- 将特征向量复制到 C 数组
- 将std ::向量复制到CV :: Mat_的行操作相同
- 将向量复制到 std::string
- 如何以相反的顺序将整个向量复制到队列中
- 按索引将类类型元素从一个向量复制到另一个 c++
- 使用迭代器将向量复制到数组中
- 为什么是非法的:将指针向量复制到指向常量的指针向量中
- 将元素从一个向量复制到另一个向量的最有效方法,给定一个不被复制的索引列表
- C++-将数据从浮点向量复制到uint8向量
- 将字符串从向量复制到字符串
- 我可以使用STD ::复制将数据的位模式从整数向量复制到一系列未签名的字符
- 将指针从一个向量复制到另一个向量;地址指出了变化
- 如何将内容从一个字符串向量复制到另一个字符串向量
- 以相反的顺序将一个向量复制到另一个向量