0
#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

我想用replace_original之类的api封装original(old, c style api)的api但是不知道为什么#1不能工作。

4

1 回答 1

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吗?google之后,我发现在c++14中,initializer_list的size()会变成constexpr所以我们应该可以用std::array来代替std::vector

于 2013-09-03T14:27:56.967 回答