简体   繁体   中英

Replace negative values of std::vector using signbit in C++

I am trying to replace negative values of a std::vector with another known value using signbit, but it wont work. The failing command is:

replace_if(myvector.begin(), myvector.end(), signbit, 999);

The error I get is:

error: no matching function for call to ‘replace_if(std::vector<int>::iterator, std::vector<int>::iterator, <unresolved overloaded function type>, int)’

The std::vector is of type int, and from the error output I understand that it didn't find the function? I included "math.h" though.. Maybe signbit does not work with integers?

If this wont work, can you propose an alternative in one line?

Edit: Because the code is big I made an example which produces the same error.

// replace_if example
#include <iostream>     // std::cout
#include <algorithm>    // std::replace_if
#include <vector>       // std::vector
#include <cmath>       //  std::signbit

int main () {
  std::vector<int> myvector;

  // set some values:
  for (int i=-10; i<10; i++) myvector.push_back(i);              

  std::replace_if (myvector.begin(), myvector.end(), std::signbit, 0); 

  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

Thanks in advance!

The error <unresolved overloaded function type> tells you that there are
multiple overloads that could be used, but the compiler does not know which one.

One simple solution would be to use a lambda function instead of passing the function name with multiple overloads

std::replace_if (myvector.begin(), myvector.end(), [](int i){return std::signbit(i);}, 999); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM