#include <initializer_list>
#include <iostream>
#include <vector>
//this api is anti intuition
void original(int const **data)
{
for(size_t i = 0; i != 3; ++i){
int const *ptr = *data;
//std::cout<<*ptr++<<", "<<*ptr<<std::endl; //this line may cause undefined behavior
std::cout<<ptr[0]<<", "<<ptr[1]<<std::endl;
++data;
}
}
//my eyes prefer this api than original like api
void replace_original(std::initializer_list<std::initializer_list<int>> list)
{
std::vector<int const*> results(list.size());
for(auto data : list){
results.push_back(std::begin(data)); //#1
}
original(&results[0]);
}
int main()
{
int first[] = {0, 1};
int second[] = {2, 3};
int third[] = {4, 5};
int const *array[] = {first, second, third};
original(array);
replace_original({ {0, 1}, {2, 3}, {4, 5} });
return 0;
}
结果
0, 1
2, 3
4, 5
预期结果
0, 1
2, 3
4, 5
0, 1
2, 3
4, 5
我想用api替换原始(旧的,c风格的api)的api,如replace_original 但无法弄清楚为什么#1无法正常工作。
答案 0 :(得分:0)
啊,愚蠢的错误,我应该把循环改为
size_t const size = list.size();
std::vector<int const*> results(size);
for(size_t i = 0; i != size; ++i){
results[i] = std::begin( *(std::begin(list) + i) );
}
你有更好的解决方案来封装这种api吗? 谷歌之后,我发现在c ++ 14中,initializer_list的size()会 成为constexpr所以我们应该能够使用std :: array来替换std :: vector