【问题标题】:Copy index of vector Elements with condition有条件的向量元素的复制索引
【发布时间】:2017-06-21 10:12:12
【问题描述】:

我想保存我的布尔向量的索引,其中向量元素为假。

我有以下代码:

vector<bool> incumbent_solution; // (0,0,0,1,1,0,0)...
vector<int> I_minus_S(incumbent_solution.size());

auto it = copy_if(incumbent_solution.begin(), incumbent_solution.end(),
        I_minus_S.begin(), [&incumbent_solution](auto i) {if (incumbent_solution[i] == 0] return i; });
I_minus_S.erase(it, I_minus_S.end());

但它只在我的 Vector 中存储 True 而不是索引。 我的 lambda 做错了什么?

【问题讨论】:

    标签: vector c++14 remove-if


    【解决方案1】:

    std::copy_if 的工作方式与您的预期不同,它将实际元素传递给谓词,如果谓词返回 true,则将其复制到第二个容器中。

    如果您需要索引,请使用简单的for 循环:

    std::vector<bool> incumbent_solution { 0, 0, 0, 1, 1, 0, 0, 1, 1 };
    std::vector<int> I_minus_S(incumbent_solution.size());
    
    std::size_t last = 0;
    
    for(std::size_t index = 0; index < incumbent_solution.size(); ++index) {
        if(incumbent_solution[index] == false)
            I_minus_S[last++] = index;
    }
    
    I_minus_S.erase(I_minus_S.begin() + last, I_minus_S.end());
    

    【讨论】:

      【解决方案2】:
      std::vector< bool >  vb = { 0,0,0,1,1,0,0 };
      std::vector< int >   vi;
      
      unsigned counter = 0;
      for( bool b : vb ){
          if( !b ){
              vi.push_back( counter );
          }
          ++counter;
      }
      
      for( int& i : vi ){
          std::cout << i << '\n';
      }  
      

      std::copy_if 接受应返回 truefalse 的 UnaryFunction。最好使用简单的for


      如果你要求使用algorithm库,可以使用transform

      std::vector< bool >  vb = { 0,0,0,1,1,0,0 };
      std::vector< int >   vi;
      
      int counter = -1;
      
      std::transform( vb.begin(), vb.end(), std::back_inserter( vi ),
                      [&](const bool b ){
                          counter++;
                          if( !b ) return counter;
                      }
                     );  
      

      但问题在于,对于true,条件将0 返回到vi 的索引。虽然您可以使用-1,然后在vi 中删除它们

                      [&](const bool b ){
                          counter++;
                          if( !b ) return counter;
                          else     return -1;
                      }
      

      但还是一个简单的for 是一个更好的解决方案。

      【讨论】:

        猜你喜欢
        • 2017-12-08
        • 2018-08-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-15
        • 1970-01-01
        • 2017-05-25
        • 1970-01-01
        相关资源
        最近更新 更多