简体   繁体   English

如何在vector c ++中将double转换为int?

[英]How do I convert a double to int in vector c++?

I know the cast from the first array. 我知道第一个阵列的演员。

std::vector<int> v_int;
std::vector<float> v_float(v_int.begin(), v_int.end());

but how do I convert second array? 但是如何转换第二个数组呢?

vector<int> aCol(4);
vector<vector<int>> a(2, aCol);
vector<vector<double>> b(a.begin(), a.end());// ???

What should I do in this case? 在这种情况下我该怎么办?

For the compiler vector<int> and vector<double> are completely unrelated types, not implicitly convertible one to another. 对于编译器, vector<int>vector<double>是完全不相关的类型,不能隐式地转换为另一个。 What you can do is something like: 你能做的是:

for(auto&& elem: a)
    b.push_back(std::vector<double>(elem.begin(), elem.end()));
vector<vector<double>> b;
b.reserve(a.size());
for (const auto& elem : a) {
  b.emplace_back(elem.begin(), elem.end());
}

The reason your vector-of-vectors construction is not compiling is because 你的矢量矢量构造没有编译的原因是因为

vector<vector<double>> b(a.begin(), a.end())

is range constructing b with iterators whose element type is vector<int> . 是使用迭代器构造b范围,其元素类型为vector<int> This will attempt to construct b 's internal std::vector<double> s with std::vector<int> s, which is no surprise that it shouldn't compile. 这将尝试用std::vector<int>构造b的内部std::vector<double> ,这不应该是它不应该编译。

Comparing this to your first example, 将此与您的第一个示例进行比较,

std::vector<float> v_float(v_int.begin(), v_int.end());

is range constructing v_float from iterators whose element type is int . 是从元素类型为int迭代器构造v_float范围。 This works because a conversion from an int to a float is allowed, but not from std::vector<int> to std::vector<double> (or std::vector<float> ). 这是有效的,因为允许从int转换为float,但不允许从std::vector<int>std::vector<double> (或std::vector<float> )。

You may want to instead look at looping through each element of a and pushing back a vector constructed from a 's begin() and end() 您可能希望改为查看循环遍历a每个元素并推回从abegin()end()构造的向量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM