我有一个名为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());
}
答案 0 :(得分:6)
错字:你有一个.
而不是,
:
transform(vec.begin(), vec.end(). vec2.begin(), transformation());
^
vec.end()
是一个迭代器,vec.end().vec2
尝试访问该迭代器的成员vec2
。
接下来,您需要确保vec2
足够大以获取转换后的元素。您可以实例化它,使其从一开始就具有正确的大小:
vector<double> vec2(vec.size());
答案 1 :(得分:0)
您的代码无效。除了陈述中的拼写错误
transform(vec.begin(), vec.end(). vec2.begin(), transformation());
你使用句号而不是逗号语句有一个错误。矢量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());