gpt4 book ai didi

c++ - 结构上的 std::replace_if

转载 作者:搜寻专家 更新时间:2023-10-31 01:12:31 28 4
gpt4 key购买 nike

我想做的就是在满足条件的情况下替换结构 vector 上的一个结构字段。所以这是我的代码:

struct DataST{
int S_num,Charge,Duplicate_Nu;
float PEP;
string PEPTIDE;
vector<MZIntensityPair> pairs;
bool GetByT(const DataST& r,int T)
{
switch (T)
{
case 1:
return (S_num == r.S_num);
case 2:
return (Charge == r.Charge);
case 3:
return !(PEPTIDE.compare(r.PEPTIDE));
case 4:
return (Duplicate_Nu == r.Duplicate_Nu);
case 5:
return ((S_num == r.S_num)&&(Charge == r.Charge));
default:
return false;
}
}
};
int main()
{
.
.
vector<DataST> spectrums;
.
.
DataST tempDT_dup;
tempDT_dup.PEPTIDE="Test";
replace_if(spectrums.begin(), spectrums.end(), boost::bind(&DataST::GetByT, _1,tempDT_dup,3),11);
.
.
}

所以在这个考试中,如果该项目的 PEPTIDE 字段等于“测试”,我想将所有光谱项目的 Duplicate_Nu 更改为 11,但是当我想使用函数 GetByT 而不是操作“=”时,我在下面遇到错误

/usr/include/c++/4.6/bits/stl_algo.h:4985:4: error: no match for ‘operator=’ in ‘_first._gnu_cxx::__normal_iterator<_Iterator, _Container>::operator* with _Iterator = DataST*, _Container = std::vector, __gnu_cxx::__normal_iterator<_Iterator, _Container>::reference = DataST& = __new_value’ /usr/include/c++/4.6/bits/stl_algo.h:4985:4: note: candidate is: hello_pwiz/hello_pwiz.cpp:14:8: note: DataST& DataST::operator=(const DataST&) hello_pwiz/hello_pwiz.cpp:14:8: note: no known conversion for argument 1 from ‘int DataST::* const’ to ‘const DataST&’

最佳答案

目前的问题是您正试图通过复制来传递不可复制的对象。这是因为您作为参数提供给 boost::bind() 的任何内容都将被复制。

boost::bind(&DataST::GetByT, _1,tempDT_dup,3),
/|\
|
This means pass by copy. --------

如果您不想通过复制传递,您必须做的是通过指针传递(复制指针不会造成任何伤害)。或者,您可以使用 boost::ref通过引用传递,例如:

boost::bind(&DataST::GetByT, _1,boost::ref(tempDT_dup),3),

另一个问题是您将11 指定为std::replace_if() 的最后一个参数。 .它是一个元素应该被替换的值(如果 predicate 返回 true)。它应该与存储在数组中的对象具有相同的类型(或可转换为)。但是您不能将 11(它是一个普通的有符号整数,又名 int)转换为 DataST 类型的对象。你需要这样的东西:

vector<DataST> spectrums;
DataST tempDT_dup;
DataST replacee; // What you want to replace with...
replace_if(spectrums.begin(), spectrums.end(),
bind(&DataST::GetByT, _1, boost::ref(tempDT_dup), 3),
replacee);

关于c++ - 结构上的 std::replace_if,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13647312/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com