0

我有一个向量的向量。如果它小于特定值或大于另一个值,我想读取它的第一个组件并将其从向量中删除。我怎样才能做到这一点?我的代码是:

int d = sum_et.size();                
vector <float>sum_et                                    
vector <float>sum_ieta_iphi;
vector <vector<float> >v;
sum_et.push_back(energySum);
sum_ieta_iphi[0]=energySum;
sum_ieta_iphi[1]=ieta;
sum_ieta_iphi[2]=iphi;
v.push_back(sum_ieta_iphi);
float max,min;
max=sum_et[(int)(19/20*d)];
min=sum_et[(int)(d/20)];


for (int i=0;i<v.size();i++){
/* line 312 */  if (v[i[0][0][0]]<min || v[i[0][0][0]]>max){
/* line 313 */      v.erase(v[i]);
  }
}

我收到这些错误:

Analysis.cc:312:16: error: invalid types 'int[int]' for array subscript   
Analysis.cc:312:37: error: invalid types 'int[int]' for array subscript
Analysis.cc:313:14: error: no matching function for call to 'std::vector<std::vector<float> >::erase(std::vector<float>&)'
4

3 回答 3

2

问题是您正在索引i不是向量的东西(整数变量)。


还有更好的方法可以做到这一点。请记住,C++ 在标准库中有许多不错的算法,例如std::copy_if,如果谓词为真,则从一个集合复制到另一个集合。

这可用于将向量复制到自身上:

std::copy_if(std::begin(v), std::end(v), std::begin(v),
             [v, min, max](const vector<float>& value)
             { return v[value[0]] >= min && v[value[0]] <= max; });
于 2013-07-09T10:32:24.887 回答
0

你在这里做了一些奇怪的事情:

v[i[0][0][0]]

特别i是一个 plain int,它给出了第 312 行“数组子脚本的无效类型”的错误。

除此之外,我认为你还有很多[0]事情可以正常工作。

于 2013-07-09T10:28:29.493 回答
0

您的代码中有两个问题:i是整数,所以i[0][0][0]是废话。另外,该函数erase需要向量上的迭代器,而不是值。(参考参考

如果我没记错的话,你想检查每个子向量的第一个元素,如果它符合条件,删除子向量。

正如 alexisdm 在评论中指出的那样,我建议的 for 循环首先错过了元素。它应该是 :

// We get an iterator on the first vector
vector<vector<float> >::iterator it = v.begin();
while(it != v.end())
{
    // We check the first element of the subvector pointed by the iterator
    if ( (*it).at(0) < min || (*it).at(0) > max)
    {
        // We erase the subvector of v and erase returns
        // an iterator to the next element
        it = v.erase(it);
    }
    else
    {
        // We go to next element
        it++;
    }
}

第一个不工作的循环是:

// We get an iterator on the first vector
for(vector<vector<float> >::iterator it = v.begin(); it != v.end(); ++it)
{
    // We check the first element of the subvector pointed by the iterator
    if ( (*it).at(0) < min || (*it).at(0) > max)
    {
        // We erase the subvector of v
        it = v.erase(it);
    }
}
于 2013-07-09T10:36:55.033 回答