c++ - 将 vector<int> 分配给 vector<double> 安全吗?

标签 c++ casting vector

<分区>

要为某个计算初始化变量,我必须从整数数组中为它们赋值。 所以我这样做:

vector<double> vd;
int ai[N]; // Filled somewhere else

vd.assign(ai, ai+N);

这适用于 gcc 4.6.1 Linux。但它总是正确的吗?或者我应该回到常青树:

vd.resize(N);
for(int i=0; i < N; ++i) vd[i] = (double)ai[i];

感谢您的澄清!

最佳答案

将进行隐式转换,因此是安全的。为什么不在构造过程中初始化 vector :

std::vector<double> vd(ai, ai + N);

关于c++ - 将 vector<int> 分配给 vector<double> 安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7901256/

相关文章:

c++ - 为什么 & 对字符串的行为不同?

c++ - Makefile 找不到包含路径

c++ - 将 dynamic_cast 与引用和指针一起使用时的行为差异

java - ClassCastException : java. lang.String 无法转换为 Ljava.lang.String

java - 我在 Asteroids 游戏中使用 Vector2d 类是否多余?

r - 将向量列表组合到 data.frame 中,并带有列表编号

c++ - 使用 C 或 C++ 时如何防止整数溢出?

c++ - 保留没有文件支持的共享内存 (Linux/Windows) (boost::interprocess)

java - 为什么 '(int)(char)(byte)-2' 在 Java 中产生 65534?

c++ - 使用 getline 读取文件时将值迭代到 vector 中