初始化程序列表与向量 [英] Initializer list vs. vector

查看:86
本文介绍了初始化程序列表与向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++ 11中,可以使用初始化程序列表来初始化函数中的参数。目的是什么? const向量不能做到相同吗?以下两个程序有什么区别?

In C++11, one can use initializer lists to initialize parameters in functions. What is the purpose of it? Can't the same be done with const vectors? What is the difference of the two programs below?

使用初始化列表:

#include <iostream>

using namespace std;

int sumL(initializer_list<int> l){
    int sum = 0;
    for (const auto i: l){
        sum += i;
    }
    return sum;
}

int main(){

    cout << sumL({1, 2, 3}) << "\n";

    return 0;
}

使用const向量:

#include <iostream>
#include <vector>

using namespace std;

int sumV(const vector<int> l){
    int sum = 0;
    for (const auto i: l){
        sum += i;
    }
    return sum;
}

int main(){

    cout << sumV({1, 2, 3}) << "\n";
    return 0;
}


推荐答案

<$的常用用法c $ c> std :: initializer_list 作为容器(和类似)类的构造函数的参数,可以方便地从几个相同类型的对象初始化这些容器。
当然,您可以使用 std :: initializer_list 否则使用相同的 {} 语法。

The common use of std::initializer_list is as argument to constructors of container (and similar) classes, allowing convenient initialisation of those containers from a few objects of the same type. Of course, you can use std::initializer_list otherwise and then use the same {} syntax.

由于 std :: initializer_list 具有固定大小,因此不需要动态分配,因此可以有效实施。另一方面, std :: vector 需要动态内存分配。即使在您的简单示例中,编译器也不太可能优化此开销(避免中介 std :: vector 及其动态内存分配)。除此之外,程序的结果没有区别(尽管您应该使用 const std :: vector< int>& 参数来避免复制及其内容)。关联的动态内存分配)。

Since a std::initializer_list has a fixed size, it doesn't require dynamic allocation and hence can be efficiently implemented. A std::vector, on the other hand, requires dynamic memory allocation. Even in your simple example it is unlikely that the compiler will optimize this overhead away (avoid the intermediary std::vector and its dynamic memory allocation). Other than that, there is no difference in the outcome of your programs (though you should take a const std::vector<int>& argument to avoid a copy and its associated dynamic memory allocation).

这篇关于初始化程序列表与向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆