小编Pat*_*tes的帖子

std :: copy和std :: vector :: assign的转换警告

当一个浮点数插入a时std::vector<int>,该数字必须通过某种舍入来转换.通常这会更改数字,1.5会更改为1或2,我希望编译器至少会警告此转换.所以我-Wconversion在g ++或clang ++上使用了标志.这可以启用警告std::vector::push_back或直接分配,但不能用于std::copystd::vector::assign(iterator first, iterator end).

现在的问题是:我如何转换警告,std::copystd::vector::assign

这是我的示例程序:

#include <iostream>
#include <vector>
#include <algorithm>

using source_type = std::vector<double>;
using target_type = std::vector<int>;

int main() {
    source_type vsource;
    target_type vtarget1;
    target_type vtarget2;
    target_type vtarget3;
    target_type vtarget4;

    // Fill source with a number
    vsource.push_back(1.5);

    // This will give a compiler warning as expected
    vtarget1.push_back(vsource.at(0));

    // This does not give a warning, why not?
    vtarget2.assign(vsource.begin(), vsource.end());

    // Also this …
Run Code Online (Sandbox Code Playgroud)

c++

12
推荐指数
1
解决办法
290
查看次数

标签 统计

c++ ×1