jeudi 31 décembre 2015

C++ code working on local MacOx but showing error on linux server

I did a project on C++. The project contains several cpp files and .h files. The project runs fine on my iMac but when I tried to run the same code on a linux sever, it is showing a lots of errors. some of the error are like:

'string' was not declared in this scope
typedef std::vector<pair<long, string> > allelic_reads;

template argument 2 is invalid
typedef std::vector<pair<long, string> > allelic_reads;

template argument 1 is invalid
void get_vcf_info(queue<string> &CH_NAME, queue<long> &POS, queue<char> &REF, queue<char> &ALT, queue<double> &QUAL);

Is this problem occurred because of discrepancies in C++11 compiler?

c++ multiple interfaces to the same functionality template

I have several methods that work over utf8 encoded strings that I usually keep in std::string.

In same cases though I just have const char* to the data, or the data is part of a bigger string I do not want to create a substring.

All the functionality boils down to one generic method say:

void foo(int a, int b, const char* beginStr, const char* endStr);

Now if I would like to avoid some ugliness I will create

void foo(int a, int b, const char* beginStr, const char* endStr);
void foo(int a, int b, const char* str);
void foo(int a, int b, const std::string% str);

and in some cases even:

void foo(int a, int b, const std::string::const_iterator& beginStr
                       const std::string::const_iterator& endStr);

This seems Ok, but as I mentioned I have several methods and it gets really annoying maintaining all these flavors.

What I am looking is some magic that could eliminate the need of multiplying every interface. Can some of the c++11 features help with solving this without performance impact - making it less chaty?

How can I use std::sort with objects that have no copy constructor?

I'm trying to sort a vector containing objects that are not copy constructible or default constructible (but are move constructible), but I get errors about the compiler not being able to find a valid function for swap. I thought that having a move constructor would be enough. What am I missing here?

class MyType {
public:
    MyType(bool a) {}
    MyType(const MyType& that) = delete;
    MyType(MyType&& that) = default;
};

int main(void) {
    vector<MyType> v;
    v.emplace_back(true);
    sort(v.begin(), v.end(), [](MyType const& l, MyType const& r) {
        return true;
    });
}

Iterate an std::vector by capacity

When I fill an std::vector knowing in advance the final size, I usually reserve its capacity in advance to avoid reallocation of its content (which on C++03 involves calling copy constructors for each object already stored in the vector).

This is a trivial example:

std::vector<int> v;
v.reserve(10);
std::vector<int>::size_type capacity = v.capacity();

for( std::vector<int>::size_type i = 0; i < capacity; ++i )
{
    v.push_back(i);
}

There's a better way to loop around the std::vector capacity?

I'm looking for both C++03 and C++11 answers.

Edit: I rewrote the sample because all the answer and comments where going off topic, concerning only filling the std::vector with an array, which is not the point of the question.

Simulating nan/inf in a constexpr variable template

Is there a way to simulate nan/inf in a constant expression and without! using the C macros HUGE_VAL and INFINITY or any other for that matter! Plus, even with them, it still isn't constexpr.

I do not wish to use any standard function that the C++ standard library or the C standard library provides.

Of course the following doesn't compile. Compiler says constexpr variable must be initialized with a constant expression...

template<typename T = double>
constexpr T NaN = T(0.0 / 0.0);

Method that the MSVC compiler uses also doesn't compile:

template<typename T = double>
constexpr T NaN = T(1e+300); //with some changes, apparently having the float overflow

I know this is kind of broad, but this is for a library and I'm looking for some educated advice! Thanks!

Class operator[] does not return a lhv

Consider this class:

#include <vector>
using namespace std;

template<typename T>
class Vector{
private:
    size_t      size_;
    vector<T>   items;

public:
    Vector(){ size_ = 0; }
    inline void clear(){ size_ = 0; }
    inline void push_back( const T item ){
        if( items.size() == size_ )
            items.push_back( item );
        else
            items[size_] = item;
        size_++;
    }
    inline const T& operator[](int i) const { return items[i]; }
    inline T& operator[](int i) { return items[i]; }
};

int main(int argc, char *argv[]){
    Vector<bool> vec;
    vec.push_back( true );
    if( vec[0] )
        vec[0] = false;
}

When compiling with MSVS 2013 you get the following error for the non const operator[]: error C2440: 'return' : cannot convert from 'std::_Vb_reference<std::_Wrap_alloc<std::allocator<char32_t>>>' to 'bool &'

Changing the return statement in return (T&)(items[i]); results in a warning warning C4238: nonstandard extension used : class rvalue used as lvalue

The program runs (in debug mode) but the last statement does not change the value of vec[0] (as you should expect for a rhv).

What's wrong here?

Is there any way to insert a unique_ptr into a map in C++0x/gcc 4.4.7)?

I can't figure out how to do it; it's driving me nuts.

#include <iostream>
#include <memory>
#include <map>

int main()
{
    std::map<std::string, std::unique_ptr<std::string>> map;
    std::unique_ptr<std::string> bar(new std::string("bar"));
    map["foo"] = std::move(bar);

    std::cout << "foo: " << *(map["foo"]) << std::endl;
}

This compiles just fine on gcc v4.9.2:

$ g++ -std=c++0x test.cc -o test

Unfortunately, all I have available to me is gcc v4.4.7, which produces a hideous error message that I'll stick at the bottom.

I can push_back unique_ptrs into vectors just fine; I don't understand why there's an issue with map.

I've also tried using insert:

int main()
{
    std::map<std::string, std::unique_ptr<std::string>> map;
    std::unique_ptr<std::string> bar(new std::string("bar"));
    auto pair = std::make_pair("foo", std::move(bar));
    map.insert(std::move(pair));

    std::cout << "foo: " << *(map["foo"]) << std::endl;
}

I can make the pair just fine, but when I try to move it into insert I get the error. It appears that it's trying to call the copy constructor for some reason, but I don't understand why, since I'm moveing it.

emplace has the same result:

int main()
{
    std::map<std::string, std::unique_ptr<std::string>> map;
    std::unique_ptr<std::string> bar(new std::string("bar"));
    auto pair = std::make_pair("foo", std::move(bar));
    map.emplace(std::move(pair));

    std::cout << "foo: " << *(map["foo"]) << std::endl;
}

Both of these compile fine in g++ v4.9.2, but not in v4.4.7.

Anyone have any ideas on an alternative way to do this (in v4.4.7)?

Full error message output (from the first example):

In file included from /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_algobase.h:66,
                 from /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/char_traits.h:41, 
                 from /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/ios:41,                
                 from /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/ostream:40,            
                 from /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/iostream:40,           
                 from test.cc:1:
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/unique_ptr.h: In copy constructor 'std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::unique_ptr<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::default_delete<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >::pair(const std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::unique_ptr<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::default_delete<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >&)':
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_pair.h:68:   instantiated from 'std::_Rb_tree_node<_Val>::_Rb_tree_node(_Args&& ...) [with _Args = const std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::unique_ptr<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::default_delete<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >&, _Val = std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::unique_ptr<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::default_delete<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >]'
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/ext/new_allocator.h:111:   instantiated from 'void __gnu_cxx::new_allocator<_Tp>::construct(_Tp*, _Args&& ...) [with _Args = const std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::unique_ptr<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::default_delete<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >&, _Tp = std::_Rb_tree_node<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::unique_ptr<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::default_delete<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > > >]'
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_tree.h:394:   instantiated from 'std::_Rb_tree_node<_Val>* std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_create_node(_Args&& ...) [with _Args = const std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::unique_ptr<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::default_delete<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >&, _Key = std::basic_string<char, std::char_traits<char>, std::allocator<char> >, _Val = std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::unique_ptr<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::default_delete<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >, _KeyOfValue = std::_Select1st<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::unique_ptr<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::default_delete<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > > >, _Compare = std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, _Alloc = std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::unique_ptr<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::default_delete<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > > >]'
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_tree.h:881:   instantiated from 'std::_Rb_tree_iterator<_Val> std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_insert_(const std::_Rb_tree_node_base*, const std::_Rb_tree_node_base*, const _Val&) [with _Key = std::basic_string<char, std::char_traits<char>, std::allocator<char> >, _Val = std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::unique_ptr<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::default_delete<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >, _KeyOfValue = std::_Select1st<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::unique_ptr<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::default_delete<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > > >, _Compare = std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, _Alloc = std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::unique_ptr<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::default_delete<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > > >]'
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_tree.h:1215:   instantiated from 'std::_Rb_tree_iterator<_Val> std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_insert_unique_(std::_Rb_tree_const_iterator<_Val>, const _Val&) [with _Key = std::basic_string<char, std::char_traits<char>, std::allocator<char> >, _Val = std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::unique_ptr<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::default_delete<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >, _KeyOfValue = std::_Select1st<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::unique_ptr<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::default_delete<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > > >, _Compare = std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, _Alloc = std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::unique_ptr<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::default_delete<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > > >]'
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_map.h:540:   instantiated from 'typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_Select1st<std::pair<const _Key, _Tp> >, _Compare, typename _Alloc::rebind<std::pair<const _Key, _Tp> >::other>::iterator std::map<_Key, _Tp, _Compare, _Alloc>::insert(typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_Select1st<std::pair<const _Key, _Tp> >, _Compare, typename _Alloc::rebind<std::pair<const _Key, _Tp> >::other>::iterator, const std::pair<const _Key, _Tp>&) [with _Key = std::basic_string<char, std::char_traits<char>, std::allocator<char> >, _Tp = std::unique_ptr<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::default_delete<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >, _Compare = std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, _Alloc = std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::unique_ptr<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::default_delete<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > > >]'
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_map.h:450:   instantiated from '_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = std::basic_string<char, std::char_traits<char>, std::allocator<char> >, _Tp = std::unique_ptr<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::default_delete<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >, _Compare = std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, _Alloc = std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::unique_ptr<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::default_delete<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > > >]'
test.cc:9:   instantiated from here
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/unique_ptr.h:214: error: deleted function 'std::unique_ptr<_Tp, _Tp_Deleter>::unique_ptr(const std::unique_ptr<_Tp, _Tp_Deleter>&) [with _Tp = std::basic_string<char, std::char_traits<char>, std::allocator<char> >, _Tp_Deleter = std::default_delete<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >]'
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_pair.h:68: error: used here
In file included from /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/map:60,
                 from test.cc:3:
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_tree.h: In constructor 'std::_Rb_tree_node<_Val>::_Rb_tree_node(_Args&& ...) [with _Args = const std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::unique_ptr<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::default_delete<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >&, _Val = std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::unique_ptr<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::default_delete<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >]':
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_tree.h:136: note: synthesized method 'std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::unique_ptr<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::default_delete<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >::pair(const std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::unique_ptr<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::default_delete<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >&)' first required here

Eigen and c++11 assignment and rreference

I'm getting very confused with c++11 move semantics and especially with eigen- does it have an assignment operator for rvalue (operator=(Type&&)), or not?

This code crashes over size mismatch:

    Eigen::VectorXd&& func(){
        Eigen::VectorXd&& v=Eigen::VectorXd::Zero(5);
        return std::move(v);
    }

    Eigen::VectorXd v=Eigen::VectorXd::Zero(10);
    v.block(0,0,5,1)=func();

The only way it worked was if func was defined as:

    Eigen::VectorXd func(){
        Eigen::VectorXd v=Eigen::VectorXd::Zero(5);
        return v;
    }

Even the regular single reference (&) didn't work. When can I use these references? What is going on with the memory? Thanks!

C++ 11 operator overload with return type deduction

I have a template class that depends on one type (for example template <typename T> class Vector). Now, I want to overload the arithmetic operators such that:

  • I can them to Vectors instantiated with two different types;
  • The result is deduced in the same way of the template instance types;

Example:

Vector<float> fv = {1.5, 2.5};
Vector<int> iv = {1,2};
auto s1 = fv + iv;   // s1 MUST be of type Vector<float> == {2.5, 4.5}
auto s2 = iv + fv;   // s2 MUST be of type Vector<float> == {2.5, 4.5}

I think that, in a generic purpose mathematical library that implements Matrices, Vectors, Polynomials, etc., this would be a feature that makes the difference in terms of usability.

I found three ways to obtain this result with C++11

  1. -> notation

    template <typename T, typename U>
    auto operator +(const Vector<T> &lhs, const Vector<U> &rhs)
        -> Vector<decltype(lhs[0]+rhs[0])>
    {
        Vector<decltype(lhs[0]+rhs[0])> res(lhs);
        res += rhs;
        return std::move(res);
    }
    
    
  2. declval

    template <typename T, typename U> 
    Vector<decltype(std::declval<T>()+std::declval<U>())> 
    operator +(const Vector<T> &lhs, const Vector<U> &rhs)
    {
        Vector<decltype(lhs[0]+rhs[0])> res(lhs);
        res += rhs;
        return std::move(res);
    }
    
    
  3. declval as default type arg

    template <typename T, typename U, 
              typename R = decltype(std::declval<T>()+std::declval<U>())> 
    Vector<R> operator *(const Vector<T> &lhs, const Vector<U> &rhs)
    {
        Vector<decltype(lhs[0]+rhs[0])> res(lhs);
        res += rhs;
        return std::move(res);
    }
    
    

What, in your opinion, the best approach to implement such a feature? If is there a FOURTH better solution I'll appreciate it.

Do you consider such "interworking" operators a worthwhile feature?

Thanks and Best Regards, Davide

Lambda takes iterator as paramters

How to create a lambda function that accepts iterators for vector,list,array? Something like:

auto do_somthing=[](iterator beg,iterator end){
    //code here
}

C++(11) "High Performance" Concurrent Single Writer(s)

I have an object B, composed of 10 double values. The double values are produced by a sensor which communicates via ethernet and sends out updates once every 1-2 milliseconds. Instances of B must be used at 2 other places in the program to do some calculations and visualization.

In another thread, an object A, holding ~1000 double values is updated every 4-10 milliseconds using another sensor.

Both objects have a time signature (procured by using boost::chrono::high_resolution_clock when the sensor's update arrives)

Now I want to use two objects A and B that have been updated at nearly the same time to calculate some values for an object C. This should be done while both threads are running, and the output used to do some visualization, computing averages, etc. The whole procedure is running for 1-2 hours and only instances of calculated Cs are used after that, instances of A and B are not longer needed.

What is the recommended method (or design pattern) to implement this communication and data sharing between the threads ?

At the moment, this whole construct is badly implemented, and the thread composing A communicates directly with the one composing B without using synchronization methods like mutexes.

  • Should I use lockless double ended queues for storing A and Bs and read from this in the thread composing C?
  • Should I use an (thread-safe) observer pattern like boost::signals2 to "send" the instances of A and B ?
  • Or something different ?

C++ templates specializations and xcode

I have the following error from xcode:

"Template argument for template template parameter must be a class template or type alias template"

However the same exact code works fine in visual studio.

template< typename T_NODE, template< typename > class T_ALLOCATOR >
class qt_fixed_pool_general {};

template< template< typename, int > class T_ALLOCATOR, int T_COUNT >
struct static_to_dynamic
{ template< typename T_NODE > using t_allocator = T_ALLOCATOR< T_NODE,T_COUNT >; };

template< typename T_NODE, int T_COUNT >
struct safe_array {};

template< class T_NODE, int T_COUNT >
class qt_fixed_pool_static : public qt_fixed_pool_general< 
      T_NODE, 
      static_to_dynamic< safe_array, T_COUNT >::t_allocator >
{};

Any ideas what it may be going on? I am using xcode: 7.2

Thanks

std::iota is very limited

Coming from a Python world, I find the function std::iota very limited. Why is the interface restricted to not take any UnaryFunction ?

For instance I can convert

>>> x = range(0, 10)

into

std::vector<int> x(10);
std::iota(std::begin(x), std::end(x), 0);

But how would one do:

>>> x = range(0,20,2)

or even

>>> x = range(10,0,-1)

I know this is trivial to write one such function or use Boost, but I figured that C++ committee must have picked this design with care. So clearly I am missing something from C++11.

for Android application, best solution of transferring 128 bit unsigned data between native and java?

with "best", I mean minimum memory consuming. the best solution it comes to me is that using four "unsigned long" data.

what C++11 and Java used for 64-bit unsigned data ?

OOP implementation details in C++

Speaking from an Object-Oriented point of view. What are some good guidelines about hiding implementation details from the reader? To go in further depth, three things that were clearly on my mind were

  1. Where would using opaque pointers and incomplete types be a good idea?
  2. Should I hide static member variables and give them file scope (in the implementation file) instead?
  3. Is it wise to only include the public interface as much as possible in a header file for a class and hide all the implementation details as much as possible with the help of opaque pointers?

NOTE : I am not looking to implementing interfaces in the context of inheritance. But rather an virtual base class free design. I personally don't like having virtual base classes where they are not needed. And the use case I have in mind is of a class which should not be extended but rather simply used to provide some sort of focused functionality. I hope that was not too vague :(

I know the above question is asking for personal opinion, if the members of the SO community feel like it should not be here. I would gladly take it down. But if someone wants to have a discussion then I would be open to any sorts of suggestions! Thanks!

the arrow '->' separator is crashing when calling function from class

I'm working on a project for class and I'm using classes and pointers of type class to call some functions in the class but it's crashing on Code Blocks and Eclipse and I don't know what is going on Note it crashes when assigning x with y

#include <iostream>

using namespace std;

class a{
private:
    int x;
public:
    void set_X(int y){
        x=y;
    }
};

int main()
{
    a *Ptr;
    Ptr->set_X(5);
}

c++ constexpr pointer casting

The code below explains the problem

    constexpr int x = *(reinterpret_cast<const int*>("abcd")); //wrong
    constexpr int y = ("abcd")[0]*1l + ("abcd")[1]*256l + ("abcd")[2]*256*256l + ("abcd")[3]*256*256*256l; //ok

How can I do such type casting in constexpr expression?

mercredi 30 décembre 2015

Why does the standard allow a tuple of rvalue references to be assigned to by a tuple of lvalue references?

It seems like a std::tuple containing one or more references has unexpected behavior with regards to construction and assignment (especially copy/move construction and copy/move assignment). It's different from the behavior of both std::reference_wrapper (changes the referred to object) and a struct with a member reference variable (assignment operator deleted). It allows for the convenient std::tie python like multiple return values, but it also allows obviously incorrect code like the following (link here):

#include <tuple>

int main()
{
    std::tuple<int&> x{std::forward_as_tuple(9)}; // OK
    std::forward_as_tuple(5) = x; // OK
    // std::get<0>(std::forward_as_tuple(5)) = std::get<0>(x); // ERROR - and should be
    return 0;
}

The standard seems to require or strongly hint at this behavior in the copy(ish) assignment section 20.4.2.2.9 of the latest working draft (Ti& will collapse to lvalue ref):

template <class... UTypes> tuple& operator=(const tuple<UTypes...>& u);

9 Requires: sizeof...(Types) == sizeof...(UTypes) and is_assignable<Ti&, const Ui&>::value is true for all i.

10 Effects: Assigns each element of u to the corresponding element of *this.

11 Returns: *this

Although the move(ish) construction section 20.4.2.1.20 is less clear (is_constructible<int&, int&&> returns false):

template <class... UTypes> EXPLICIT constexpr tuple(tuple<UTypes...>&& u);

18 Requires: sizeof...(Types) == sizeof...(UTypes).

19 Effects: For all i, the constructor initializes the ith element of *this with std::forward<Ui>(get<i>(u)).

20 Remarks: This constructor shall not participate in overload resolution unless is_constructible<Ti, Ui&&>::value is true for all i. The constructor is explicit if and only if is_convertible<Ui&&, Ti>::value is false for at least one i.

These are not the only affected subsections.

The question is, why is this behavior desired? Also, if there are other parts of the standard at play, or I'm misunderstanding it, explain where I went wrong.

Thanks!

Create a new function in the class method (C++11) [duplicate]

This question already has an answer here:

I have a class A:

class Date
{
    int myFoo1();
};
int Date::myFoo1()
{

}

I want to create myFoo2 inside myFoo1 like this:

int Date::myFoo1()
{
  int myFoo2()
  {

  }
}

I get this error:

 error: a function-definition is not allowed here before ‘{’ token
     {
     ^

How can I define such a function?

Resolving errors in std headers when using std methods/classes incorrectly

I am new to C++ and I frequently come into a situation where I get a compile time error while using std templated classes/containers/methods.

Most of the time, error is shown inside of some std header file that I don't include directly. Furthermore, offending line is always inside of some method that I don't call directly.

So I have no idea which line of my code eventually leads to that error. In other words, I can't determine the call stack (if it can be called so in this case) that causes the error.

Is there an efficient "debugging" process that I can use when determining offending code in case of errors like this?

This is an example of such error. I will figure this error out somehow, so I am not interested in this particular error, but rather in more general solution to problems such as this.

Error C2280 'MyNamespace::MyClass &MyNamespace::MyClass::operator =(const MyNamespace::MyClass &)': attempting to reference a deleted function MyLib c:\program files (x86)\microsoft visual studio 14.0\vc\include\utility 53

Why are std::vector and std::string's comparison operators defined as template functions?

A little overview. I'm writing a class template that provides a strong typedef; by strong typedef I am contrasting with a regular typedef which just declares an alias. To give an idea:

using EmployeeId = StrongTypedef<int>;

Now, there are different schools of thought on strong typedefs and implicit conversions. One of these schools says: not every integer is an EmployeeId, but every EmployeeId is an integer, so you should allow implicit conversions from EmployeeId to integer. And you can implement this, and write things like:

EmployeeId x(4);
assert(x == 4);

This works because x gets implicitly converted to an integer, and then integer equality comparison is used. So far, so good. Now, I want to do this with a vector of integers:

using EmployeeScores = StrongTypedef<std::vector<int>>;

So I can do things like this:

std::vector<int> v1{1,2};
EmployeeScores e(v1);
std::vector<int> v2(e); // implicit conversion
assert(v1 == v2);

But I still can't do this:

assert(v1 == e);

The reason this doesn't work is because of how std::vector defines its equality check, basically (modulo standardese):

template <class T, class A>
bool operator==(const vector<T,A> & v1, const vector<T,A> & v2) {
...
}

This is a function template; because it gets discarded in an earlier phase of lookup it will not allow a type that converts implicitly to vector to be compared.

A different way to define equality would be like this:

template <class T, class A = std::allocator<T>>
class vector {
... // body

  friend bool operator==(const vector & v1, const vector & v2) {
  ...
}

} // end of class vector

In this second case, the equality operator is not a function template, it's just a regular function that's generated along with the class, similar to a member function. This is an unusual case enabled by the friend keyword.

The question (sorry the background was so long), is why doesn't std::vector use the second form instead of the first? This makes vector behave more like primitive types, and as you can clearly see it helps with my use case. This behavior is even more surprising with string since it's easy to forget that string is just a typedef of a class template.

Two things I've considered: first, some may think that because the friend function gets generated with the class, this will cause a hard failure if the contained type of the vector does not support equality comparison. This is not the case; like member functions of template classes, they aren't generated if unused. Second, in the more general case, free functions have the advantage that they don't need to be defined in the same header as the class, which can have advantages. But this clearly isn't utilized here.

So, what gives? Is there a good reason for this, or was it just a sub-optimal choice?

Why is my std::unordered_map access time not constant

I wrote some code to test my unordered map performance with a 2 component vector as a key.

std::unordered_map<Vector2i, int> m;                                                                      

for(int i = 0; i < 1000; ++i)                                                                             
    for(int j = 0; j < 1000; ++j)                                                                         
        m[Vector2i(i,j)] = i*j+27*j;                                                                      

clock.restart();                                                                                          

auto found = m.find(Vector2i(0,5));                                                                                                                                                            

std::cout << clock.getElapsedTime().asMicroseconds() << std::endl;                                         

output for the code above: 56 (microseconds) When I replace 1000 in the for loops by 100 the outputs is 2 (microseconds) Isn't the time supposed to be constant ?

hash function for my Vector2i:

namespace std                                                                                                    
{

   template<>                                                                                                   
    struct hash<Vector2i>                                                                                        
    {                                                                                                            
        std::size_t operator()(const Vector2i& k) const                                                          
        {                                                                                                        
            using std::size_t;                                                                                   
            using std::hash;                                                                                     
            using std::string;                                                                                   

            return (hash<int>()(k.x)) ^ (hash<int>()(k.y) << 1);                                                 
        }                                                                                                        

    };                                                                                                           


}                                                                             

EDIT: I added this code to count the collisions after the for loop:

for (size_t bucket = 0; bucket != m.bucket_count(); ++bucket)                                             
    if (m.bucket_size(bucket) > 1)                                                                        
         ++collisions; 

With 100*100 elements: collisions = 256

1000*1000 elements: collisions = 2048

Behavior of the poll() system call and receiving or sending data afterwards

Lets consider following piece of code

pollfd file_descriptors[1];
file_descriptors[0].fd = sock_fd;
file_descriptors[0].events = POLLIN | POLLPRI;

int return_value = poll(file_descriptors, 1, 0);

if (return_value == -1) { cerr << strerror(errno); }
else if (return_value == 0) { cerr << "No data available to be read"; }
else { 
    int received = 0;
    if (file_descriptors[0].revents & POLLIN) {
        received += recv(sock_fd, buff, 1024, 0); 
    }

    if (file_descriptors[0].revents & POLLPRI) {
        recv(sock_fd, buff + received, 1024 - received, MSG_OOB);
    }
}

Now I have three questions regarding the above code.

  1. If the call to poll() returns neither -1 nor 0 and sets the POLLIN flag in the bitmap revents for the first entry in the file_descriptors array, then will the call to recv() block? If no, then will the data be read in instantaneously?
  2. Assuming the call to poll() goes the same way as mentioned above. How much data is going to be read in? Is it just going to be the same as a regular call to recv()? i.e. an arbitrary (to the programmer) amount less than or equal to 1024 in the above case. Then if I want to poll() before reading again, do I just repeat from the first invocation of poll()?
  3. What exactly is out-of-band data? I apologize for asking this here but I did look this up a little on Google and I didn't understand when exactly I can expect there to be out of band data in the socket to be read. Is the above way of reading in out-of-band data along with regular data correct?

Thank you!

How can I double a time value in C++

The task is to double a time from the txt file "time.in" in the format of HH:MM:SS (e.g. 12:22:03) and to output it in the same format (e.g. 24:44:06) in "time.out". I am having trouble skipping the ":" character in the input. Here's my code:

#include <fstream>
#include <cmath>
#include <stdio.h>
using namespace std;

int main() {
FILE *fin = fopen("time.in", "r");
FILE *fout = fopen("time.out", "w");
char c;
double hrs, mins, secs;
double fhrs = 0, fmins = 0, fsecs = 0;

ifstream input;
input.open("time.in");
input>> hrs;
c = fgetc(fin); //what should this be? I can't get it to work properly.
input>> mins;
c = fgetc(fin);
input>> secs;
input.close();

fhrs = hrs * 2;
if (secs < 30) {
    fsecs = secs * 2;
    if (mins < 30)
        fmins = mins * 2;
    else {
        fmins = abs(60 - (mins * 2));
        fhrs++;
    }
} else {
    fsecs = abs(60 - (secs * 2));
    fmins++;
    if (mins < 30)
        fmins += mins * 2;
    else {
        fmins += abs(60 - (mins * 2));
        fhrs++;
    }
}

ofstream output;
output.open("time.out");
output << fhrs <<":"<< fmins <<":"<< fsecs <<endl;
output.close();

return 0;

}

how do I set compilingflags in a makefile?

I'm used to program in IDEs, but switched to vim and plugins recently. Now I try to write a makefile for a c++ project, but somehow if I run make I always get the error

g++    -c -o *.o createOutput.cpp
In file included from /usr/include/c++/4.8/thread:35:0,
                 from createOutput.cpp:5:
/usr/include/c++/4.8/bits/c++0x_warning.h:32:2: error: #error This file requires compiler and library support for the ISO C++ 2011 standard. This support is currently experimental, and must be enabled with the -std=c++11 or -std=gnu++11 compiler options.
 #error This file requires compiler and library support for the \
  ^

This is my makefile:

CC = clang++

# compiler flags
CFLAGS = -O3 -Wall -Werror -std=c++11
CFLAGS_SFML = -lsfml-graphics -lsfml-window -lsfml-system

all: program.exe clean

program.exe: *.o
    $(CC) -o program.exe *.o $(CFLAGS) $(CFLAGS_SFML) 

getInput.o: getInput.cpp
    $(CC) -c getInput.cpp $(CFLAGS) 

createOutput.o: createOutput.cpp
    $(CC) -c createOutput.cpp $(CFLAGS) 

main.o: main.cpp
    $(CC) -c main.cpp $(CFLAGS)

.PHONY: clean
clean:
    rm *.o
    @echo clean done

Where is my error? Why is it using g++ instead of clang? And why isn't it using the -std=c++11 parameter? Sorry for the beginner questions, I unfortunately can't find a solution with google.

N-dimensionally nested metaloops with templates

Is it possible to do N-dimensionally nested metaloops with template metaprogramming? The nesting part is trivial, however passing all the arbitrary number of iteration indices as template parameters to the most-inner loop seems problematic.

A simple unnested metaloop looks like:

template <size_t I, size_t N>
struct meta_for
{
    template <typename Lambda>
    inline meta_for(Lambda &&iteration)
    {
        iteration(I);
        meta_for<I+1, N> next(static_cast<Lambda&&>(iteration));
    }
};

template <size_t N>
struct meta_for<N, N>
{
    template <typename Lambda>
    inline meta_for(Lambda &&iteration)
    {
        return;
    }
};

using smart pointers as global variables

Let's say I have a program in which I must use a global variable (of some class type).

I would like to be able to use smart pointers so I won't have to worry about deleting it.

in some file Common.hpp file I have the declaration:

extern unique_ptr<CommandBuffer> globalCommandBuffer;

and in my main.cpp:

#include "Common.hpp"

int main(int argc, char* argv[]) {   
   globalCommandBuffer(new CommandBuffer());
}

this creates many compilation errors. so obviously I'm doing it wrong.

my questions are:

  • is it a good design choice to use smart pointers for global variables?
  • if so, what is the correct way of doing so?
  • which smart pointer is preferable?

std vector at could not resolve on eclipse

I have this code in eclipse:

#include <vector>

typedef struct tal{
    tal()
    :a(0), b(0)
    {};
    int a;
    int b;
} Tal;

int main() {
    std::vector<Tal> tal_vec;
    Tal tt;
    tal_vec.push_back(tt);
    Tal tt2 = tal_vec.at(0);
    tt2.a;

    int c = tal_vec.at(0).a;
}

At the last statement: int c = tal_vec.at(0).a;
Eclipse tell me: Field 'a' could not be resolved.

Already tell CDT GCC Builtin Compiler add this: -std=c++11 flag like here

In the other statement you can see that there is no error if i tell eclipse to go Tal tt2 = tal_vec.at(0); the after that to get filed a value.

can anyone suggest a solution?

Enable multithreading Eclipse C++

I have been trying to get a program working in Eclipse C++. One of the functions uses multithreading from std. Here is the function in the code:

void PrimeCheck::checkFull(long long int number)
{
    std::thread t1(&PrimeCheck::checkFirstHalf, this, number);
    std::thread t2(&PrimeCheck::checkSecondHalf, this, number);

    t1.join();
    t2.join();
}

When searching for a solution, I came across many solutions, all of which stating to either add a -pthread flag or a -std=c++11 in addition to changing the dialect to C++11. All of which I have done. This is what the compile command looks like in eclipse so you can see exactly which modifications I have already added:

Building file: ../src/Prime Checker.cpp
Invoking: GCC C++ Compiler
g++ -std=c++0x -D__GXX_EXPERIMENTAL_CXX0X__ -O2 -g -Wall -c -fmessage-length=0 -std=c++11  -pthread -Wl,--whole-archive -lpthread -Wl,--no-whole-archive -MMD -MP -MF"src/Prime Checker.d" -MT"src/Prime\ Checker.d" -o "src/Prime Checker.o" "../src/Prime Checker.cpp"
Finished building: ../src/Prime Checker.cpp

And this is the linker command as it appears in eclipse:

Invoking: GCC C++ Linker
g++ -Wl,--no-as-needed -pthread -shared -o [A bunch of .o files]

The code compiles correctly, and eclipse content assist recognizes thread as a member of std. Yet, when I run the program I still this error:

terminate called after throwing an instance of 'std::system_error'
  what():  Enable multithreading to use std::thread: Operation not permitted

To test this, I wrote a simple program outside of Eclipse which looked like this:

#include <thread>
#include <iostream>

using namespace std;

void func1(int x){
    for(int i=0; i<x; i++){
        cout << " " << 1 + i;
    }
}

void func2(){
    for(int j=0; j<5; j++){
        cout << "Standard message! ";
    }
}

int main(){
    int input;
    cout << "Give me a number:" << endl;
    cin >> input;

    thread t1(func1, input);
    thread t2(func2);
    t1.join();
    t2.join();


    return 0;
}

And compiled it in the terminal with this:

g++ ThreadTest.cpp -o Program.o -std=c++11 -pthread

And the program ran without error. I think this means that there's something wrong with Eclipse, but I'm not sure.

As a note, I'm doing this on Ubuntu 14.04 with gcc version 4.8.4. Also, I know that similar questions have been asked, but as far as I can tell, I've implemented those solutions with little success.

Help would be appreciated. Thanks!

Call method on parameter pack [duplicate]

This question already has an answer here:

I am trying to pass a parameter pack to a function. This function then needs to call a method on each element of the parameter pack. My (non-compiling) attempt here is this:

template <typename... TYPES>
void function_caller(const TYPES &... entries)
{
    // Doesn't compile!
    (entries...).some_method();
}

struct Foo { void some_method() { } };
struct Bar { void some_method() { } };

int main()
{
    Foo foo;
    Bar bar;

    function_caller(foo, bar);

    return 0;
}

clang++ doesn't like my parameter pack expansion. Is there a way to fix this without adding helper functions?

Private nested classes - C++11 compiler misbehavior? Or as designed? [duplicate]

This question already has an answer here:

Consider the following code:

class Main
{
  private:
      class Inner
      {
        public:
          void DoSomething() {}
      };

  public:
    static Inner* CreateInner() { return new Inner(); }
 };

It is impossible to compile the following:

Main::Inner* pInner = Main::CreateInner();
pInner->DoSomething();

Because we'll get a compiler error 'C2248: cannot access private class decalred in class Main'

However, using the following syntax will compile and execute smoothly:

auto pInner = Main::CreateInner();
pInner->DoSomething();

Suddenly, (to my surprise, anyway...), the inner private class is 'visible' to the outside world...

Does anyone aware to this compiler behavior? Is it considered 'valid' to use the auto keyword according to the C++11 standard in this case, or is it some kind of a bug?

It behaves as described on both:

  1. Visual Studio 2010 - platform toolset v100
  2. Visual Studio 2013 - platform toolset v120

Any thoughts?

Thanks!

Effective construction std::string from std::unordered_set

I have an unordered_set of chars

std::unordered_set<char> u_setAlphabet;

Then I want to get a content from the set as std::string. My implementation now looks like this:

std::string getAlphabet() {
    std::string strAlphabet;
    for (const char& character : u_setAlphabet)
        strAlphabet += character;
    return strAlphabet;
}

Is this a good way to solve this task? The additions of signle chars to string seems not to be optimal for large u_setAlphabet (multiple reallocs?). Is there any other method to it?

Get current number of hours and minutes using chrono::time_point

I have been trying to find an example using std::chrono which simply gets a chrono::time_point and extracts the number of hours and number of minutes as integers.

I have:

std::chrono::system_clock::time_point now = std::chrono::system_clock::now();

but I cannot find out how to then extract the hours and the minutes (since midnight)? I am looking for something like:

int hours = now.clock.hours();

CCCallFunc::create(this, callfunc_selector(Wack_ModeSelection::ParticleAnimation)); this callback showing error in cocos2d 3.0

please give the alternate of FiniteTimeAction* callFunc=CCCallFunc::create(this,callfunc_selector(Wack_ModeSelection::ParticleAnimation));

Printing out result between a date range in a text file and print them dates only?

I quite confused on how to implement a c++ code that takes an start and end date string from a text file and print out the dates between that range?

Need Mac compatile 64-bit version of nsppxl.lib (Intel NSP FIR Library)

I am using nsppxl.lib (Intel NSP FIR Library) as a dependency for old MFC based image processing code which is written in Visual Studio 2005. Now i want to move this code to standard C++ 11 so that I can use it on Mac OS platform as well. " I need Mac compatible (static library) 64 bit version of nsppxl.lib ". I have searched for the same on Intel site and forum but no help so far. Thanks.

How to insert value in c++ map std::map

I am trying to insert a value in map where key to map is string and value is list. When I try to insert then I am getting error.

#include <iostream>
#include <utility>
#include <vector>
#include <map>
#include <string>
using namespace std;
main()
{
     string key = "myKey";
     string str1 = "str1";

     map<string, list<string>> myMap;
     myMap.insert( make_pair (key, str1));

 }

error

Error 2 error C2664: 'std::pair<_Ty1,_Ty2> std::_Tree<_Traits>::insert(std::pair &&)' : cannot convert parameter 1 from 'std::pair<_Ty1,_Ty2>' to 'std::pair<_Ty1,_Ty2> &&'

Help is appreciated !!

Start with Qt with weak C++ knowledge

Whether it is wise to start using Qt with a weak C++ knowledge? Or it is more recommended to go throught C++ 5th Primer book and then switch to Qt?

mardi 29 décembre 2015

Widget Cross Thread GUI update

How can I implemante the following in Widget? I want to update GUI in a detached background thread. c++ language

Why does std::copy_n take a template parameter instead of std::size_t?

So simple question.

template<class InputIt, class Size, class OutputIt>
OutputIt copy_n(InputIt first, Size count, OutputIt result);

Why does std::copy_n take a type for the number of elements it's going to copy instead of simply std::size_t? I just can't think of a reason.

template<class InputIt, class OutputIt>
OutputIt copy_n(InputIt first, std::size_t count, OutputIt result);

How do I call make_shared or make_unique with a templated Constructor

How can I call make_shared or make_unique on a class that has a templated constructor? Here's an example:

class A
{
    template <class T> A() { ... }
};

make_shared<A<T>>() doesn't make sense (nor does it compile), since that would rather be for a templated class, not a templated constructor.

Neither make_shared<A><T>() nor make_shared<A>(<T>()) compile---nor look like they should. Ditto on make_shared<A, T>()

Is there any way to specify the template for the constructor call in the call to make_shared? I assume the answer would apply for make_unique; if it doesn't, please indicate that. Thanks!

How do you create a custom deleter for a unique_ptr class member that wraps a c function which requires 2 arguments?

I am trying to use mupdf to create a program (in Qt) that will allow me to list the objects of the document as a list and allow me to select which objects to render / not render. Since Qt is c++, and I am more comfortable with it, I am trying to wrap structures defined in mupdf in C++ classes. Right now my problem is this - one of the first things you do in mupdf is create a global context, that is passed around to everything, including functions that clean up and delete structures. I am familiar with creating an object that has an overloaded operator(), much like:

struct ContextDeleter
{
    inline void operator()(fz_context* ctx)
    {
        fz_drop_context(ctx);
    }
};

which you would then hand to unique_ptr -

std::unique_ptr<fz_context, ContextDeleter> ctxPtr;

What I can't figure out is how to do the same thing with function like:

fz_drop_page(ctx, page);

ie:

struct PageDeleter
{
     inline void operator()(fz_context* ctx, fz_page* pg)
     {
          fz_drop_page(ctx, pg);
     }
}
(this is obviously incoorect, but what I am trying to achieve)

How can I create a deleter to pass to a member of a class that is a unique_ptr that includes 2 arguments (in this case the necessary context pointer)? Is there a way for me to make unique_ptr aware of the context pointer to delete the (in this example) page? Or (one thought I had) do I need to create something that wraps the unique_ptr so I can hand it the context for deletion later somehow (haven't fully thought it through yet).

I have seen the examples here: How do I use a custom deleter with a std::unique_ptr member?

and

Wrapping of C-code with a unique_ptr and custom deleter

but I can't figure out how to make them work in my case.

Top-level or low-level constness or neither?

I'm working through the C++ Primer and if I understand it correctly:

  • Top-level constness applies to the object itself.
  • Low-level constness means that the the referenced object is const which makes the referenced object top-level const.
// A plain int.
int i {0};

// Top-level const ints.
const int ci {42};
const int ci2 {0};

// A low-level pointer to const int.
const int * pci {&ci};

// Low-level, because the referenced object can't be changed.
*pci = 0; // error

// But not top-level, because it can be changed to point to another object.
pci = &ci2; // fine

// This is both top-level and low-level const
// because both the pointer and the object it
// points to are const:
const int * const cpci {&ci};
*cpci = 0;   // error
cpci = &ci2; // error

Now the question. Is there a naming convention for a constness which is neither top-level nor low-level? I.e. the pointer itself is not const but it points in a constant way to a non-const object? Or is this a special case of low-level constness? Example:

int i {0];
int j {42};

// The following pointer is not const itself.
// The object it's pointing to is not const but
// it can't be manipulated through the pointer.
const int * pci {&i};
*pci = 42; // error

// All these are fine:
++i;
pci = &j;
++j;

*pci = 42; // error as above

Remove duplicates vector from vector of vector

I am trying to implement the solution to the problem found at Link.

Here is my snippet of code

bool compareVec(vector<int> a, vector<int> b) {
    return std::equal(a.begin(), a.end(), b.begin());
}
vector<vector<int> > ans;
ans.erase(std::remove_if(ans.begin(), ans.end(), compareVec), ans.end());

I am getting the following errors

/usr/include/c++/4.8/bits/stl_algo.h: In instantiation of 
'_RandomAccessIterator std::__find_if(_RandomAccessIterator, 
_RandomAccessIterator, _Predicate, std::random_access_iterator_tag) [with 
_RandomAccessIterator = __gnu_cxx::__normal_iterator<std::vector<int>*, 
std::vector<std::vector<int> > >; _Predicate = bool (*)(std::vector<int>, 
std::vector<int>)]':

/usr/include/c++/4.8/bits/stl_algo.h:4465:41:   required from '_IIter   
std::find_if(_IIter, _IIter, _Predicate) [with _IIter = 
__gnu_cxx::__normal_iterator<std::vector<int>*, std::vector<std::vector<int>
 > >; _Predicate = bool (*)(std::vector<int>, std::vector<int>)]'

/usr/include/c++/4.8/bits/stl_algo.h:1144:64:   required from '_FIter 
std::remove_if(_FIter, _FIter, _Predicate) [with _FIter = 
__gnu_cxx::__normal_iterator<std::vector<int>*, std::vector<std::vector<int> 
> >; _Predicate = bool (*)(std::vector<int>, std::vector<int>)]'

solution.cpp:40:64:   required from here
/usr/include/c++/4.8/bits/stl_algo.h:214:23: error: too few arguments to    
function
if (__pred(*__first))
                   ^
/usr/include/c++/4.8/bits/stl_algo.h:218:23: error: too few arguments to   
function
if (__pred(*__first))
                   ^
/usr/include/c++/4.8/bits/stl_algo.h:222:23: error: too few arguments to 
function
if (__pred(*__first))
                   ^

Can anyone help me out in debugging this? Thanks in advance

EDIT

The elements of vector are sorted and all these vectors are also sorted.

Unique also gives an error. I am unable to figure out why?

Why is the example given in the link I provided, not helpful here?

Inherit Singleton

Quick question. Is there anyway to inherit a singleton so that the child class is a singleton? I have searched around but every singleton I can find is implemented per class, and not in a generic fashion.

std::to_string not a member in C++11 using CygWin

I have the following code...

// My.h
#include <string>
....

// My.cpp
#include "My.h"
...
errMsg = "X value [too low]: " + std::to_string(xInVal);

But when I compile like...

//setup.py
extra_compile_args =['-std=c++11']

//console output
gcc -Wno-unused-result -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -ggdb -O2 -pipe -Wimplicit-function-declaration -fdebug-prefix-map=/usr/src/ports/python3/python3-3.4.3-1.x86_64/build=/usr/src/debug/python3-3.4.3-1 -fdebug-prefix-map=/usr/src/ports/python3/python3-3.4.3-1.x86_64/src/Python-3.4.3=/usr/src/debug/python3-3.4.3-1 -I./My -c ./My.cpp -o build/temp.cygwin-2.2.1-x86_64-3.4/./My.o -std=c++11

I get the following error....

 error: ‘to_string’ is not a member of ‘std’
   errMsg = "X value [too low]: " + std::to_string(xInVal);

What am I missing how do I use to_string in this way?

_GLIBCXX_USE_C99 is not defined, to_wstring not available

I've run into a very serious (IMO) problem. I am using the native cross platform tools in visual studio 2015.

Since several implementations of the standard library were downloaded by visual studio

C:\ProgramData\Microsoft\AndroidNDK\android-ndk-r10e\sources\cxx-stl\

I was surprised when I started finding stl classes that were not compiling.

I wrote off std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> not being available as a quirk of gnu-libstdc++.

I tried to set the stl to others to see if they were better. This was done in the visual studio project properties window.

enter image description here

No combination of toolset or STL made std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> available.

I moved on, saying "If I have to implement that one function myself it's not the end of the world."

However shortly afterward I tried to use to_wstring. Again the function was not recognized even though wstring was.

This was a step too far so I checked to see if gnu-libstdc++ had in fact implemented anything at all. In fact they had, see 21.5 of the standard is Y.

I was very confused now. I did some googling and found nothing more substantial than "set it to c++ 11."

Unless Visual Studio isn't doing anything with the following setting I assume GCC is being called correctly.

enter image description here

Eventually I opened up basic_string.h in visual studio to make sure that the function was actually there.

It was, line 3000:

inline wstring
to_wstring(int __val)
{ return __gnu_cxx::__to_xstring<wstring>(&std::vswprintf, 4 * sizeof(int), L"%d", __val); }

Then I saw by the shading that it was being omitted by the preprocessor. Behold line 2847:

#if ((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \
     && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF))

The problem was not __cplusplus nor _GLIBCXX_HAVE_BROKEN_VSWPRINTF. _GLIBCXX_USE_C99 was not defined.

Searching for this problem yielded a couple of stack overflow questions.

Most of the comments seemed to think the problem would be fixed with a new release of GCC. For instance GCC 4.4.5. However since visual studio downloaded 4.9... I don't think this is merely a problem with versions.

I followed the link there to a three year old bug report which contained the statement:

It's not possible to fix in GCC without extraordinary effort for a single target, which is not going to happen. If a given target wants to support C++11 features then it needs to provide the necessary C99 features. This is not a GCC issue.

Well, in visual studio I had set the C standard to C99, for the record C11 didn't make any difference.

I am really not sure how to proceed from here. It seems to me that somehow Visual Studio is not communicating to GCC what is or is not available. That is just a theory though.

I am opposed to trying to manually change a distribution on the stl. That defeats the purpose of a stl. At the same time this project I am undertaking may well be impossible without the standard library (given the time constraints). I am afraid to continue lest I find more critical functionality hidden due to lack of C library functions.

I have this insane hope that there is something I could change in visual studio, some setting or command line override that would fix this.

P.S. I have looked into developing the android part in eclipse or android studio. The NDK documentation mentions eclipse often, but the android SDK has scary messages about the ADT no longer being supported. On top of that I had issues out of the box debugging the native code (but those are beyond the scope). The android studio build system (gradle) doesn't seem friendly to custom folder structures in the least. All of our source is in TFS and I can't change that at this point.

Passing std::string as parameter gives error - htons function

I'm working with sockets, but when I compile my program I get some errors.

This is my code:

address.sin_family = AF_INET;
address.sin_port = htons(string); // here I get an error
inet_aton(str.c_str(),&address.sin_addr);

What I get is:

cannot convert ‘__gnu_cxx::__alloc_traits > >::value_type {aka std::__cxx11::basic_string}’ to ‘uint16_t {aka short unsigned int}’ for argument ‘1’ to ‘uint16_t htons(uint16_t)’

How can I solve this error?

Thanks in advance.

Conversion from int to nullptr

Consider following code:

void f( void * );

int main()
{
    f( 0 );               // compiles fine
    f( 1 - 1 );           // compiles fine
    constexpr int i = 0;
    f( i );               // fails to compile, cannot convert int to void *
    f( i - 0 );           // compiles fine
}

why f( i ) fails to compile, though i should be evaluated as compile time constant with value 0?

PS checked with g++ v 5.1.0

Implementation of Naive Bayes for text classification in C++

I am writing a code for implementing Naive Bayes classifier for text classification. I have worked a very small example, please refer page 44, it seems to be working.

  1. But I want know whether the implementation is correct, whether it will work for other training and testing sets? I am not trying to implement a commercial level Naive Bayes, just a small assignment, to learn some C++.
  2. I want to know how the code is? Like the way I wrote the code is it a good C++ practice?
  3. I know there lot of improvements which can be done, like for example at present I am testing only one test file, so a way to test multiple files is something that I am thinking of doing in the future, also at present I am doing only 2 class classification, in the future maybe multi class classification. But anything other improvement code wise?

Here is the code, NB header file:

#pragma once

#include<iostream>
#include<fstream>
#include<string>
#include<vector>
#include<map>
using namespace std;

class NB
{
public:
    NB(NB& cl1, NB& cl2, string className);
    NB(string className);
    NB(string className, int classType);
    vector <string> combineClassText();
    void bagOfWords(string classCombine, bool isTotal = false);
    void calcProb(NB& total);
    float totalProb(NB& prob, NB& total);
    int classType;

private:
    int _len = 0;
    float _prob = 1.0f;
    int _voc = 0;
    int _nOfClass = 0;
    int _tnClass = 0;
    int _totalWordsinC = 0;
    int _wordCounter = 0;
    bool _isDone = false;
    ifstream _in;
    ofstream _out;
    //string _classCombine;
    string _className;
    string _fileName;
    vector <string> _combined;
    map<string, string> _category;
    map<string, int> _bow;
    map<string, float> _probCalc;
};

The NB.cpp file:

#include "NB.h"
#include<cmath>

NB::NB(NB& cl1, NB& cl2, string className)
{
    _className = className;
    _out.open("combineAll.txt");
    if (_out.fail()) {
        perror("cannot write to combineAll.txt");
    }
    _len = cl1.combineClassText().size();
    for (int i = 0; i < _len; i++) {
        _combined.push_back(cl1.combineClassText()[i]);
    }

    _len = cl2.combineClassText().size();
    for (int i = 0; i < _len; i++) {
        _combined.push_back(cl2.combineClassText()[i]);
    }

    _len = _combined.size();
    for (int i = 0; i < _len; i++) {
        _out << _combined[i] << endl;
        //cout << i + 1 << ". " << _combined[i] << endl;
    }
    _out.close();
    _tnClass = cl1._tnClass + cl2._tnClass;
    bagOfWords("combineAll.txt", true);
}

NB::NB(string className, int classType) {
    NB::classType = classType;
    _className = className;
    cout << "Enter a filename for " + _className << endl;
    cin >> _fileName;
    _category[_fileName] = _className;
    combineClassText();
    bagOfWords(_className + ".txt");
}

NB::NB(string className)
{
    _className = className;
    while (_isDone == false) {
        cout << "Enter a filename for " + _className << endl;
        cin >> _fileName;
        if (_fileName != "q") {
            _category[_fileName] = _className;
            _nOfClass++;
            _tnClass++;
        } else {
            _isDone = true;
        }
    }
    combineClassText();
    bagOfWords(_className + ".txt");
}

vector<string> NB::combineClassText() {

    string temp;
    string classCombine = _className + ".txt";
    vector <string> tmp;
    map<string, string>::iterator it;

    _out.open(classCombine);
    if (_out.fail()) {
        perror("cannot write to");
    }
    for (it = _category.begin(); it != _category.end(); it++) {
        _in.open(it->first);
        if (_in.fail()) {
            perror("cannot read from");
        }
        while (_in >> temp) {
            _out << temp << endl;
            tmp.push_back(temp);            
        }
        _in.close();
    }
    _out.close();
    return tmp;
}

void NB::bagOfWords(string classCombine, bool isTotal) {

    map<string, int>::iterator it;
    string temp;
    vector<string> tp;
    string name = _className + "_bow.txt";
    int len;

    _in.open(classCombine);
    if (_in.fail()) {
        perror("cannot read from");
    }

    _out.open(name);
    if (_out.fail()) {
        perror("cannot write to");
    }

    while (_in >> temp) {
        tp.push_back(temp);
    }

    for (int i = 0; i < tp.size(); i++) {
        for (int j = 0; j < tp[i].size(); j++) {
            if (tp[i][j] == '.' || tp[i][j] == ',') {
                tp[i][j] = ' ';
            }
        }
    }

    len = tp.size();
    vector<int> count(len, 1);

    for (int i = 0; i < len; i++) {
        for (int j = 0; j < (len - i - 1); j++) {
            if (tp[i] == tp[j + i + 1]) {
                count[i]++;
            }
        }
    }

    for (int i = len - 1; i >= 0; i--) {
        _bow[tp[i]] = count[i];
    }

    for (it = _bow.begin(); it != _bow.end(); it++) {
        _out << it->first << ": " << it->second << endl;
        //cout << it->first << ": " << it->second << endl;
    }
    //cout << endl;

    if (isTotal == true) {
        for (it = _bow.begin(); it != _bow.end(); it++) {
            _voc += 1;
            //cout << _voc << endl;
        }
    } else {
        for (it = _bow.begin(); it != _bow.end(); it++) {
            _totalWordsinC += it->second;
        }
        //cout << _totalWordsinC << endl;
    }
    _in.close();
    _out.close();
}

void NB::calcProb(NB& total) {

    map<string, int> ::iterator it;
    map<string, int> ::iterator it2;
    map<string, float> ::iterator it3;

        _out.open(_className + "_prob.txt");
        if (_out.fail()) {
            perror("cannot write to");
        }
        for (it = total._bow.begin(); it != total._bow.end(); it++) {
            for (it2 = _bow.begin(); it2 != _bow.end(); it2++) {
                if (it->first == it2->first) {
                    _probCalc[it->first] = (float)((it2->second) + 1) / (_totalWordsinC + total._voc);
                    break;
                } else {
                    _probCalc[it->first] = (float)(1) / (_totalWordsinC + total._voc);
                }
            }
        }

        for (it3 = _probCalc.begin(); it3 != _probCalc.end(); it3++) {
            //cout << it3->first << ": " << it3->second << endl;
            _out << it3->first << ": " << it3->second << endl;
        }
        _out.close();
    }

float NB::totalProb(NB& prob, NB& total) {

    map<string, int> ::iterator it;
    map<string, int> ::iterator it2;
    map<string, float> ::iterator it3;

    _out.open(_className + "_" + prob._className + "_prob.txt");
    if (_out.fail()) {
        perror("cannot write to");
    }
    _prob = 1.0f;
    for (it = _bow.begin(); it != _bow.end(); it++) {
        for (it3 = prob._probCalc.begin(); it3 != prob._probCalc.end(); it3++) {
            if (it->first == it3->first) {
                _wordCounter = 0;
                _prob = (_prob * pow((it3->second), (it->second)));
                break;
            } else {
                _wordCounter++;
                if (_wordCounter == prob._probCalc.size()) {
                    _prob = _prob * ((float)1 / (prob._totalWordsinC + total._voc));
                }
            }
        }
    }
    _prob = (_prob * ((float)(prob._nOfClass) / total._tnClass));
    cout << _prob << endl;
    _out << "The probalility of the " << _className << " beloning to " << prob._className << " is: " << _prob << endl;
    _out.close();
    return _prob;
}

and finally main.cpp:

#include<iostream>
#include<vector>
#include"NB.h"

using namespace std;

int main() {

    NB class1("class1");
    NB class2("class2");
    NB total(class1, class2, "all_combined");

    class1.calcProb(total);
    class2.calcProb(total);

    int nOfTestDocs = 0;
    int corrClass = 0;
    float accurancy = 0.0f;
    cout << "Enter the number of test documents\n";
    cin >> nOfTestDocs;

    NB test("test", 1);
    if (test.totalProb(class1, total) >= test.totalProb(class2, total)) {
        cout << "The test data belongs to class 1\n";
        if (test.classType == 1) {
            corrClass++;
            accurancy = (float)corrClass / nOfTestDocs;
            cout << "The accurancy is: " << accurancy << endl;
        }
    }
    else {
        cout << "The test data belongs to class 2\n";
        if (test.classType == 1) {
            corrClass++;
            accurancy = (float)corrClass / nOfTestDocs;
            cout << "The accurancy is: " << accurancy << endl;
        }
    }
    system("PAUSE");
    return 0;
}

Is std::swap guaranteed to find nonmember swap by ADL?

A textbook by Torsten T. Will on C++11 says that since C++11, std::swap will use a nonmember swap found by ADL if such a nonmember function is defined, thus the pattern

using std::swap;
swap (obj1, obj2);

can always be replaced by a simple

std::swap (obj1, obj2);

Unfortunately, I did not find such a statement anywhere else.

What is the truth?

why type deduction failed 0 to shared_ptr and NULL to unique_ptr?

#include<iostream>
#include <memory>
#include <thread>
#include <mutex>
using namespace std;
class Linux
{
};
int f1(std::shared_ptr<Linux> spw) // call these only when
{
  //do something
  return 0;
}
double f2(std::unique_ptr<Linux> upw) // the appropriate
{
  //do something
  return 0.0;
}
bool f3(Linux* pw) // mutex is locked
{

return 0;
}

std::mutex f1m, f2m, f3m; // mutexes for f1, f2, and f3
using MuxtexGuard = std::lock_guard<std::mutex>;

void lockAndCallF1()
{
        MuxtexGuard g(f1m); // lock mutex for f1
        auto result = f1(static_cast<int>(0)); // pass 0 as null ptr to f1
        cout<< result<<endl;
}

void lockAndCallF2()
{
        MuxtexGuard g(f2m); // lock mutex for f2
        auto result = f2(static_cast<int>(NULL)); // pass NULL as null ptr to f2
        cout<< result<<endl;
}

void lockAndCallF3()
{
        MuxtexGuard g(f3m); // lock mutex for f2
        auto result = f3(nullptr);// pass nullptr as null ptr to f3 
        cout<< result<<endl;
} // unlock mutex
template<typename FuncType, typename MuxType, typename PtrType>
auto lockAndCall(FuncType func, MuxType& mutex, PtrType ptr) -> decltype(func(ptr))
//decltype(auto) lockAndCall(FuncType func, MuxType& mutex, PtrType ptr)
{
        MuxtexGuard g(mutex);
        return func(ptr);
}
int main()
{
        lockAndCallF1();
        lockAndCallF2();
        lockAndCallF3();
        auto result1 = lockAndCall(f1, f1m, 0); //error - compilation failed
        auto result2 = lockAndCallF2(f2, f2m, NULL); //error  compilation failed
        auto result3 = lockAndCall(f3, f3m, nullptr);
        return 0;
}

compilation failed of above program failed

c++$ g++ nullptr.cpp  --std=c++11
nullptr.cpp: In function ‘int main()’:
nullptr.cpp:60:46: error: no matching function for call to ‘lockAndCall(int (&)(std::shared_ptr<Linux>), std::mutex&, int)’
         auto result1 = lockAndCall(f1, f1m, 0); //error
                                              ^
nullptr.cpp:60:46: note: candidate is:
nullptr.cpp:49:6: note: template<class FuncType, class MuxType, class PtrType> decltype (func(ptr)) lockAndCall(FuncType, MuxType&, PtrType)
 auto lockAndCall(FuncType func, MuxType& mutex, PtrType ptr) -> decltype(func(ptr))
      ^
nullptr.cpp:49:6: note:   template argument deduction/substitution failed:
nullptr.cpp: In substitution of ‘template<class FuncType, class MuxType, class PtrType> decltype (func(ptr)) lockAndCall(FuncType, MuxType&, PtrType) [with FuncType = int (*)(std::shared_ptr<Linux>); MuxType = std::mutex; PtrType = int]’:
nullptr.cpp:60:46:   required from here
nullptr.cpp:49:82: error: could not convert ‘ptr’ from ‘int’ to ‘std::shared_ptr<Linux>’
 auto lockAndCall(FuncType func, MuxType& mutex, PtrType ptr) -> decltype(func(ptr))
                                                                                  ^
nullptr.cpp:61:51: error: too many arguments to function ‘void lockAndCallF2()’
         auto result2 = lockAndCallF2(f2, f2m, NULL); //error 
                                                   ^
nullptr.cpp:35:6: note: declared here
 void lockAndCallF2()
      ^
nullptr.cpp:61:51: error: ‘void result2’ has incomplete type
         auto result2 = lockAndCallF2(f2, f2m, NULL); //error 

Question1. Why lockAndCall call is failed for 0 and Null and succeed for f1(static_cast<int>(0)); and auto result = f2(static_cast<int>(NULL));? Question2. I know it is deducted as int and i passing integer literal but i am typecasting to integer then even why it is failed?

How to call a method based on a specific derived class

I was trying to understand how the weak pointer member (using the visual studio 2013 C++ compiler)

mutable weak_ptr<_Ty> _Wptr

from the template class enable_shared_from_this was initialized when a std::shared_ptr<_Ty> was created out of an object that derived from it. For this purpose I traced the code from a simple code that created a std::shared_ptr<_Ty> with the template function std::make_share<_Ty>

I found that the initialization of _Wptr proceeded when the compiler called the method _Enable_shared within the base class _Ref_count_del_alloc.

Now 2 template methods were defined for this purpose. One method is defined when the _Ty class is derived from enable_shared_from_this. This is the method:

template<class _Ty>
inline void _Enable_shared(_Ty *_Ptr, _Ref_count_base *_Refptr,
    typename _Ty::_EStype * = 0)
{   // reset internal weak pointer
if (_Ptr)
    _Do_enable(_Ptr,
        (enable_shared_from_this<typename _Ty::_EStype>*)_Ptr, _Refptr);
}

The second method is defined when the _Ty class is not derived from enable_shared_from_this. This is the method:

inline void _Enable_shared(const volatile void *, const volatile void *)
{   
    // not derived from enable_shared_from_this; do nothing
}

The question I have is how the C++ compiler is able to resolve which method to use? Beside I would have expected both methods to be instantiated at compile time and have a compile error if the class is not derived from enable_shared_from_this. Yet the compiler seems to select only one method to instantiate and the appropriate method.

Simplest method to check whether unordered_map of unordered_maps contains key

I am using an unordered_map of unordered_maps, such that I can reference an element using the "ulti key" syntax:

my_map[k1][k2].

Is there a convenient way to use the same "multi-key" syntax to check whether an element exists before trying to access it? If not, what is the simplest way?

Is this resource leak provided by possible evaluation order or Scott Meyers is wrong?

I am reading about std::shared_ptr in the Effective Modern C++14 book by Scott Meyers. Here is a code in which the author says a potentital resource leak can be:

int computePriority(); // this function always throw an exception
// ...
processWidget(std::shared_ptr<Widget>(new Widget), // (S.M): potentital
              computePriority());                  // resource
                                                   // leak

Scott Meyers says that computePriority() function may be called between new Widget and std::shared_ptr<Widget>(expr) expressions are evaluated what will lead to a memory leak caused by new. Should not be there a one sequence point that can guarantee if the new Widget expression is evaluated then std::shared_ptr<Widget>(expr) will be evaluated next? I think about this because It would be correct in my opinion: sequence point is in std::shared_ptr<Widget>(expr) will evaluate all of it's arguments(sub expressions) without sequencing and will make shared pointer be ready, then do something else (evalute other arguments without sequencing). Just if this is untrue and Scott Meyers is right (I still believe him, obviously) , would not be this behavior incorrect?

Is there a rule that explains why is this possible? I am not good at sequence points, but people who told me about them says this should be valid.

Changing max_load_factor() causing segfault in std::unordered_map

I have std::unordered_map which I have initialized with bucket size 100. When I change the max_load_factor, code is giving segfault while accessing the bucket_size(). I am using g++ as compiler on linux. I want to increase load factor so that elements collide.

1> Why I am getting segfault? 2> What is correct way to set max_load_factor for unordered_map? as far as I know constructor of std::unordered_map does not accept load factor as argument.

Code without setting max_load_factor, gives no problem

// unordered_map::bucket_size
#include <iostream>
#include <string>
#include <unordered_map>

using namespace std;

int main ()
{
  std::unordered_map<int, std::string> mymap(10);
  unsigned nbuckets = mymap.bucket_count();
  std::cout << "mymap has " << nbuckets << " buckets:\n";
  std::cout << "mymap load factor " << mymap.max_load_factor() << endl;

  for (unsigned i=0; i<nbuckets; ++i) {
    std::cout << "bucket #" << i << " has " << mymap.bucket_size(i) << " elements.\n";
  }
  return 0;
}

Output

mymap has 11 buckets:
mymap load factor 1
bucket #0 has 0 elements.
bucket #1 has 0 elements.
bucket #2 has 0 elements.
bucket #3 has 0 elements.
bucket #4 has 0 elements.
bucket #5 has 0 elements.
bucket #6 has 0 elements.
bucket #7 has 0 elements.
bucket #8 has 0 elements.
bucket #9 has 0 elements.
bucket #10 has 0 elements.

Now once I introduce the code to change the max_load_factor, I get segfault.

#include <iostream>
#include <string>
#include <unordered_map>

using namespace std;

int main ()
{
  std::unordered_map<int, std::string> mymap(10);
  unsigned nbuckets = mymap.bucket_count();
  std::cout << "mymap has " << nbuckets << " buckets:\n";
  mymap.max_load_factor(10);
  std::cout << "mymap load factor " << mymap.max_load_factor() << endl;

  for (unsigned i=0; i<nbuckets; ++i) {
    std::cout << "bucket #" << i << " has " << mymap.bucket_size(i) << " elements.\n";
  }
  return 0;
}

Output

mymap has 11 buckets:
mymap load factor 10
bucket #0 has 0 elements.
bucket #1 has 0 elements.
bucket #2 has 0 elements.
Segmentation fault

Override a pointer attribute with a static array

typedef struct chlnglck{
    friend struct chlnglck_8;
    friend struct chlnglck_10;
    friend struct chlnglck_12;

    chlng nb;
    uint64_t wt;
}chlnglck;

struct chlnglck_8 : chlnglck{
    char ress[255];
    chlnglck();
};

struct chlnglck_10 : chlnglck{
    char ress[1024];
    chlnglck();
};

Here is my code. I would want to know how I could mention the ress attribute in the parent class chlnglck.

Is there a way or not knowing I have to use fixed size array in the child classes?

No std::string please.

OpenCV3, SIFT compute with vector

According to the document, SIFT object could use the function below to compute descriptors for multiple images:

virtual void compute (InputArrayOfArrays images, std::vector< std::vector< KeyPoint > > &keypoints, OutputArrayOfArrays descriptors)

I'm trying to compute the SIFT descriptors for multiple images with the code below:

Ptr<Feature2D> f2d = xfeatures2d::SIFT::create();
vector<vector<KeyPoint>> train_keypoints;
f2d->detect(train_imgs, train_keypoints);

vector<Mat> train_descriptors;
f2d->compute(train_imgs, train_keypoints, train_descriptors);

It could be compiled under Mac OS 10.10.5 with opencv3, while it might terminate during execution with error:

libc++abi.dylib: terminating with uncaught exception of type std::length_error: vector

Or I could change the type of train_descriptors into Mat (instead of vector< Mat >), it'll still fail during execution with another error:

OpenCV Error: Assertion failed (_descriptors.kind() == _InputArray::STD_VECTOR_MAT) in compute, file /tmp/opencv320151228-32931-2p5ggk/opencv-3.1.0/modules/features2d/src/feature2d.cpp, line 126 libc++abi.dylib: terminating with uncaught exception of type cv::Exception: /tmp/opencv320151228-32931-2p5ggk/opencv-3.1.0/modules/features2d/src/feature2d.cpp:126: error: (-215) _descriptors.kind() == _InputArray::STD_VECTOR_MAT in function compute

What type of train_descriptors should I use to make this code compile and run correctly?

select() system call and bash escaping

When I compile and run the following code with the command g++ -std=c++11 <filename> and run with ./a.out and enter in some text to see what the select call will return (it should return 1 because when I enter text, text is then available to be read in). Somehow the text I enter escapes as a bash command itself. Could someone explain why this happens?

#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/time.h>
int input_timeout (int filedes, unsigned int seconds) {

  fd_set set;
  struct timeval timeout;

  // Initialize the file descriptor set.
  FD_ZERO (&set);
  FD_SET (filedes, &set);

  // Initialize the timeout data structure.
  timeout.tv_sec = seconds;
  timeout.tv_usec = 0;

  // select returns 0 if timeout, 1 if input available, -1 if error. 
  return select (FD_SETSIZE,
                 &set, NULL, NULL,
                 &timeout);
}
int main () {

  fprintf (stderr, "select returned %d.\n", input_timeout (STDIN_FILENO, 1));

  return 0;
}

So an example of what I said above is in the output below

bash-3.2 $ ./a.out 
what
select returned 1.
bash-3.2$ what

and then waits indefinitely for the input to the what command

How to install man pages for C++11

I know the man pages for C++ are installed with libstdc++6-<version>-doc, but when I'm looking for a function like stoull there is no man page. Even apropos does not find anything.

Man pages are available online: http://ift.tt/1OW7Fph or http://ift.tt/1niiRp1 but I would like to have them offline.

Is there a way to install the man pages under GNU/Linux?

--Corbie

lundi 28 décembre 2015

std::atomic

Can I use std::atomic<uint64_t> instead of sig_atomic_t in handler code?

My original code is below and i would like to upgrade 32 bit sig_atomic_t counter in order to handle periods longer than 596 hours of millisecond precision.

static sig_atomic_t ms_long_counter;

static void MonotonicMsHandler(int sig, siginfo_t *si, void *uc) {
  ms_long_counter += (1 + si->si_overrun);
}


///... Setup
struct sigaction sa;
sa.sa_flags = SA_RESTART | SA_SIGINFO;

sa.sa_sigaction = &MonotonicMsHandler;
sigemptyset(&sa.sa_mask);
sigaction(SIGRTMIN, &sa, NULL);

struct sigevent sev;
sev.sigev_notify = SIGEV_SIGNAL;
sev.sigev_signo = SIGRTMIN;

timer_create(CLOCK_MONOTONIC, &sev, &millis_timer);

struct itimerspec its;
its.it_value.tv_sec = 0;
its.it_value.tv_nsec = 1000000;  // The first expiration in 1ms.   
its.it_interval.tv_sec = its.it_value.tv_sec;
its.it_interval.tv_nsec = its.it_value.tv_nsec;    
timer_settime(millis_timer, 0, &its, NULL);

using typedef in template instantiation and extern template declaration

There are two cases where typedef confuses me when it comes to extern template declaration and explicit template instantiation.

To illustrate the two see below 2 example code snippets.

Consider following example (Case 1):

// suppose following code in some cpp file    
template <typename T>
    struct example
{
    T value;
};

// valid typedefs
typedef example<int> int_example;
typedef example<std::string> string_example;

// explicit instantiation using above typedefs
template class int_example; // -> compile time error
template class string_example; // -> compile time error

// instead we need to use type names
template class example<int>; // -> OK
template class example<std::string>; // -> OK

// QUESTION 1: Why does this work however? is this valid code?
typedef std::string type_string;
template class example<type_string>;

Why does the template class example<type_string> work with typedef ? and why is it valid while template class string_example is not?

Consider following example (Case 2):

// suppose following code is in some header file
template <typename T>
struct example
{
    T value;
};

// valid typedefs
typedef std::string type_string;
typedef example<type_string> string_example;

// Explicit instantiation declaration
// QUESTION 2: Is this valid code? if not why not?
extern template string_example; // -> at least this compiles, but is it OK?

As questioned in the comment above, is it valid to use typedef in extern template declaration, like in the example above, and why does this compile unlike the Case1 where it does not.

I've read about similar cases but none gives the detailed answer to above 2 questions. detailed elaboration is very much appreciated!

Initialization after deletion of constructor

My question is this: after deleting a constructor is there any way to initialize a class? For example

class A{
    public:
        A() = delete;
        int a = 42;
        int fun(){
            a += 1; 
            return a;
        }
};

Now it should not be possible to use this class. For example you cannot:

A* instance = (A*)malloc(sizeof(A));
a->fun(); //segfault

and

A instance; //compile error undefined function

Assuming for some strange reason you actually wanted to use the class with the constructor deleted is there a way that you could do it? That is without doing something like overriding the constructor.

I know this is a strange question, but I am interested in knowing if someone has a (perhaps obscure) way of doing this. Thanks!

error C2664 - cannot convert parameter 1 from 'initializer-list' to 'const QList

I downloaded some code and run it in VS2013+QT5.4, there is code like this:

parser.addOptions({
        { "nogui", QString("Using command line arguments, do not show GUI.") },
        { { "p", "path" }, QString("Path for job files or shape files."), QString("path") },
    });

and I got an error:

error C2664 - cannot convert parameter 1 from 'initializer-list' to 'const QList<QCommandLineOption> &'

It seems about a VS problem of C++11?...and I wonder how to fix it?

Could someone explain to me what exactly happens when you read a file?

How does it work when you use a while loop with the condition !fin.eof()? What if my loop contains a statement like fin.get(ch) where ch is of type char?

  • How exactly does the pointer move and when is it updated?
  • If at the beginning of the file, the pointer points to the 1st element. Does it move over to the second element in the first iteration itself?

Lambda type saying it doesn't have an operator()?

Getting the following error in the following code and I don't see why. Shouldn't the lambda have an operator() method? Basically I am trying to capture the return type of the lambda operator() and the args type and crate a new typedef that the MakeFoo will be returning by forwarding the lambda on to Foo's constructor and then returning the object. See below.

#include <functional>                                                                                 
#include <tuple>                                                                                      
#include <iostream>                                                                                   

template <typename T>                                                                                 
class Foo;                                                                                            

template <typename R, typename... Args>                                                               
struct Foo<R(Args...)> {                                                                              

   template <typename T>                                                                              
   Foo(T aT) {                                                                                        
   }                                                                                                  
};                                                                                                    

template <typename LambdaT>                                                                           
struct function_traits                                                                                
   : public function_traits<decltype(&LambdaT::operator())> {};                                       

template <typename ClassType, typename ReturnType, typename... Args>                                  
struct function_traits<ReturnType (ClassType::*)(Args...) const> {                                    
   using FooType = Foo<ReturnType(Args...)>;                                                          
};                                                                                                    

template <typename ClassType, typename ReturnType, typename... Args>                                  
struct function_traits<ReturnType (ClassType::*)(Args...)> {                                          
   using FooType = Foo<ReturnType(Args...)>;                                                          
};                                                                                                    

template <typename ReturnType, typename... Args>                                                      
struct function_traits<ReturnType (*)(Args...)> {                                                     
   using FooType = Foo<ReturnType(Args...)>;                                                          
};                                                                                                    

template <typename T>                                                                                 
auto MakeFoo(T&& lambda) ->                                                                           
   typename function_traits<decltype(lambda)>::FooType {                                              
   return function_traits<decltype(lambda)>::FooType(std::forward<T>(lambda));                        
}                                                                                                     

// test code below:                                                                                   
int main() {                                                                                          
   int z = 001;                                                                                       
   auto lambda = [z](int x) { std::cout << " test " << std::endl; };                                  

   using traits = function_traits<decltype(lambda)>;                                                  

   auto f = MakeFoo(lambda);                                                                          

   return 0;                                                                                          
}    





g++ -g3  -std=c++14 -pedantic -Werror -Wno-invalid-offsetof -fno-omit-frame-pointer -march=ivybridge -mtune=ivybridge -mno-avx2 -mavx -fl
o -ffat-lto-objects -fuse-linker-plugin -fno-strict-aliasing -c main.cpp                                                                 
main.cpp: In instantiation of ‘struct function_traits<main()::<lambda(int)>&>’:                                                          
main.cpp:36:6:   required by substitution of ‘template<class T> typename function_traits<decltype (lambda)>::FooType MakeFoo(T&&) [with T
= main()::<lambda(int)>&]’                                                                                                               
main.cpp:48:27:   required from here                                                                                                     
main.cpp:18:38: error: ‘operator()’ is not a member of ‘main()::<lambda(int)>&’                                                          
    : public function_traits<decltype(&LambdaT::operator())> {};                                                                         
                                      ^