在不同的数据类型上使用std::transform
Using std::transform on different data types
我有一个名为atom的自定义数据类型。我想使用std::transform来填充一个双精度向量,其中原子成员"number"是双精度。我得到错误"std::vector::iterator '没有名为' vec2 '的成员",其中vec2是我的双精度向量。为什么会这样?是否有可能在转换中使用两种不同的数据类型?
atom.h
#ifndef _atom_
#define _atom_
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
class atom{
public:
bool operator==(const atom rhs);
double number;
string name;
};
#endif
atom.cpp
#include "atom.h"
atom::atom(){}
atom::~atom(){}
bool atom::operator==(const atom rhs){
return this->name==rhs.name;
}
transformation.h
#ifndef _transformation_
#define _transformation_
#include "atom.h"
#include <vector>
#include <algorithm>
using namespace std;
struct transformation{
double operator() (atom a) const{
return a.number;
}
};
#endif
main.cpp
int main(){
vector<atom> vec;
atom hydro;
atom oxy;
atom carb;
carb.name = "carbon";
carb.number = 6;
hydro.name="hydrogen";
hydro.number=1;
oxy.name="oxygen";
oxy.number=8;
vec.push_back(hydro); //here i push atoms into my atom vector
vec.push_back(oxy);
vec.push_back(hydro);
vec.push_back(oxy);
vec.push_back(oxy);
vec.push_back(carb);
vector<double> vec2;
transform(vec.begin(), vec.end(). vec2.begin(), transformation());
}
打印错误:您有一个.
而不是,
:
transform(vec.begin(), vec.end(). vec2.begin(), transformation());
^
vec.end()
是一个迭代器,vec.end().vec2
试图访问该迭代器的成员vec2
。
接下来,您需要确保vec2
足够大,可以容纳转换后的元素。您可以实例化它,使它从一开始就具有正确的大小:
vector<double> vec2(vec.size());
您的代码无效。除了语句
中的一个错别字transform(vec.begin(), vec.end(). vec2.begin(), transformation());
中使用句号而不是逗号的语句有错误。Vector vec2不包含元素。因此,您不能在此语句中这样使用它。
定义向量为
vector<double> vec2( vec.size() );
transform(vec.begin(), vec.end(), vec2.begin(), transformation());
或者使用以下方法
#include <iterator>
//...
vector<double> vec2;
vec2.reserve( vec.size() );
transform(vec.begin(), vec.end(), std::back_inserter( vec2 ), transformation());
相关文章:
- 使用std::transform将一个范围的元素添加到另一个范围中
- 使用 std::transform 将向量向量 (a) 添加到另一个向量向量 (b)
- std::transform 将一个结构数组复制到另一个结构数组
- 如何正确使用 std::transform 和 std::mem_fn?
- 如何在 std::transform 中使用 std::p ow 作为一元函数?
- 将 std::transform 与 std::back_inserter 一起使用是否有效?
- 使用 std::transform 最终向量保持为空
- C++ 通过 std::transform 的 vector 索引获取向量
- 使用 std::transform 在 2d C 阵列上转换为 1d C 数组
- std::transform 可以替换为 std::累积吗?
- 使用 std ::transform 构造 std::vector.返回未命名结果的可能性?
- std::transform C++ 上的致命错误
- std::transform 操作到 --end() 和奇怪的输出
- 在 lambda(parameter) 中为 std::transform with std::sregex_token
- 如何使用 std::transform with container without push_back.
- std::transform with std::reference_wrapper
- std::transform 或 std::generate 在没有 ExecutionPolicy 的情况下是否可以并
- std::transform的最后一个参数
- 在 std::for_each 和 std::transform 中正确使用函子
- 使用 std::transform() 添加四个向量 c++