How do I set parameter default values that rely on other parameters?

只愿长相守 提交于 2019-12-01 02:11:58

If you truly want a function with a size parameter, and want the size to default to the vector size (instead of just getting it as a local variable), then you could solve this with two functions. One taking just the vector, and one taking the vector and the size (without default). Then the one-argument function can just call the second.

So

void function(const std::vector<int>& vec, const size_t size)
{
   ...
}

void function(const std::vector<int>& vec)
{
   function(vec, vec.size());
}

Why do you need second parameter if it based on the first?

    void function(std::vector<int> vec ){
        size_t size = vec.size();
        //code..
        return;
    }

Isn't it easier?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!