用随机元素填充向量

时间:2020-01-08 19:19:46

标签: c++ random lambda stl

为什么我的lambda不将元素放入向量中?

textView.leftDrawable(R.drawable.my_icon, colorRes = R.color.white)

fun TextView.leftDrawable(@DrawableRes id: Int = 0, @DimenRes sizeRes: Int = 0, @ColorInt color: Int = 0, @ColorRes colorRes: Int = 0) {
    val drawable = drawable(id)
    if (sizeRes != 0) {
        val size = resources.getDimensionPixelSize(sizeRes)
        drawable?.setBounds(0, 0, size, size)
    }
    if (color != 0) {
        drawable?.setColorFilter(color, PorterDuff.Mode.SRC_ATOP)
    } else if (colorRes != 0) {
        val colorInt = ContextCompat.getColor(context, colorRes)
        drawable?.setColorFilter(colorInt, PorterDuff.Mode.SRC_ATOP)
    }
    this.setCompoundDrawables(drawable, null, null, null)
}

2 个答案:

答案 0 :(得分:4)

使用reserve时,向量中的元素数量不会增加。这意味着begin(vec)end(vec)之间的差为0(或向量的大小在开始时为零)。有两种可能性:

vec.resize(N);
std::generate(vec.begin(), vec.end(), [](){return distribution(gen);});
// or
vec.reserve(N); // Not necessary but sensible.
std::generate_n(std::back_inserter(vec), N, [](){return distribution(gen);});

答案 1 :(得分:1)

Doc.Curr. -4,248,057.00 -25,998,733.00 25,998,733.00 -192,534.00 -118,509.00 192,534.00 保留空间,这意味着增加容量,而不增加大小。使用std::vector::reserve来更改矢量的大小。

相关问题