What is a good clean way to convert a std::vector<int> intVec
to std::vector<double> doubleVec
. Or, more generally, to convert two vectors of convertible types?
将std转换成std::vector
2 个解决方案
#1
117
Use std::vector
's range constructor:
构造函数使用std::向量的范围:
std::vector<int> intVec;
std::vector<double> doubleVec(intVec.begin(), intVec.end());
#2
3
Any problem? I can run on my PC. My IDE is Code::blocks.
任何问题吗?我可以在电脑上运行。我的IDE是代码:块。
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
int main()
{
vector<int> v_int;
for (int i=0; i<10; ++i) {
v_int.push_back(i);
}
vector<double> v_float(v_int.begin(), v_int.end());
copy (v_float.begin(), v_float.end(), ostream_iterator<double>(cout, " "));
cout << endl;
return 0;
}
#1
117
Use std::vector
's range constructor:
构造函数使用std::向量的范围:
std::vector<int> intVec;
std::vector<double> doubleVec(intVec.begin(), intVec.end());
#2
3
Any problem? I can run on my PC. My IDE is Code::blocks.
任何问题吗?我可以在电脑上运行。我的IDE是代码:块。
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
int main()
{
vector<int> v_int;
for (int i=0; i<10; ++i) {
v_int.push_back(i);
}
vector<double> v_float(v_int.begin(), v_int.end());
copy (v_float.begin(), v_float.end(), ostream_iterator<double>(cout, " "));
cout << endl;
return 0;
}