在不同的数据类型上使用std::transform

Using std::transform on different data types

本文关键字:std transform 数据类型      更新时间:2023-10-16

我有一个名为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());