Negate boost is_directory in std algorithm - c++

boost::filesystem::recursive_directory_iterator end, begin(directory);
auto num_of_files=std::count_if(begin, end,
std::not1(boost::filesystem::is_directory)));
I am trying to negate the function is_directory on the above directory iterator but am hitting a brick wall. I have tried specifying the template for not1 as bool(*)(const boost::filesystem::path&) and tried static casting the function both without success.
I know I can resort to a lamdba but this is cleaner if it works.
Thanks

std::not1 needs a function object as its argument. This function object can be obtained with std::ptr_fun, so this should work:
auto num_of_files=std::count_if(begin, end,
std::not1(std::ptr_fun((bool(*)(const boost::filesystem::path&))boost::filesystem::is_directory)));
(the number of parentheses is probably incorrect). BTW, you need the cast because is_directory is an overloaded function.
However, since you tag you question c++11, you could use lambdas:
auto num_of_files=std::count_if(begin, end, [](const boost::filesystem::path& p) { return !boost::filesystem::is_directory(p); });

not1 accepts an instance of functor class, which should be an Adaptable Predicate (i.e. with typedefs for return value etc.), while you are trying to feed it with a function pointer. So you need to wrap it in a functor and ptr_fun might help.
Perhaps this would work (assume using namespace std; using namespace boost;):
auto num_of_files=count_if(begin, end, not1(ptr_fun(filesystem::is_directory)));

You need ptr_fun,
this rather elaborate illustration should print 1 three times: (see also http://ideone.com/C5HTR)
#include <functional>
#include <string>
#include <algorithm>
#include <iostream>
bool pred(const std::string& s)
{
return s.size() % 2;
}
int main()
{
std::string data[] = { "hello", "world!" };
std::cout << std::count_if(data, data+2,
pred) << std::endl;
std::cout << std::count_if(data, data+2,
std::ptr_fun(pred) ) << std::endl;
std::cout << std::count_if(data, data+2,
std::not1(std::ptr_fun(pred))) << std::endl;
return 0;
}

Related

Boost.Program_Options: Why does options_description_easy_init::operator() not have an overload for std::string?

Consider this MCVE:
#include <boost/program_options.hpp>
#include <iostream>
#include <map>
namespace po = boost::program_options;
using namespace std;
po::options_description createOptions(const std::string& description, const map<string, string>& opts) {
po::options_description newoptions(description);
for (const auto& [k, v] : opts) {
newoptions.add_options()(k, v);
}
return newoptions;
}
int main() {
map<string, string> descMap = {
{ "key", "description" },
{ "hello", "world" }
};
auto opts = createOptions("My options", descMap);
cout << opts << endl;
}
I am trying to write a convenience function to reduce the amount of C&P code when inserting similar options into an options_description object (the original code uses notifiers which were removed for simplicity, but add even more boilerplate).
To my surprise, there is no options_description_easy_init::operator() overload that accepts std::string, thus the example fails to compile.
While I could easily make the example work by calling .c_str() on k and v within the for loop, of course this would be dangerous. Is there any reason why the boost devs left out such an important overload? Why didn't they use const std::string& as argument in the first place?
And how can I make this code work without .c_str()? There is no indication that the pointer memory will be copied internally (which would be odd anyway) and I really don't feel like going back in time and managing memory on my own :-)
Looking into the implementation, it seems that internally the const char* argument passed to options_description_easy_init::operator() is wrapped by a new option_description object, which eventually converts the argument into a std::string. So as commented by #pptaszni, it is safe to call .c_str() on the std::string arguments to pass them to the program options.
What I still don't understand, however, is why there is not an std::string overload. I consider this a design flaw (also considering that options_description has a constructor taking std::string).

How do I store a vector of std::bind without a specific case for the template?

After going though a question on std::bind, I was wondering if it was possible to hold a vector of functions created by std::bind so I can avoid using std::function and its heavyweight wrapping.
#include <iostream>
#include <functional>
#include <typeinfo>
#include <vector>
int add(int a, int b) {return a + b;}
int main() {
//I believe this here is just a special type of bound function.
auto add2 = std::bind(add, std::placeholders::_1, 2);
auto add3 = std::bind(add, std::placeholders::_1, 3);
//Yup.
std::cout << typeid(add2).name() << std::endl;
//Here's the type of the second function
std::cout << typeid(add3).name() << std::endl;
//Is there a nicer way to do this?
std::vector<decltype(std::bind(add, std::placeholders::_1, 1))> vec;
return 0;
}
Although it's possible of to create a vector of std::bind functions, is there a way I don't have to provide a specific case of a bound function in order to declare a container without an empty/dummy type of a function made from std::bind?
So, it appears that this isn't possible--std::bind doesn't appear to have a normally nameable/explicit type--the type is usually generated according to the signature of the bound function, and doesn't appear to be specifiable. Using std::function seems to be the only way to wrap std::bind functions and store them in a vector.
Even for lambdas, this doesn't seem possible--using a wrapper in the form of std::function seems to be the go-to answer, despite the increased size of the resulting function-object.
Possible alternatives might be storing Functor objects designed to mimic closures couples with generic objects with a type-checking layer (though this seems quite heavy). Whatever the case, using std::function seems to be the cleanest solution.
How about this?
#include <iostream>
#include <functional>
#include <vector>
int add(int a, int b) { return a + b; }
using bound_add_t = decltype(std::bind(add, std::placeholders::_1, int()));
int main() {
std::vector<bound_add_t> vec;
vec.emplace_back(add,std::placeholders::_1, 1);
vec.emplace_back(add,std::placeholders::_1, 2);
vec.emplace_back(add,std::placeholders::_1, 3);
for (auto &b : vec)
std::cout << b(5) << std::endl;
return 0;
}

Cast boost::any instance to its real type

I recently started to use Boost C++ library and I am testing the any class which can hold any data type. Actually I am trying to define the operator<< to print easily the content of any variable of type any (and sure, the class of the content should have the operator<< defined too).
I only started by sample types ( int, double ...) because they have be displayed by default. And till now, I have this code :
#include <boost/any.hpp>
#include <iostream>
#include <string>
using namespace std;
using namespace boost;
ostream& operator<<(ostream& out, any& a){
if(a.type() == typeid(int))
out << any_cast<int>(a);
else if(a.type() == typeid(double))
out << any_cast<double>(a);
// else ...
// But what about other types/classes ?!
}
int main(){
any a = 5;
cout << a << endl;
}
So the problem here is that I have to enumerate all possible types. Is there any way to cast the variable to a particular type having the type_info of this particular type ?
Boost.Any any
With boost::any you cannot do that as others have already noted in comments. That is because boost::any forgets everything about the type of value it stores and requires you to know what type is there. While you have no way to enumerate every possible type.
The solution is to change boost::any so that it forgets everything about the type of value it stores except for how to stream it out. Mooing Duck provided one solution in comments. Another would be to write a new version of boost::any but extend its internals to support the streaming operation.
Boost.Spirit hold_any
Boost.Spirit already provides something like that in <boost/spirit/home/support/detail/hold_any.hpp>.
Boost.TypeErasure any
A far better approach is however to use Boost.TypeErasure's any as was mentioned by Kerrek SB in his comment.
An example for your case (use of <<) would look like this:
#include <boost/type_erasure/any.hpp>
#include <boost/type_erasure/operators.hpp>
#include <iostream>
#include <string>
int main() {
typedef
boost::type_erasure::any<
boost::mpl::vector<
boost::type_erasure::destructible<>,
boost::type_erasure::ostreamable<>,
boost::type_erasure::relaxed
>
> my_any_type;
my_any_type my_any;
my_any = 5;
std::cout << my_any << std::endl;
my_any = 5.4;
std::cout << my_any << std::endl;
my_any = std::string("text");
std::cout << my_any << std::endl;
}

C++ Generic Swap Function

In my class.h i got:
template<class T> void Swap(T, T);
And in class.cpp:
template<class T>
void class::Swap(T& p1, T& p2)
{
T aux = p1;
p1 = p2;
p2 = aux;
}
When I try :
this->Swap<char*>(&lit[i][k], &lit[i][l]);
And another question:
What am i doing wrong here: i want to split my string after some delimitators ("+-") and strtok isn't working as I expected.
int counter = 0;
char* s = strtok(eq_clone ," ");
while(s != NULL)
{
counter++;
if(s == "")
counter--;
s = strtok(eq_clone ,"+-");
}
This looks like a mistake as it will never be true:
if(s == "")
this is comparing the address of s to the address of the string literal "": it is not checking if s is an empty string. An alternative to using strtok() would be boost::algorithm::split:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
int main()
{
std::string s("a,string+with-multiple delimiters");
std::vector<std::string> s_tokens;
boost::algorithm::split(s_tokens, s, boost::is_any_of(",+- "));
std::for_each(s_tokens.begin(),
s_tokens.end(),
[] (const std::string& s)
{
std::cout << s << "\n";
});
return 0;
}
Output:
a
string
with
multiple
delimiters
Regarding swap, as has already been stated in comments and other answer(s) just use std::swap(). I am guessing that lit is a char[][] so std::swap(lit[i][k], lit[i][l]); will do exactly what you require.
EDIT:
After comment giving declaration string* lit and that lit appears to be an array (from example usage) then use std::swap() in this manner:
std::string* lit = new std::string[4];
lit[0] = "zero";
std::swap(lit[0][1], lit[0][2]); // The characters will be passed by reference,
// don't take address.
std::cout << lit[0] << "\n"; // Prints "zreo"
Note, that the declaration of your Swap() passes arguments by value (incorrect), but the definition of Swap() passes arguments by reference (correct). If you change the declaration of your Swap() and invoke it as follows it will work (if you really don't want to use std::swap():
template<class T> void Swap(T&, T&);
//^ //^
Swap(lit[i][k], lit[i][l]);
1) Why is Swap() a class member? Class members should somehow be tightly coupled to your classes. In most cases it is is sign of bad design if something, which does not use private members or is very similar to a method that does (i.e. a convinience method), becomes a class member. C++ is not java where everything has to belong to a class. Make your swap() method a free standing template method.
2) Better yet, do not reinvent the wheel. std::swap() is there and it works mightily well. In many cases you can expect the methods and classes provided by the standard library to work better than something you could write up.
3) In your class you called the method Sort(), but the question is about Swap(). Since you did not write what you expected to happen and what actually happens, this is the only thing I can find which might be wrong.
4) Do not use strtok() in C++ unless you have to. char* are C-Style strings and should not be used in C++. Use std::string instead.

Call member function on each element in a container

This question is a matter of style, since you can always write a for loop or something similar; however, is there a less obtrusive STL or BOOST equivalent to writing:
for (container<type>::iterator iter = cointainer.begin();
iter != cointainer.end();
iter++)
iter->func();
?
Something like (imagined) this:
call_for_each(container.begin(), container.end(), &Type::func);
I think it would be 1) less typing, 2) easier to read, 3) less changes if you decided to change base type/container type.
EDIT:
Thanks for your help, now, what if I wanted to pass some arguments to the member function?
#include <algorithm> // for_each
#include <functional> // bind
// ...
std::for_each(container.begin(), container.end(),
std::bind(&Type::func));
See std::for_each and std::bind documentation for details.
Missed your edit: Anyway here is another way of achieving what you want without using Boost, if ever need be:
std::for_each(foo_vector.begin(), foo_vector.end(),
std::bind(&Foo::func, std::placeholders::_1));
You can use std::for_each or boost's foreach constructs.
Use boost's BOOST_FOREACH or BOOST_REVERSE_FOREACH when you don't want to move the logic into another function.
I found out that boost bind seems to be well suited for the task, plus you can pass additional arguments to the method:
#include <iostream>
#include <functional>
#include <boost/bind.hpp>
#include <vector>
#include <algorithm>
struct Foo {
Foo(int value) : value_(value) {
}
void func(int value) {
std::cout << "member = " << value_ << " argument = " << value << std::endl;
}
private:
int value_;
};
int main() {
std::vector<Foo> foo_vector;
for (int i = 0; i < 5; i++)
foo_vector.push_back(Foo(i));
std::for_each(foo_vector.begin(), foo_vector.end(),
boost::bind(&Foo::func, _1, 1));
}
Since C++11 standard the BOOST approach is standardized with different syntax as the "range-based-loop":
class Foo {
Foo(int x);
void foo();
}
vector<int> list = {Foo(1),Foo(2),Foo(3)};
for(auto &item: list) item.foo();
If you actually want to improve performance rather than just pretty up your code, what you really need is a map function. Eric Sink wrote a .net implementation