mercredi 31 janvier 2018

Inherent support for dynamic Reflection in C++ (without boost)

Like Java is having an Object class and MFC is having CObject class, is C++ latest versions (11,14 etc) having any concept of dynamic reflection ?

If yes, please share any details.

Note: I am not looking for boost libraries but something from std only.

How to get the matrix from the text file in c++?

Projection matrix are mentioned in a file calib.txt

ifstream fcalib = fopen("/home/chaiein/chai_vr_th/calib.txt"); . . .

calib.txt has the following

P0: 7.188560000000e+02 0.000000000000e+00 6.071928000000e+02 0.000000000000e+00 0.000000000000e+00 7.188560000000e+02 1.852157000000e+02 0.000000000000e+00 0.000000000000e+00 0.000000000000e+00 1.000000000000e+00 0.000000000000e+00 P1: 7.188560000000e+02 0.000000000000e+00 6.071928000000e+02 -3.861448000000e+02 0.000000000000e+00 7.188560000000e+02 1.852157000000e+02 0.000000000000e+00 0.000000000000e+00 0.000000000000e+00 1.000000000000e+00 0.000000000000e+00 P2: 7.188560000000e+02 0.000000000000e+00 6.071928000000e+02 4.538225000000e+01 0.000000000000e+00 7.188560000000e+02 1.852157000000e+02 -1.130887000000e-01 0.000000000000e+00 0.000000000000e+00 1.000000000000e+00 3.779761000000e-03 P3: 7.188560000000e+02 0.000000000000e+00 6.071928000000e+02 -3.372877000000e+02 0.000000000000e+00 7.188560000000e+02 1.852157000000e+02 2.369057000000e+00 0.000000000000e+00 0.000000000000e+00 1.000000000000e+00 4.915215000000e-03

How to extract as P0, P1, P3 separately in to a variable in a c++ opencv program?

decltype() variadic template base class

I have the following code where I'm expecting decltype() to not work on Derived class to get run() base class method return-type, since the base class does not have a default constructor.

class Base
{
  public:
    int run() { return 1; }

  protected:
    Base(int){}
}; 

struct Derived : Base
{
  template <typename ...Args>
  Derived(Args&... args) : Base{args...}
  {}
};

int main()
{
  decltype(Derived{}.run()) v {10}; // it works. Not expected since
                                    // Derived should not have default constructor
  std::cout << "value: " << v << std::endl;

  //decltype(Base{}.run()) v1 {10}; // does not work. Expected since 
                                    // Base does not have default constructor
  //std::cout << "value: " << v1 << std::endl;
}

I'm aware you can use declval<> to get member functions without going through constructors, but my question is why decltype works here. I tried to find in the C++ standard something relevant, but did not find anything. Also tried multiple compilers including clang and have the same behavior.

static const std::vector

Let's say I'd like to have a std::vector of unsigned chars. It's initialized with an initializer-list (this is C++11) and will never change. I'd like to avoid any heap allocation, even at startup time, and have the whole vector live in the data segment like const strings. Is that possible? I.e: static const vector<char> v{0x1, 0x2, 0x3, 0x0, 0x5}; (This is a somewhat academic question; I know it's not that hard to just use C arrays for this.)

Weird hang in generic multiple producers / consumers in C++11 (or above)

I wrote a "generic" multiple producer / consumer using C++11 (or higher) multithreading. The code (below) sort of works, but it hangs / crashes if too many producers / consumers threads are created.

The idea is to neatly separate the concerns: the MultiProducerConsumer object takes care of the protocols (thread maintenance, mutex, condvar) while the "user" injects the relevant functors doing the concrete work (producer, consumer, termination predicate) into the object.

Tested with VS 2017 and cygwin g++. The situation is worse on cygwin (why?). I cannot figure out what the problem is, and I could use a hint. Thanks in advance.

The header, multi_producer_consumer.hpp:

#pragma once
#include <algorithm>
#include <functional>
#include <iterator>
#include <thread>
#include <mutex>
#include <condition_variable>
//#include <cassert>

template<typename Container>
struct MultiProducerConsumer
{
    using Type = typename Container::value_type;
    using ModifierFct = std::function<void(Container&)>;
    using DoneFctr = std::function<bool(const Container&)>;

    MultiProducerConsumer(const Container& q, 
                          ModifierFct producer,
                          ModifierFct consumer,
                          DoneFctr donef,
                          size_t n_producers,
                          size_t n_consumers):
        m_queue(q),
        m_pf(producer),
        m_cf(consumer),
        m_producers(n_producers),
        m_consumers(n_consumers),
        m_done(donef),
        m_joined(false)
    {
        ///std::lock_guard<std::mutex> lk(m_mutex);//why? to prevent the producers to start before consumers are created. So what, if they do?

        for (auto i = 0; i < n_producers; ++i)
        {
            m_producers[i] = std::thread(std::mem_fn(&MultiProducerConsumer::produce), this, i);
        }

        for (int i = 0; i < n_consumers; ++i)
        {
            m_consumers[i] = std::thread(std::mem_fn(&MultiProducerConsumer::consume), this, i);
        }
    }

    virtual ~MultiProducerConsumer(void)
    {
        if (!m_joined)
            join();
    }

    virtual bool done(void) const
    {
        std::lock_guard<std::mutex> lk(m_mutex);
        return m_done(m_queue);
    }

    void join(void)
    {
        std::for_each(m_producers.begin(), m_producers.end(), std::mem_fn(&std::thread::join));
        std::for_each(m_consumers.begin(), m_consumers.end(), std::mem_fn(&std::thread::join));
        m_joined = true;
    }

protected:
    virtual void produce(size_t i)
    {
        while (!done())
        {
            std::lock_guard<std::mutex> lk(m_mutex);
            m_pf(m_queue);
            ///if (i == 0)//should only only one thread notify all the consumers...? nope
            m_condvar.notify_all();//notifies all...not one
        }
    }

    virtual void consume(size_t i)
    {
        while (!done())
        {
            std::unique_lock<std::mutex> lk(m_mutex);
            m_condvar.wait(lk, [this]() {
                return !m_queue.empty();
            });
            m_cf(m_queue);
        }
    }
private:
    Container m_queue;
    ModifierFct m_pf;
    ModifierFct m_cf;
    DoneFctr m_done;

    mutable std::mutex m_mutex;
    std::condition_variable m_condvar;

    std::vector<std::thread> m_producers;
    std::vector<std::thread> m_consumers;

    bool m_joined;
};

The tester, below, uses a queue of vectors that are being "produced" (simply moved from an "outside" queue, matrix, into the producer / consumer queue). The consumers "consume" the vectors by summing each of them and storing the sum into another "outside" container (sums). The whole process terminates when the first vector summing up to zero is encountered. Below is the code:

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <queue>
#include <numeric>
#include <iterator>
#include <cassert>

#include "multi_producer_consumer.hpp"

template<typename T>
using QVec = std::queue<std::vector<T>>;

template<typename T>
inline
T sum(const std::vector<T>& v)
{
    return std::accumulate(v.begin(), v.end(), 0);
}

template<typename T>
T from_string(std::string&& str)
{
    T ret;
    std::stringstream ss(str);
    ss >> ret;

    return ret;
}

int main(int argc, char* argv[])
{
    int n_p = 1;
    int n_c = 1;
    if (argc == 3)
    {
        n_p = from_string<int>(argv[1]);
        n_c = from_string<int>(argv[2]);
    }

    const unsigned long max_n_threads = std::thread::hardware_concurrency();
    std::cout << "max # threads: " << max_n_threads << "\n";
    std::cout << "n_producers: " << n_p << ", n_consumers: " << n_c << "\n";

    try {
        std::vector<int> vstart(1, 1);
        std::vector<int> vstop(1, 0);

        std::queue<std::vector<int>> matrix;
        matrix.push(vstart);
        matrix.push(std::vector<int>{ 1, 2, 3, 4, 5 });
        matrix.push(std::vector<int>{ 6, 7, 8, 9 });
        matrix.push(std::vector<int>{ 10, 11, 12, 13 });
        matrix.push(vstop);
        matrix.push(std::vector<int>{ 20, 21, 22, 23 });//testing: this shouldn't get processed: okay, it's not
        std::vector<long> sums;
        QVec<int> qqv;

        //multi-producer-consumer that feeds vector from a queue
        //to a consumer that sums them up, until sum is zero:
        //
        MultiProducerConsumer<QVec<int>> mpc(qqv, 
            [&matrix](QVec<int>& qv) { //producer function: move elements from matrix into qv
            if (!matrix.empty())
            {
                auto v = matrix.front();
                matrix.pop();
                qv.push(v);
            }
        },
            [&sums](QVec<int>& qv) {  //consumer function: pop from qv and sum up elements
            //if (!qv.empty())//this test is superfluous
            //{
                auto v = qv.front();
                qv.pop();
                sums.push_back(sum(v));
            //}
        },
            [](const QVec<int>& qv) { //done predicate: if nonempty top of queue sums up to 0: done; else not done;
            if (!qv.empty())
            {
                auto v = qv.front();
                return (sum(v) == 0);
            }
            return false;
        }, n_p, n_c);//1,1 => okay; 1,2 => okay; 2,2 => okay; 5,5 => okay on Win64; hangs on cygwin; 5,10 => it can hang

        //need main thread to block until producers/consumers are done,
        //so that matrix/sums are not destructed while 
        //producers/consumers are still trying to use them:
        //
        mpc.join();

        std::cout << "sums:\n";
        std::copy(std::begin(sums), std::end(sums), std::ostream_iterator<int>(std::cout, "\n"));
    }
    catch (std::exception& ex)
    {
        std::cerr << ex.what() << "\n";
        return 1;
    }
    catch (...)
    {
        std::cerr << "Unknown exception.\n";
        return 1;
    }

    std::cout << "Done!" << std::endl;
    return 0;
}

Something is wrong with it. Just cannot figure what.

Cmake parse parameters into code

Can I parse a parameter out of a configuration file in cmake and paste this as a parameter into the C++ code?

I need to dynamically set the template value N for std::array<T,N> that depends on some system properties?

N = (a - b) / c

Where all should be system parameters.

C++ 11 can you safely pass and access std::atomics by reference in different threads

I am wondering if you can pass a an atomic by reference to a thread and for the .load and .store operations still be thread safe. For instance:

#include <thread>
#include <atomic>
#include <cstdlib>

void addLoop(std::atomic_int& adder)
{
    int i = adder.load();
    std::srand(std::time(0));
    while(i < 200)
    {
        i = adder.load();
        i += (i + (std::rand() % i));
        adder.store(i);
    }
}

void subLoop (std::atomic_int& subber)
{
    int j = subber.load();
    std::srand(std::time(0));
    while(j < 200)
    {
        j = subber.load();
        j -= (j - (std::rand() % j));
        subber.store(j);
    }
}

int main()
{
    std::atomic_int dummyInt(1);
    std::thread add(addLoop, std::ref(dummyInt));
    std::thread sub(subLoop, std::ref(dummyInt));
    add.join();
    sub.join();
    return 0;
}

When the addLoop thread stores the new value into the atomic if subLoop were to access it using the load and store functions would it end up being an undefined state?

Is it possible to test whether a something is constexpr?

In C++11 and later, is it possible at compile-time for any given identifier to derive (without compile errors) a constexpr bool value, which is true if and only if that given identifier refers to a constexpr variable?

If not, why? If yes, how? Is it also possible to detect constexpr functions?

c++ compiler configuration

#include <iostream>
#include <algorithm>
#include <string>

int main()
{
std::string s = "This is an example";
std::cout << s << '\n';

s.erase(0, 5); // Erase "This "
std::cout << s << '\n';

s.erase(std::find(s.begin(), s.end(), ' ')); // Erase ' '
std::cout << s << '\n';

s.erase(s.find(' ')); // Trim from ' ' to the end of the string
std::cout << s << '\n';
}

Output:

This is an example

is an example

isan example

isan

i run this code on code::blocks and it didn't get the same results as it is on cppreferences.com it's like the function find and erase does not have the same parametres or i don't know what is the problem my compiler version is cpp 5.1.0 if any one know how to fix this and get results as it is on the site, i'd greatfull if u tell me

How do I combine strings in an if/else statements in C++?

I'm a beginner learning C++, and I'm confused about where I've gone wrong here. So far I have what is below, but it's not recognizing the && operand for this. What would I use in place of &&?

What I'm suppose to be doing is writing a program that prompts the user to enter the names of two primary colors to mix. I'd appreciate any and all advice.

Thank you.

 #include <iostream>
    #include <string>
    #include <iomanip>

    using namespace std;

    int main()
    {
        //Declare string variables for colors to mix

        string color;
        string color2;
        string red;
        string yellow;
        string blue; 

        //Output instructions for creating secondary color
        cout<< " Enter first primary color to help create a secondary color.";
        cout<< " Must be in lowercase letters. "<<endl;

        cin>>color;

        cout<< "Enter another primary color to help create a secondary color: ";
        cout<< " Must be in lowercase letters. "<<endl;
        cin>>color2;


        //Create statements to help determine the results
        if (red && yellow)
        {cout<< " Your secondary color is Orange! ";

        }

        else if (red && blue) 
        {cout<< " Your secondary color is Purple! ";


        }

        else if (blue && yellow) 
        {cout<< " Your secondary color is Green! ";

        }

        else 
        {cout<< "Input is inaccurate. Please enter a different color. ";


        }


        return 0;
    }

Don't putting T in non-allocating new of an aligned_storage_t allocation and reinterpret_cast/deref T out of aligned_storage_t violate strict alias?

TL;DR

(1) Doesn't putting a T object in a non-allocating new of an aligned_storage_t allocation violate strict aliasing rules?

(2) Doesn't reinterpret_cast and deref T out of aligned_storage_t violate strict alias rules?


On the cppreference page of std::aligned_storage (here), there is an example code of static_vector containing a member which is an array of aligned_storage_t.

typename std::aligned_storage<sizeof(T), alignof(T)>::type data[N];

There is an emplace_back like this:

// Create an object in aligned storage
template<typename ...Args> void emplace_back(Args&&... args) 
{
    if( m_size >= N ) // possible error handling
        throw std::bad_alloc{};
    new(data+m_size) T(std::forward<Args>(args)...);
    ++m_size;
}

Doesn't putting T in a non-allocating new of an aligned_storage_t allocation violate the strict aliasing rules?

Then there is indexer like this:

// Access an object in aligned storage
const T& operator[](std::size_t pos) const 
{
    return *reinterpret_cast<const T*>(data+pos);
}

Doesn't aliasing T out of aligned_storage_t violate the strict aliasing rules? [basic.val]/11 -- N4713 page 82 § 8.2.1 ¶ 11

BOOST 1.66.0 + ANDROID NDK 1.6 CRASH WITH ASIO.HPP

Good night,

I am trying to use the boost with the Android Studio NDK 1.6b and the BOOST 1.66.0 I used this process to compile the boost:

https://sites.google.com/site/robdevelopertips/how-to-build-boost-1-64-0-for-android

and everything it's ok

I am linking my BOOST as static library like this:

target_link_libraries( # Specifies the target library. native-lib

                   # Links the target library to the log library
                   # included in the NDK.
                   ${log-lib} "/home/asilva/boost-android/arm/lib/libboost_system.a" "/home/asilva/android-openssl/jni/openssl/arch-armeabi/lib/libssl.a" "/home/asilva/android-openssl/jni/openssl/arch-armeabi/lib/libcrypto.a"
                   )

And they work with this teste :

https://github.com/trashoverride/AndroidRest/blob/master/app/src/main/cpp/teste.cpp

But when i put this header:

boost/asio.hpp

A error is generated:

In file included from /home/asilva/AndroidRest/app/src/main/cpp/teste.cpp:20: In file included from /home/asilva/Android/Sdk/ndk-bundle/sysroot/usr/include/boost/asio.hpp:131: In file included from /home/asilva/Android/Sdk/ndk-bundle/sysroot/usr/include/boost/asio/use_future.hpp:156: /home/asilva/Android/Sdk/ndk-bundle/sysroot/usr/include/boost/asio/impl/use_future.hpp:49:26: error: no member named 'current_exception' in namespace 'std' p.set_exception(std::current_exception());

I am tried to change the libc like this :

https://developer.android.com/ndk/guides/cpp-support.html

But Doesn't work.

Someone have some clue ?

Kind Regards,

Antonio Carlos

Why the move assignment of std::initializer_list was not blocked?

It is clear that std::initializer_list is not an actual container. The standard defines clearly what you can and cannot do with std::initializer_list.

But why does the language keep the option of doing foolish things, like assigning a temporary std::initializer_list into another - when it could have been easily blocked with =delete on std::initializer_list's move assignment operator?

Here is a broken code example, that compiles:

void foo(std::initializer_list<int> v) {
    std::cout << *v.begin() << std::endl;
}

int main() {
    int a = 1, b = 2, c = 3;
    auto val = {a, b, c}; // ok, extending the lifetime of {a, b, c}
    foo(val); // prints ok
    int i = 7;
    val = {i}; // doesn't handle well assignment of temporary
    foo(val); // prints garbage...
}

Eclipse CDT open declaration of auto type variable

With Eclipse CDT one can use "Open Declaration" to goto the declaration of a class, function, ... . This function can be accessed by the shortcut key F3.

If one hovers with the mouse over auto in code looking like this

const auto A = getA();

eclipse resolves the type of A. A popup displays the correct type. Nevertheless, one can not use F3 to goto the declaration of the type of A.

Can eclipse be configured to activate this?

Does std::async can "reuse" threads?

As described in title I'd like to know whether tasks runned with std::async can "reuse" idle threads.

For example lets take next code:

auto task = []() { std::this_thread::sleep_for(std::chrono::seconds(20)); };
int tasksCount = 160;
std::vector<std::future<void>> futures;

for (int i = 0; i < tasksCount; ++i)
{
    futures.push_back(std::async(task));
}

So we have a lot of tasks (160) runned in parallel which do nothing. When this code is running on windows it generates 161 waiting threads.

Isn't it too much threads for doing nothing? Why waiting threads can't be "reused"?

ChangeDisplaySettingsEx return code -2

I trying rotate the screen 360º, but the function ChangeDisplaySettingsEx return -2, if you know the reason helpme. I try too create second variable with the struct DEVMODE, but this doesn't works.

Is problem of my screen driver ? Is problem of my OS ? In my case is Windows 10 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

My code here:

#include "stdafx.h"
#include<windows.h>
#include<iostream>
#include <chrono>
#include <thread>

using namespace std;

//enum version { char nombre[] = "quesito", int version = 15 };

namespace tipos_de_campo_base {
    long int vertical = 544997536; //Default
    long int horizontal = DM_DISPLAYORIENTATION; //128
}

class abstractclass {
public:
    virtual void definir_dev(DEVMODE * dm) {
        //cout << dm << endl;
        ZeroMemory(dm, sizeof(dm));
        //cout << dm << endl;
        dm->dmSize = sizeof(dm);
    }
    //pura
    virtual int get_len() = 0;
    virtual void a_dormir(int sec) {
        this_thread::sleep_for(chrono::milliseconds(sec));
    }
};

class testing : public abstractclass{
    int array_orientation[3] = { DMDO_90,DMDO_180,DMDO_270 };
public:
    int ret_arr_val(int i) {
        return this->array_orientation[i];
    }
    int get_len() {
        return sizeof(this->array_orientation) / sizeof(this->array_orientation[0]);
    }
};

int main(){
    testing orientation;
    DEVMODE xd;
    DEVMODE horizontal; 
    orientation.definir_dev(&xd);
    if (0 != EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &xd))
    {
        DWORD dwTemp = xd.dmPelsHeight;
        xd.dmPelsHeight = xd.dmPelsWidth;
        xd.dmPelsWidth = dwTemp;
        xd.dmFields = tipos_de_campo_base::vertical;
        //xd.dmFields = tipos_de_campo_base::horizontal; //Lo pone por default por lo cual sobra //en este caso es para usar DMDO_90
        for (int me = 0; me < 1;me++) {
            for (int xn = 0; orientation.get_len() > xn; xn++) {
                if (orientation.ret_arr_val(xn) == DMDO_90 || orientation.ret_arr_val(xn) == DMDO_270) {
                    cout << "Vertical: " << endl;
                    cout << orientation.ret_arr_val(xn) << endl;
                    xd.dmDisplayOrientation = orientation.ret_arr_val(xn);
                    cout << ChangeDisplaySettingsEx(NULL, &xd, NULL, CDS_RESET, NULL) << endl;
                    orientation.a_dormir(2000);
                }
                else {
                    cout << "Horizontal: " << endl;
                    cout << orientation.ret_arr_val(xn) << endl;
                    xd.dmDisplayOrientation = orientation.ret_arr_val(xn);
                    cout << ChangeDisplaySettingsEx(NULL, &xd, NULL, CDS_RESET, NULL) << endl;
                    orientation.a_dormir(2000);
                }
            }
            xd.dmFields = tipos_de_campo_base::horizontal;
            xd.dmDisplayOrientation = DMDO_DEFAULT;
            cout << ChangeDisplaySettingsEx(NULL, &xd, NULL, CDS_RESET, NULL) << endl;
        }
        system("pause");
    }
}

Why libstdC++'s std::vector's ctor implementation doesn't occur memory leak?

I'm using GCC 7.3.0 with libstdc++.

Here is std::vector's ctor implementation.

      vector(initializer_list<value_type> __l,
         const allocator_type& __a = allocator_type())
      : _Base(__a)
      {
    _M_range_initialize(__l.begin(), __l.end(),
                random_access_iterator_tag());
      }

      // Called by the second initialize_dispatch above
      template<typename _ForwardIterator>
    void
    _M_range_initialize(_ForwardIterator __first,
                _ForwardIterator __last, std::forward_iterator_tag)
    {
      const size_type __n = std::distance(__first, __last);
      this->_M_impl._M_start = this->_M_allocate(__n);
      this->_M_impl._M_end_of_storage = this->_M_impl._M_start + __n;
      this->_M_impl._M_finish =
        std::__uninitialized_copy_a(__first, __last,
                    this->_M_impl._M_start,
                    _M_get_Tp_allocator());
    }

In function _M_range_initialize(_ForwardIterator,_ForwardIterator,std::forward_iterator_tag), when std::__uninitialized_copy_a throw exception, this->_M_impl._M_start, that was allocated in this function, will not released, I think.

That means this implementaion will occur memory leak.

However, libstdc++ is well-tested, well-known library. My understand must be incorrect.

Why this implementation doesn't occur memory leak?

Lot of threads waiting for a mutex

The following situation occured in some code I found. A lot (about 10) of threads use one mutex to write or read from a map. The mutex locking is done with a lock_guard. My question is about the situation where the thread number increased and 10 threads are waiting at the same time for the mutex. I know that there is no guarantee on the order. Are there any side effects on this situation? Is there at least a guarantee that every thread is able to lock the mutex or may there be threads that never get a chance to access the data structure because others are faster?

why sort in C++ is much slower than qsort in C?

In the book The C++ Programming Language (4th Edition), Stroustrup say that sort is much faster than qsort , but in my experiment, I got a different result, could any one help me to explain Why?

Here is my code :

double begin_time=0, end_time=0, elapsed_time=0;

vector<string> vs1 = { "fsfaa", "errer", "weesa", "yuyre", "wedsa", "xcxcx" };
begin_time = clock();

for (int i = 0; i < 1000000; i++)
{
    std::sort(vs1.begin(), vs1.end());
}

end_time = clock();
elapsed_time = double(end_time - begin_time) / CLOCKS_PER_SEC;

printf("\n\nElapsed time: %f\n", elapsed_time);

const char* vs[] = { "fsfaa", "errer", "weesa", "yuyre", "wedsa", "xcxcx" };
begin_time = clock();

for (int i = 0; i < 1000000; i++)
{
    std::qsort(vs, sizeof(vs) / sizeof(*vs), sizeof(*vs), (int(*)(const void*, const void*))compare_function);
}

end_time = clock();
elapsed_time = double(end_time - begin_time) / CLOCKS_PER_SEC;
printf("\n\nElapsed time: %f\n", elapsed_time);

and,

int compare_function(const void * a, const void * b) {
const char *pa = *(const char**)a;
const char *pb = *(const char**)b;

return strcmp(pa, pb);

}

Here is the result(Windows/Visual Studio):

Elapsed time: 0.245000
Elapsed time: 0.090000

cout vector

#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std;

int main()
{
    vector<vector<int>> v1 = { {1, 2}, {3, 4} };
    vector<vector<int>> v2 = { {5, 6}, {7, 8} };
    for (int i = 0; i < v1.size(); ++i)
    {
        transform(v1[i].begin(), v1[i].end(), v2[i].begin(), v1[i].begin(), plus<int>());
    }
    for (const auto& i : v1)
    {
        for (const auto& j : i)
        {
            cout << j << " ";
        }
        cout << endl;
    }
}

Is it possible to print the vectors with more succinct code? With something from algorithm for example. Thank you.

Output:

6 8

10 12

C++ tuple of vectors, create tuple from elements by index

I've got a template class, that has tuple, filled by vectors.

template<typename ...Ts>
class MyClass
{
    public:
        std::tuple<std::vector<Ts>...> vectors;
};

I want to get new tuple filled by vectors element on the specified index.

template<typename ...Ts>
class MyClass
{
public:
    std::tuple<std::vector<Ts>...> vectors;

    std::tuple<Ts...> elements(int index)
    {
        // How can I do this?
    }
};

Is this even possible?

Twice the same for loop: one compiles, the other does not

I have this piece of code to make a couple of strings lower case (see this SO post).

void some_free_standing_function(std::string solver, std::map<std::string, option_t> opts) {

    for (auto & c : solver) c = tolower(c);
    for (auto p : opts)
        for (auto & c : p.first)
            c = tolower(c);
}

The first range-based for seems to compile, the last one does not: Clang gives me error: cannot assign to variable 'c' with const-qualified type 'const char &'.

Why does the first one pass but not the second one, given that they are exactly the same?

An error about no match for friend template function

There's a matrix template class, and when I call the friend function "dot()", it crash and tell me "no match for call to this function. I wondered why and how to deal with it. And my code as follows with a little simplify,

#ifndef _ZMAT_H_
#define _ZMAT_H_
#include<iostream>

template <typename Type>
class Matrix {
    private:
        int Rows;
        int Cols;
        Type *Values; 
    public:
        Matrix(const int & row, const int & col);
        Matrix(const Matrix<Type> & mat);
        ~Matrix();

        template <typename FriendType, typename FriendOtherType, typename ReturnType>
        friend Matrix<ReturnType> & dot(const Matrix<FriendType> & mat, const Matrix<FriendOtherType> & other_mat);

        Type & operator() (const int & row, const int & col);
};

template <typename Type>
Type & Matrix<Type>::operator() (const int & row, const int & col) {
    return this->Values[row * this->Cols + col];
}

template <typename Type>
Matrix<Type>::Matrix(const Matrix<Type> & mat) {
    this->Rows = mat.Rows;
    this->Cols = mat.Cols;
    this->Values = new Type[this->Rows * this->Cols];
    for (int i = 0; i < this->Rows * this->Cols; ++i)
        this->Values[i] = mat.Values[i];
}

template <typename Type>
Matrix<Type>::Matrix(const int & row, const int & col) {
    this->Rows = row;
    this->Cols = col;
    this->Values = new Type[row * col];
}

template <typename Type>
Matrix<Type>::~Matrix() {
    delete [] this->Values;
}

template <typename FriendType, typename FriendOtherType, typename ReturnType=decltype(std::declval<FriendType>() * std::declval<FriendOtherType>())>
Matrix<ReturnType> & dot(const Matrix<FriendType> & mat, const Matrix<FriendOtherType> & other_mat) {
    if (mat.Cols != other_mat.Rows) {
        std::cerr << "Shape match failed." << std::endl;
        exit(0);
    }
    Matrix<ReturnType> * result = new Matrix<ReturnType>(mat.Rows, other_mat.Cols);
    for (int i = 0; i < mat.Rows; ++i)
        for (int j = 0; j < other_mat.Cols; ++j) {
            ReturnType temp = 0;
            for (int k = 0; k < mat.Cols; ++k) 
                temp += mat(i, k) * other_mat(k, j);
            (*result)(i, j) = temp;
        }
    return *result;
}
#endif

My main function as follows,

#include <iostream>
#include "Zmat.h"
int main() {
    Matrix<int> m6(2, 2, {0, 1,
                          1, 0});
    Matrix<int> m7(2, 2, {1, 2,
                          3, 4});
    Matrix<int> m8(dot(m6, m7));
    m8.display();
}

when the function "dot()" called, it crash and tell me "no match for call to ...".

mardi 30 janvier 2018

std::atomic error: no ‘operator++(int)’ declared for postfix ‘++’ [-fpermissive]

I am trying to update an atomic variable through different threads and getting this error. This is my code.

class counter {
    public:
    std::atomic<int> done;

    bool fn_write (int size) const {
        static int count = 0;
        if (count == size) {
            done++;
            count = 0;
            return false;
        } else {
            count++;
            return true;
        }
    }
};

int main() {
    counter c1;
    for (int i=0; i<50; i++) {
        while (! c1.fn_write(10)) ;
    }
}

I am getting the following error in line 8 done++.

error: no ‘operator++(int)’ declared for postfix ‘++’ [-fpermissive]

C++11 Error - What does this error mean when I try to dynamically increase the size of an array?

I am using this algorithm for dynamically increasing the size of an array:

void resize(int* oldArray, int* capacity) {
*capacity = *capacity * 2;
int* new_array = new int[*capacity];
for (int i = 0; i < *capacity/2; i++) {
    new_array[i] = oldArray[i];
}
delete[] oldArray;
oldArray = new_array;

}

However, when I build and run this algorithm I get the following error:

r3(21751,0x7fff8d76e340) malloc: * error for object 0x7f8ca5c026c0: pointer being freed was not allocated * set a breakpoint in malloc_error_break to debug Abort trap: 6

Also, this is the main function I am using:

int main(int argc, char* argv[]) {
if (argc != 2) {
    return -1;
}

std::ifstream inFile(argv[1]);
int capacity = 10;
int* num_array = new int[capacity];
int num_elements = 0;

if (inFile.is_open()) {
    std::string line;
    while (!inFile.eof()) {
        getline(inFile,line);
        if (num_elements == capacity) {
            resize(num_array,&capacity);
        }
        int num = stoi(line);
        num_array[num_elements++] = num;
    }

    for (int i = 0; i < num_elements; i++) {
        std::cout<<num_array[i]<<std::endl;
    }
}

}

Can anyone please tell me why this is happening? Thank you!

How to return non-const iterator from function taking a const reference to a container

I am trying to write a template function to return the lexicographical last element in a container.

From my understanding of const correctness, since the function doesn't modify the template argument reference it should be const correct. How would I return a non-const iterator?

In other words, the function doesn't modify the containers elements because it is constant, but that guarantee shouldn't extend to the returned iterator should it?

I wish to express that the function does not modify anything but the returned iterator could allow the caller to do so.

#include<iterator>

template<typename T>
typename T::iterator lexicographical_last(const T& container)
{
  typename T::const_iterator b, last = container.begin();
  while (b != container.end())
    {
      if (b < last) last = b;
      ++b;
    }
  return last;
}

Why does implementation of make_tuple not return via brace initialisation?

To understand the question please read this answer first.

I checked different historic make_tuple implementations (including clang versions of 2012). Before C++17 I would have expected them to return {list of values ... } but they all construct the tuple before returning it. They are all along the lines of the very simplified current cppreference example:

template <class... Types>
auto make_tuple(Types&&... args)
{
    return std::tuple<special_decay_t<Types>...>(std::forward<Types>(args)...);
}

Its not wrong but the point of returning brace initialization is to construct the returned object directly. Before C++17 there was no guaranteed copy elision which removes the temporaries even conceptually. But even with C++17 I would not necessarily expect the curly braces to disappear in this example.

Why no curly braces here in any of the C++11/14 implementations?

checking uniqueness of characters at compile time

Is it possible in C++11 (not later) to write a function that verifies the uniqueness of characters passed to it at compile time

verify('a');
verify('b');
verify('c');
verify('a');  //should cause compilation error

Template arguments deduction failed: passing func pointer to std::function [duplicate]

In provided example foo cannot infer type of T for both - function pointer and lambda (commented out), with provided type or foo2 everything works fine. What prevents foo from infering type T? Is there any way to have it done autmatically?

template<typename T>
void foo(std::function<T(const T&)> op) {
    std::cout << op(6) << std::endl;
}

void foo2(std::function<int(const int&)> op) {
    std::cout << op(6) << std::endl;
}

int bar(const int &x) {return 3 * x;}

int main() {
    //    foo(bar);
    //    foo([](const int &x) {return 3 * x;});

    foo<int>(bar);
    foo<int>([](const int &x) {return 3 * x;});

    foo2(bar);
    foo2([](const int &x) {return 3 * x;});

    return 0;
}

Using c++11 legacy library in a C++17 project: compiler & linker problems

I am working in a project based on C++17 and have to rely on a library built with C++11 (or older). Problems arise from the fact that several structs have been removed for good from std with C++17. Note that I am building the legacy library from source!

The problems:

  • If I am building the library with C++11 and use it in the C++17 project, the linker won't find the correct implementations (e.g. string). That makes sense, since listing the library symbols I can see it references std::c++11::basic_string.
  • If I am trying to build the library with C++17, the compiler does not find the missing C++03 structs (e.g. ptr_fun). Again makes sense, as they are not part of the C++17 stdlib.
  • If I am trying to build the library with C++17 but include headers from C++11, everything explodes. Makes sense since the headers are not compatible.

Long story short, I do not see how to easily solve this. Technically, since I am able to build the library from source, there should be no definitive reason why I cannot use it with any other project. What's the best practice for this?

I am using Linux with clang for this. The question should be the same with any compiler and OS though.

Unique Pointer as default parameter

I am trying to give the nullpointer wrapped as a unique pointer as the default argument to a function. Using only pointers the header might look like this

double f(A* vec = nullptr);

Since I do however need to use a unique_ptr, I tried to change it to

double f(std::unique_ptr<A>& A vec = nullptr);

or

double f(std::unique_ptr<A>& A vec = std::unique_ptr<A>(nullptr));

Which results in the errors

could not convert ‘nullptr’ from ‘std::nullptr_t’ to ‘std::unique_ptr&’

and

cannot bind non-const lvalue reference of type ‘std::unique_ptr&’ to an rvalue of type ‘std::unique_ptr’

respecively. Is there a way to do this? I am relatively new to C++, so the answer might be obvious.


Not relevant to the question, but an explanation for my choice of unique_ptr: The parameter vec is used as the start value for an iteration in f and an improved value is returned with the pointer. The plan was that if no start value is given the pointer is set to the nullptr and a start value is calculated during the program. Since I however generate a new object, it would from all I can see be safer to use unique_ptr over a naked pointer.

Can a std::promise know that the respective std::future has cancelled waiting?

I'm in a situation where I have a continuous thread working on some input. However, sometimes the work load is too high and the corresponding future will not wait for the result. I need to free some resources in that case, since the computation result then won't be carried on (to be marked as being able to be freed, somewhere else).

Is it possible for the promise to know that the respective future has stopped waiting? Or could I achieve this effect by other means? (shared_future, ...?)

As an outline of the concept I have modified the std::promise example, for your easier understanding of what I mean:

using namespace std::chrono_literals;

void accumulate(std::vector<int>::iterator first,
                std::vector<int>::iterator last,
                std::promise<int> accumulate_promise)
{
    int sum = std::accumulate(first, last, 0);

    /* Can I possibly know that the corresponding future has stopped 
     * waiting for this promise, at this very position? 
     */
    accumulate_promise.set_value(sum);
}

int main()
{
    std::vector<int> numbers = { 1, 2, 3, 4, 5, 6 };
    std::promise<int> accumulate_promise;
    std::future<int> accumulate_future = accumulate_promise.get_future();
    std::thread work_thread(accumulate, numbers.begin(), numbers.end(),
                            std::move(accumulate_promise));

    /* Do not wait forever */
    accumulate_future.wait_for(1ms);
}

"partial specialization after instantiation" in boost headers

I have the following code:

foo.h

#include <boost/range/iterator_range.hpp>

#include <string>


inline void foo(const char* s)
{
    boost::iterator_range<std::string::const_iterator> r{
        s, s + std::char_traits<char>::length(s)
    };
    (void)r;
}

foo.cpp

#include <foo.h>
#include <boost/range/as_literal.hpp>
// some other code that uses as_literal

boost/range/as_literal.hpp is included by several headers under boost/algorithm, including but not limited to

#include <boost/algorithm/string/find.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/classification.hpp>

This compiles fine with clang 4.0 and trunk, but fails with GCC 4.8, 7.2 and trunk:

$ g++ -std=c++11 -Wall -pedantic -Wextra -Wformat=2 -Wshadow -Werror foo.cpp
/usr/include/boost/range/detail/str_types.hpp:26:12: error: partial specialization of ‘struct boost::range_const_iterator<T*>’ after instantiation of ‘struct boost::range_const_iterator<const char*, void>’ [-fpermissive]
     struct range_const_iterator<T*>
            ^~~~~~~~~~~~~~~~~~~~~~~~

Now I have a problem because foo.h cannot tell whether any of the "dangerous" boost headers are included after it. Users of foo.h will get a nasty surprise if they start using any of these headers (or worse, if they were already using those boost headers and add foo.h, their code won't compile - and they're going to complain to me that foo.h is broken).

The only solution I could find was to include boost/range/as_literal.hpp into foo.h, before the usage of boost::iterator_range, even though nothing in foo.h needs boost::as_literal.

This sounds like a bug in boost (1.62), because boost/range/as_literal.hpp includes boost/range/detail/str_types.hpp, which contains

namespace boost
{
    template< class T >
    struct range_const_iterator<T*>
    {
        typedef const T* type;
    };
}

whereas boost/range/iterator_range.hpp ultimately includes boost/range/const_iterator.hpp, which contains

namespace boost
{

template< typename C >
struct range_const_iterator_helper
        : extract_const_iterator<C>
{};

template<typename C, typename Enabler=void>
struct range_const_iterator
        : range_detail::range_const_iterator_helper<
            BOOST_DEDUCED_TYPENAME remove_reference<C>::type
        >
{
};

} // namespace boost

Defining the same struct with different content can't be right.

Which compiler is right? clang for accepting it or GCC for rejecting it?

Can I use std::generate to get a vector of std::array

It's easy to use std::generate to get a sequence of T. Simple Example code here:

std::vector<int> v(5);
std::generate(v.begin(), v.end(), [n = 0] () mutable { return n++; });

Can I use std::generate to get std::vector<std::array<T,2>>?

My template function code here:

#include <algorithm>
#include <array>
#include <vector>
template<typename T>
std::vector<std::array<T, 2>> m(int rows, int cols) {
    std::vector<std::array<T, 2>> vec(rows*cols);
    // this is the x value I want to generate
    std::vector<T> x(rows*cols);
    std::generate(x.begin(), x.end(), 
                  [n = -1, COLS = cols]() mutable { ++n; return n % COLS;});
    // This is the y value I want to generate
    std::vector<T> y(rows*cols);
    std::generate(y.begin(), y.end(), 
         [n = -1, ROWS = rows]() mutable { ++n;  return floor(n / ROWS); });
    // Is it possible to combine the above steps into one step? 
    std::generate(vec.begin(), vec.end(), 
    [n = -1, COLS = cols, ROWS = rows]() mutable { ++n;  return .... });
    return vec;
}

I'd like to combine two steps into one step, is it any convenient way doing so?

Error setting pthread to Round Robin in Ubuntu 16.04

I am trying to have a real time Round Robin thread for my C++ sofware running in Ubuntu 16.04.

In the thread I have the following code:

void* thread1(void *){
   struct sched_param param;
   param.sched_priority = sched_get_priority_max(SCHED_RR);
   if(pthread_setschedparam(0, SCHED_RR, &param)!=0){
       cout<<"Error Setting Thread to Realtime..."<<endl;
   }
}

The value pthread_setschedparam() return is 3 which I think the error is ESRCH according the the #define in the errno-base.h in the /usr/include/asm-generic/errno-base.h.

According to the man page (http://man7.org/linux/man-pages/man2/sched_setscheduler.2.html) it says that

The thread whose ID is pid could not be found.

I am not sure how I can set that. Could any experience programmer give me some advice on this?

PS: I have followed the answer in this post Real-time programming with Linux and put my group into the realtime group in

/etc/security/limits.conf

Pointer references in Lambda

struct taskinfo
{
        long int id;
        bool cancel;
        std::function<void()> func;
        std::chrono::system_clock::time_point time;
        std::chrono::system_clock::duration interval;
}

....

std::priority_queue<taskinfo, std::vector<taskinfo>> tasks;
void at(taskinfo** task){
        std::function<void()> threadFunc = [task]() { std::thread((*task)->func).detach(); };
        (*task)->func = threadFunc;
        tasks.push(**task);
}

I think I am missing something here when I pop the function out of the queue to execute, the function may be empty, Nothing is getting executed.

If i copy taskinfo to locally

void at(taskinfo** task){
            taskinfo t = **task;
            //Replace everything else with t function works fine But 
            //I need to modify the same reference
}

How can I work with pointer reference herein lambda?

How to determine if the type being passed in copy constructor is same as the type in member variable

I am trying to come up with a rough sketch of a basic shared pointer. In the copy constructor I would like to ensure that the passed object is of the same type as the one present in its member variable. This is the rookie code I have so far.

template <typename t>
class myshared
{
    public:
    myshared(t* ptr) : obj(ptr)
    {
        counter++;
        std::cout << "Regular constructor called"<< std::to_string(counter+1) << std::endl;
    }

    //Copy constrcutor
    myshared(const myshared<t>& obj)
    {
         this->obj = obj.obj;
        std::cout << "Copy constrcutor called" << std::to_string(counter+1)<< std::endl;
    }

    t* operator->()
    {
        return obj;
    }

    ~myshared()
    {
        counter--;
        std::cout << "destructor called " << std::to_string(counter) << std::endl;

    }
    private:
    int counter=0;
    t* obj;
};

int main() 
{
    myshared<foo> first(new foo());
    myshared<foo> sec(first);
    sec->x =12;
}

Now my question is regarding the copy constructor

myshared(const myshared<t>& obj)
{
}

The above I believe would accept any template type of myshared. I would like it to only accept the type similar to its member variable t* objtype. How can I accomplish that ?

lundi 29 janvier 2018

#define constexpr in C++

I came across some code as shown below:

#define set_opcode(name) \
    constexpr static auto get_opcode() noexcept \
    { \
        return OpcodeValue::name; \ //OpcodeValue is some enum
    }

class NoopOpcode : public Opcode
{
public:
    set_opcode(NOOP);

    std::string serialize() const noexcept override;

    bool deserialize(const std::string &serialized) noexcept override;

    void execute(state::State &state) const noexcept override;

};


class InvOpcode : public Opcode
{

private:

    Int _item_id{};

    Int _item_count{};



public:

    set_opcode(INV);

    std::string serialize() const noexcept override;

    bool deserialize(const std::string &serialized) noexcept override;

    void execute(state::State &state) const noexcept override;

};

what is the reason/benefit for using #define to declare a constexpr?

Isn't it same thing as explicitly declaring get_opcode() {return OpcodeValue::NOOP; } inside the class NoopOpcode for example?

std::lock_guard constructor instantiation order

I suppose this is more a general question about lvalue instantiation ordering.

In short, is this safe?:

void func1()
{
    std::lock_guard< std::mutex > lock( mutex );
    //do some stuff in locked context
}

void func2()
{
    func1();
    std::lock_guard< std::mutex > lock( mutex );
    //do some stuff in locked context
}

I am somewhat concerned that the compiler may call the constructor of the lock_guard before calling func1 from within func2, thus causing a deadlock.

Is it guaranteed that this is safe or do I need to do something like this:

void func1()
{
    std::lock_guard< std::mutex > lock( mutex );
    //do some stuff in locked context
}

void func2()
{
    func1();

    { //lock
        std::lock_guard< std::mutex > lock( mutex );
        //do some stuff in locked context
    } //unlock
}

specify nested template parameters for function call

How I can specify types for template function when I call it?

#include <string>
#include <utility>
#include <boost/variant.hpp>

template <typename O, typename E, template <typename, typename> class VariantType>
VariantType<O, E> f(O o)
{
    return VariantType<O, E>{std::move(o)};
}

int main()
{
    boost::variant<int, std::string> res = 
     f<int, std::string, boost::variant<int, std::string>>(17);
}

clang reports such error(clang++ -Wall -std=c++11 test.cpp):

test.cpp: error: no matching function for call to 'f'
                boost::variant<int, std::string> res = f<int, std::string, boost::variant<int, std::string>>(17);
                                                       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
test.cpp: note: candidate template ignored: invalid explicitly-specified argument for template parameter 'VariantType'
VariantType<O, E> f(O o)

Looking for a clean way to use dynamic type declaration when accessing information in a union

I'm wrote some code today to access information in a very annoying hierarchy of classes. The code seems very ugly and repetitive for what I need to do, but I cannot figure out how to simplify it. I think the key would be the ability to declare types at runtime. I tried to find a better solution with auto, but I am unable to come up with anything.

I receive a message and need to determine if a sensor has been deployed. An value called the discriminant holds an enumerated value of the sensor type. Using that information I have to access a Union composed of many different sensors, selecting the correct one, and iterate through an array of utilization states looking for a value which represents deployed.

The classes would be near impossible to replicate but I write some psudo-code down below representing my current solution to the problem.

  SomeNamespace::Sensor_UE sensorType = message->data.sensingSystem.sensor.discriminant;
  bool dropMessage = true;
  if(message->data.sensingSystem.isValid)
  switch(sensorType)
  {
    case sensorType1:
    sensorType1 *sensor = &(message->data.sensingSystem.sensor.sensorType1)
    if(sensor->isValid)
      for(int i = 0; i < AnotherNamespace::ConstantsStruct::MaxUtilizationStates; i++)
      {
        if(sensor->utilizationState[i].value == YetAnotherNamespace::UtilizationStates::deployed)
        {
          dropMessage = false;
        }
      } 
  }

The switch statement below repeats with a dozen or so iterations of practically the same code. The only difference is the declaration and initiation of the sensor pointer. I would really like to get everything else outside the switch statement but since I have to declare the value based on the value of the sensorType enum I'm not sure if there is a way to do this. I would prefer not to use pointer math or c type casts as that stuff generally gets frowned upon unless absolutely necessary. Any thoughts would be appreciated.

I wonder why there is an error calling the destructor in the inheritance

#include<iostream>
using namespace std;

class A
{
public:
   A() { cout << "A Creator" << endl; }
   ~A() { cout << "A Destroyer" << endl; }
};

class B : public A
{
public:
    B() { cout << "B Creator" << endl; }
    virtual ~B() { cout << "B Destroyer" << endl; }
};

void main()
{
    A* temp = new B;
    delete temp;
}

enter image description here

I'm not sure I think this is what I think. I am definitely wondering why the error is happening.

temp allocates a derived class B and stores it in a pointer type (base class A).

At this time, the compiler is based on the pointer data type.

The virtual function table is not created because the base class destructor does not have a virtual declaration.

Class B creates a virtual function table. A virtual function table pointer is also created.

When trying to destroy temp, temp calls the pointer data type destructor and issues a problem.

 

Class B virtual function table pointer can not be found.

This is because the pointer data type is a non-virtual base class.

Problems with slow building and compiling c++ programs

I am a Computer Science student and we are using Sublime Text 3, Windows Powershell, and MinGW to compile, build, and run c++ programs. I am using a Surface Pro 4 laptop for school with Norton Security Suite. I've excluded the folders where I store these programs, Sublime Text 3, and Windows Powershell from scans and Auto-Protect. When I try to compile and build using ctrl + B in Sublime Text 3 it takes much longer to do so. Running the exact same code as the instructor, compared to his 0.4 seconds mine will take 1.4 seconds. What is it that could be slowing down my build/compile/run?

I need this to run faster because we'll be making larger programs and I can't have windows stopping me in before I know if a program works or not. Thank you!

std::binding to a lambda: compilation error

I ran into an error trying to std::bind to a lambda. The following code sample compiles fine:

#include <functional>
#include <iostream>

int main()
{
    const auto lambda1 = [](int a, int b){ return a + b; };

    std::cout << (std::bind( lambda1, std::placeholders::_1, 2))(2)
              << std::endl;

    return 0;
}

but the following doesn't:

#include <functional>
#include <iostream>

int main()
{
    const auto lambda2 { [](int a, int b){ return a + b; } }; // Note the "{ }-initialization"

    std::cout << (std::bind( lambda2, std::placeholders::_1, 2))(2)
              << std::endl;

    return 0;
}

Here's the error output I got using Visual Studio 2013, update 4:

1>------ Build started: Project: Project1, Configuration: Debug Win32 ------
1>  main.cpp
1>C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\xrefwrap(58): error C2064: term does not evaluate to a function taking 2 arguments
1>          C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\xrefwrap(118) : see reference to class template instantiation 'std::_Result_of<_Fty,int &,int &>' being compiled
1>          with
1>          [
1>              _Fty=std::initializer_list<main::<lambda_55c00b1d5f4fcd1ad46b46ad921a2385>>
1>          ]
1>          C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\functional(975) : see reference to class template instantiation 'std::result_of<_Funx (int &,int &)>' being compiled
1>          with
1>          [
1>              _Funx=std::initializer_list<main::<lambda_55c00b1d5f4fcd1ad46b46ad921a2385>>
1>          ]
1>          main.cpp(23) : see reference to class template instantiation 'std::_Do_call_ret<false,_Ret,std::initializer_list<main::<lambda_55c00b1d5f4fcd1ad46b46ad921a2385>>,std::tuple<std::_Ph<1>,int>,std::tuple<int &>,std::_Arg_idx<0,1>>' being compiled
1>          with
1>          [
1>              _Ret=void
1>          ]
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

What is going on? There seems to be some kind of mix up with initializer list but I'm not sure I nee why.

Is accessing "object representation" using the constructor string_view(const CharT*, size_type) defined char aliasing or undefined behavior?

Let we have this object

constexpr uint64_t lil_endian = 0x65'6e'64'69'61'6e; // 00en dian
    // a.k.a. Clockwise Rotated Endian which allocates like
    // char[8] = { 'n','a','i','d','n','e','\0','\0' }

It is believed that memcpy is there also to help pun type like this

char arr[sizeof(lil_endian)];
auto p1 = std::addressof(arr[0]);
std::memcpy(p1, &lil_endian, sizeof(lil_endian) ); // defined?
auto sv1 = std::string_view(p1, sizeof(lil_endian) );
std::string str1(sv1.crbegin()+2, sv1.crend() );
std::cout << str1        << "\n"
          << str1.size() << "\n";

everything is like expected:

endian
6


The matter of fact is that even with string_view alone, we access the object by char anyway, which char is one of the allowance three char, unsigned char, std::byte aliases.

So can we just skip the redundant copy part of the code, like this?

auto p2 = reinterpret_cast<const char *>
                ( &lil_endian );
auto sv2 = std::string_view(p2, sizeof(lil_endian) ); // is this "char" aliasing?
std::string str2(sv2.crbegin()+2, sv2.crend() );   
std::cout << str2        << "\n"
          << str2.size() << "\n";

}

output:

endian
6

Is the constructor string_view(const CharT*, size_type) "char" aliasing by strict aliasing [basic.val] § 11 in N4713 page 82

godbolt

wandbox

How to access the template function that is stored in the structure?

struct taskinfo{
    template <class callable, class... arguments>
    taskinfo(callable&& f, arguments&&... args){
        std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...));
    }
};

void test2(int a)
{
    printf("%i\n", a);
    return;
}

int main()
{
    taskinfo t1(&test2,100);
    std::priority_queue<taskinfo> tasks;
    tasks.push(t1);
    //tasks.top(). Execute task
    return 0;
}

I need to execute tasks by popping out of priority queues. My goal is to have a structure with function with any return type and accepting variable arguments.

C++: Map 3 elements to one key in std::unordered_multimap

My question is an extension of the following question: Searching and Inserting in a map with 3 elements in C++

In addition to the above mentioned case, I would like to have an extra pair in map as given below definition.

std::unordered_multimap<unsigned int, 
      std::pair< std::pair<unsigned int, unsigned int>, float>> wedgeAlphaMap;

This does not work well. All the time when I emplace values for the second variable in the pair(i.e. vi2), I am getting a garbage value. (code shown below)

wedgeAlphaMap.emplace(vi0, std::make_pair(std::make_pair(vi1,vi2), alpha) );

How I can properly make use of it/ or do I have missed something?

c++ 11 regex print all groups

My question is really simple, I can't make c++ 11 regex to return all groups present in the string.

code below is what I'm using:

#include <iostream>
#include <regex>

int main()
{
  auto fixMessage("8=FIXT|9=69|35=5|34=18|49=102|56=asd|115=TESTTESTTEST|52=20170810-15:36:22.500867816|1409=42|");
  std::regex e ("(([0-9]+)=(.*?)\\|)+?");
  std::cmatch element_match;

  if(std::regex_match(fixMessage, element_match, e)) {
        for (size_t i = 0; i < element_match.size(); ++i) {
            std::cout << i << ": " << element_match[i] << '\n';
        }
  }
  return 0;
}

this only prints this

0: 8=FIXT|9=69|35=5|34=18|49=102|56=asd|115=TESTTESTTEST|52=20170810-15:36:22.500867816|1409=42|
1: 1409=42|
2: 1409
3: 42

while I would like to have all groups not just the last one .. here is a cpp.sh url

Accesing 2dimension set

How to print all elements of 2-dimensional set created here?

int i, j, n;
set< set<int> > st;
set< set<int> > ::iterator it;
for(i=0;i<5;i++)
{
    set<int>row;
    for(j=0;j<5;j++)
    {
        cin>>n;
        row.insert(n);
    }
    st.insert(row);
}

Passing variable by reference to several threads corrupts heap

This is part of a test for thread safety. I'm running an anonymous lambda in different threads.

I use the variable i as thread id.

Originally I passed every variable from main scope by using [&], but this corrupts the heap.

Solved it now by passing i by value, but for the life of me I can't figure out why this would cause problems on the heap since the threads are only reading i.

Can anyone explain?


Minimal compilable example producing error:

#include <thread>
#include <vector>

using namespace std;

int main(int argc, char** argv) {
    vector<thread> threads;
    vector<string> vec1;
    vector<string> vec2;
    for (int i = 0; i < 2; i++) {
        threads.push_back(
            thread([&vec1, &vec2, &i]() {
                for (int j = 0; j < 10; j++) {
                    const string str = "foo";
                    if (i == 0) {
                        vec1.push_back(str);
                    } else {
                        vec2.push_back(str);
                    }
                }
            })
        );
    }

    for (auto& thread : threads) {
        thread.join();
    }

    return 0;
}

Output:

*** Error in `/vagrant/bin/TempFileTest': double free or corruption (fasttop): 0x00007f00240008c0 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x777e5)[0x7f002a0e97e5]
/lib/x86_64-linux-gnu/libc.so.6(+0x8037a)[0x7f002a0f237a]
/lib/x86_64-linux-gnu/libc.so.6(cfree+0x4c)[0x7f002a0f653c]
/vagrant/bin/TempFileTest(_ZNSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS5_EE19_M_emplace_back_auxIJRKS5_EEEvDpOT_+0x1a3)[0x4021b3]
/vagrant/bin/TempFileTest[0x401e83]
/usr/lib/x86_64-linux-gnu/libstdc++.so.6(+0xb8c80)[0x7f002a70ac80]
/lib/x86_64-linux-gnu/libpthread.so.0(+0x76ba)[0x7f002a9db6ba]
/lib/x86_64-linux-gnu/libc.so.6(clone+0x6d)[0x7f002a17941d]
======= Memory map: ========
00400000-00403000 r-xp 00000000 08:02 2622834                            /vagrant/bin/TempFileTest
00602000-00603000 r--p 00002000 08:02 2622834                            /vagrant/bin/TempFileTest
00603000-00604000 rw-p 00003000 08:02 2622834                            /vagrant/bin/TempFileTest
02182000-021b4000 rw-p 00000000 00:00 0                                  [heap]
7f001c000000-7f001c021000 rw-p 00000000 00:00 0 
7f001c021000-7f0020000000 ---p 00000000 00:00 0 
7f0024000000-7f0024021000 rw-p 00000000 00:00 0 
7f0024021000-7f0028000000 ---p 00000000 00:00 0 
7f0028d67000-7f0028d68000 ---p 00000000 00:00 0 
7f0028d68000-7f0029568000 rw-p 00000000 00:00 0 
7f0029568000-7f0029569000 ---p 00000000 00:00 0 
7f0029569000-7f0029d69000 rw-p 00000000 00:00 0 
7f0029d69000-7f0029e71000 r-xp 00000000 00:32 313                        /lib/x86_64-linux-gnu/libm-2.23.so
7f0029e71000-7f002a070000 ---p 00108000 00:32 313                        /lib/x86_64-linux-gnu/libm-2.23.so
7f002a070000-7f002a071000 r--p 00107000 00:32 313                        /lib/x86_64-linux-gnu/libm-2.23.so
7f002a071000-7f002a072000 rw-p 00108000 00:32 313                        /lib/x86_64-linux-gnu/libm-2.23.so
7f002a072000-7f002a232000 r-xp 00000000 00:32 45                         /lib/x86_64-linux-gnu/libc-2.23.so
7f002a232000-7f002a432000 ---p 001c0000 00:32 45                         /lib/x86_64-linux-gnu/libc-2.23.so
7f002a432000-7f002a436000 r--p 001c0000 00:32 45                         /lib/x86_64-linux-gnu/libc-2.23.so
7f002a436000-7f002a438000 rw-p 001c4000 00:32 45                         /lib/x86_64-linux-gnu/libc-2.23.so
7f002a438000-7f002a43c000 rw-p 00000000 00:00 0 
7f002a43c000-7f002a452000 r-xp 00000000 00:32 314                        /lib/x86_64-linux-gnu/libgcc_s.so.1
7f002a452000-7f002a651000 ---p 00016000 00:32 314                        /lib/x86_64-linux-gnu/libgcc_s.so.1
7f002a651000-7f002a652000 rw-p 00015000 00:32 314                        /lib/x86_64-linux-gnu/libgcc_s.so.1
7f002a652000-7f002a7c4000 r-xp 00000000 00:32 311                        /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21
7f002a7c4000-7f002a9c4000 ---p 00172000 00:32 311                        /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21
7f002a9c4000-7f002a9ce000 r--p 00172000 00:32 311                        /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21
7f002a9ce000-7f002a9d0000 rw-p 0017c000 00:32 311                        /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21
7f002a9d0000-7f002a9d4000 rw-p 00000000 00:00 0 
7f002a9d4000-7f002a9ec000 r-xp 00000000 00:32 61                         /lib/x86_64-linux-gnu/libpthread-2.23.so
7f002a9ec000-7f002abeb000 ---p 00018000 00:32 61                         /lib/x86_64-linux-gnu/libpthread-2.23.so
7f002abeb000-7f002abec000 r--p 00017000 00:32 61                         /lib/x86_64-linux-gnu/libpthread-2.23.so
7f002abec000-7f002abed000 rw-p 00018000 00:32 61                         /lib/x86_64-linux-gnu/libpthread-2.23.so
7f002abed000-7f002abf1000 rw-p 00000000 00:00 0 
7f002abf1000-7f002ac17000 r-xp 00000000 00:32 42                         /lib/x86_64-linux-gnu/ld-2.23.so
7f002adf6000-7f002adfc000 rw-p 00000000 00:00 0 
7f002ae15000-7f002ae16000 rw-p 00000000 00:00 0 
7f002ae16000-7f002ae17000 r--p 00025000 00:32 42                         /lib/x86_64-linux-gnu/ld-2.23.so
7f002ae17000-7f002ae18000 rw-p 00026000 00:32 42                         /lib/x86_64-linux-gnu/ld-2.23.so
7f002ae18000-7f002ae19000 rw-p 00000000 00:00 0 
7fff30694000-7fff306b5000 rw-p 00000000 00:00 0                          [stack]
7fff30761000-7fff30763000 r--p 00000000 00:00 0                          [vvar]
7fff30763000-7fff30765000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]
Aborted (core dumped)

Minimal compilable example without error (notice no & on i):

#include <thread>
#include <vector>

using namespace std;

int main(int argc, char** argv) {
    vector<thread> threads;
    vector<string> vec1;
    vector<string> vec2;
    for (int i = 0; i < 2; i++) {
        threads.push_back(
            thread([&vec1, &vec2, i]() {
                for (int j = 0; j < 10; j++) {
                    const string str = "foo";
                    if (i == 0) {
                        vec1.push_back(str);
                    } else {
                        vec2.push_back(str);
                    }
                }
            })
        );
    }

    for (auto& thread : threads) {
        thread.join();
    }

    return 0;
}


I'm using:

Ubuntu 16.04

gcc 5.4.0

binary search fuction always returns -1 value instead of index

My Binarysearch function returns -1 always instead of index even if the data is present in the array.Can anyone please help me in figuring out the problem

int main(){

int ar[10]={1,2,3,4,5,6,7,8,9,10};
int i,w;
cout<<"enter the element to search"<<endl;
cin>>w;
int y  = binarysearch(ar,w,0,9);
cout<<y<<" index"<<endl;
return 0;
}

int binarysearch(int ar[],int x,int p,int r)
{

    int q;
    if(p==r)
    {
        if(ar[r]==x)
            {
                return r;
            }
        else
           {
                return -1;
           }
    }
    else{
        q = ((r+p)/2);
          if(x<ar[q])
             {
                 return(binarysearch(ar,x,p,q));
             }
              else
                return(binarysearch(ar,x,q+1,r));
}


}

Usage of std::unique_ptr when moving object to worker thread in QT

I am trying to update old code by removing class destructors. Now I got to the following code situation with a QT master and a QT slave (the slave is created, and moved to a second thread afterwards):
My slave was formerly written as

serial_controller_worker::serial_controller_worker(const QString &portname, int waitTimeout, int BaudRate, int numStopBits, bool parity, bool useParity, bool useHex)
{
    this->portName = portname;
    this->waitTimeout = waitTimeout;
    this->baudrate = BaudRate;
    this->numStopBits = numStopBits;
    this->useParity = useParity;
    this->parity = parity;
    this->useHex = useHex;
    this->serial = new QSerialPort(this);
    this->storage = "";
    this->delay_write = 0;
}

serial_controller_worker::~serial_controller_worker()
{
    if(this->serial->isOpen())
        this->serial->close();
    if(this->serial != NULL)
        delete this->serial;
}

and was called in the master as

serial_controller_worker *newWorker = new serial_controller_worker(portName, waitTimeout, BaudRate, numStopBits, parity, useParity, useHex);
newWorker->moveToThread(&workerThread);
this->Hex = Hex;
connect(&workerThread, &QThread::finished, newWorker, &QObject::deleteLater);
connect(this, &Serial_port_library::newTransaction, newWorker, &serial_controller_worker::transaction);
connect(this, &Serial_port_library::connect_now, newWorker, &serial_controller_worker::connectToSerial);
connect(newWorker, &serial_controller_worker::response, this, &Serial_port_library::response_slot);
connect(newWorker, &serial_controller_worker::error_Val, this, &Serial_port_library::connectError);
workerThread.start();
emit this->connect_now();

Now I would like to transfer the slave to a constructor-only class, thus removing the destructor in the slave class. Nevertheless I still have to keep the destruction functions. Thus I created a new function for that:

void serial_controller_worker::delete_serial_controller_worker()
{
    if(this->serial->isOpen())
        this->serial->close();
    if(this->serial != NULL)
        delete this->serial;
}

and created a std::unique_ptr with a custom destructor function:

struct WorkerFree
{
  void operator() (serial_controller_worker *p) const { p->delete_serial_controller_worker(); }
};

class serial_controller_master{
    private:
        std::unique_ptr<serial_controller_worker, WorkerFree> serial_worker;
    public:
        serial_controller_master();
}

serial_controller_master::serial_controller_master()
{
    serial_worker.reset(serial_controller_worker(portName, waitTimeout, BaudRate, numStopBits, parity, useParity, useHex));
    serial_worker->moveToThread(&workerThread);
    this->Hex = Hex;
    connect(&workerThread, &QThread::finished, serial_worker, &QObject::deleteLater);
}

How can I tell QT to use my "destructor" when calling QObject::deleteLater() instead of trying to find another destructor, and how do I use the connect-calls later correctly? Currently I get errors like

error: no matching function for call to ‘Serial_port_library::connect(QThread*, void (QThread::*)(QThread::QPrivateSignal), std::unique_ptr<serial_controller_worker, WorkerFree>&, void (QObject::*)())’
     connect(&workerThread, &QThread::finished, serial_worker, &QObject::deleteLater);

No matching function for call std::forward(const std::string &)

I'm trying to make a movable wrapper to non-copyable, non-movable class, however I have a problem passing a const std::string variable to the constructor. The minimal example below produces following error:

#include <iostream>
#include <memory>
#include <string>
#include <utility>

struct X {
    std::string x;

    X(const std::string &x) : x(x) {}
    X(const X &x) = delete;
    X(X &&x) = delete;
};

struct Wrapper {
    std::unique_ptr<X> x;

    Wrapper(const Wrapper & wrapper) = delete;
    Wrapper(Wrapper && wrapper) = default;

    template<typename... Args>
    Wrapper(Args&&... args) : x(std::make_unique<X>(std::forward(args)...)) {}
};

int main() {
    const std::string XXX = "XXX";
    Wrapper w{XXX};
    std::cout << w.x->x << std::endl;
}

Error message here:

forwarding.cc:21:53: error: no matching function for call to 'forward'
    Wrapper(Args&&... args) : x(std::make_unique<X>(std::forward(args)...)) {}
                                                    ^~~~~~~~~~~~
forwarding.cc:26:13: note: in instantiation of function template specialization 'Wrapper::Wrapper<const std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > &>' requested here
    Wrapper w{XXX};
            ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/7.2.0/../../../../include/c++/7.2.0/bits/move.h:73:5: note: candidate template ignored: couldn't infer template argument '_Tp'
    forward(typename std::remove_reference<_Tp>::type& __t) noexcept
    ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/7.2.0/../../../../include/c++/7.2.0/bits/move.h:84:5: note: candidate template ignored: couldn't infer template argument '_Tp'
    forward(typename std::remove_reference<_Tp>::type&& __t) noexcept
    ^
1 error generated.

Exact measurement of the memory consumption for std::map?

I'm just wondering whether there is a way in C++11 to get an exact estimation of the occupied memory for std::map (in bytes). For example:

std::map<int,int> m;

assume "m" has 10 elements, I want to know what the overall memory consumption is. In some posts I see the following rough estimation for this particular case:

size_t map_size = sizeof(std::map<int,int>) + m.size()*(sizeof(int)*2);

However, it does not consider the memory overhead per element, is it somehow measurable?! Thanks.

Why does std::make_pair not return a pair? Or does it?

My internal sanity check failed so I'm rerunning it on Stackoverflow.

The following code:

#include <iostream>
#include <typeinfo>
#include <utility>

int main()
{
    constexpr auto pair_of_ints = std::make_pair(1, 2);
    std::cerr << typeid(pair_of_ints).name();
    //static_assert(std::is_same<decltype(pair_of_ints), std::pair<int, int>>::value, "WTF");
}

produces the mangled symbol name for std::__1::pair<int, int> on my system (XCode Clang 8.x).

If I then enable the static_assert, it fails. I have no idea why. How can I make this work? I have a function that returns a pair or tuple depending on the arguments passed to it and would like to verify it actually returns a pair or tuple in the correct cases.

How to efficiently roll out a sequence using c++ templates

I've a complex type C depending on a template parameter which I need in a (length bounded) sequence. A constexpr function next() is available to go from C_n -> C_n+1. As every sequence element has a different type I'm using a std::tuple to store the results. The mkTuple() functions take care of the (limited) sequence rollout.

Here's a simplified example of what I did (using std::array as placeholder for my more complex C):

#include <array>
#include <tuple>
#include <iostream>


template<std::size_t OFFSET>
using C=std::array<uint8_t, OFFSET>;

static
constexpr
std::size_t
next(const std::size_t START, const std::size_t DISTANCE)
{
    return START + DISTANCE;
}


template<template<std::size_t OFFSET> class CONTENT, std::size_t START, std::size_t DISTANCE, std::size_t SEQ_LENGTH>
struct mkTuple
{
    using _LT = CONTENT<START>;
    using _RT = typename mkTuple<CONTENT, next(START, DISTANCE), DISTANCE, SEQ_LENGTH - 1>::tuple;
    using tuple=decltype(std::tuple_cat(std::make_tuple(_LT()), _RT()));
};


template<template<std::size_t OFFSET> class CONTENT, std::size_t START, std::size_t DISTANCE>
struct mkTuple<CONTENT, START, DISTANCE, 1>
{
    using _LT = CONTENT<START>;
    using tuple = std::tuple<_LT>;
};


int
main()
{
    using tMyTuple = typename mkTuple<C, 16, 2, 64>::tuple;

    const std::size_t iTupleLength = std::tuple_size<tMyTuple>::value;
    std::cout << "Sequence length =  " << iTupleLength << std::endl;

    const tMyTuple myTuple;
    std::cout << "Tuple[4].size() =  " << std::get<4>(myTuple).size() << std::endl;

    return 0;
}

Problem is that my mkTuple() functions seem to be soo memory expensive that I quickly run into compiler-out-of-memory trouble. In fact g++ -ftime-report ... reports >1GB usage for template instantiations. And this number quickly (exponentially?) rises with growing sequence lengths.

I suspect the std::tuple instantiation required for std::tuple_cat to be the inflater. Does anybody have a good idea how to roll out a sequence more efficiently?

Thx in advance!

Initialization of const pointer to another member of the same struct

I'm creating a struct in which one member is a const pointer (immutable address) to another member of the struct.

In the simplified version below, will both structs always behave the same way? Especially in the sense of whether the addresses stored in ptr are guaranteed to be properly initialized.

struct First
{
  int a;
  int* const ptr = &a;
};

struct Second
{
  int a;
  int* const ptr;

  Second() : ptr(&a) {}
};

(In my actual application the member a is a class instance, and ptr is replaced by a map from some enums to pointers pointing to members of a.)

C++ std::initializer_list constructor

In code like this:

#include <iostream> 
#include <initializer_list>
#include <string>

struct A 
{
  A() { std::cout << "2" << std::endl; }
  A(int a) { std::cout << "0" << std::endl; }
  A(std::initializer_list<std::string> s) { std::cout << "3" << std::endl; }
  A(std::initializer_list<int> l) { std::cout << "1" << std::endl; } 
};

int main() 
{ 
 A a1; 
} 

Why does it call std::initializer_list specification of constructor? It'll generate ambiguity compilation error if we define, for example, constructor with std::initializer_list. What are the rules of such construction and why it's so specific about std::initializer_list with number as template parameter?

dimanche 28 janvier 2018

std::vector initializations and typedefs

I know how to do this the long way so to speak:

#include <vector>

int main() {
    // Simple vector of ints = resized to 1k elements
    std::vector<int>  ints;
    ints.resize( 1000 );  // Easy enough

    // nested vector of ints 1k vectors each with 1k elements
    std::vector<std::vector<ints>> vecInts;
    vecInts.resize( 1000 );
    for ( auto& a : vecInts ) {
        a.resize( 1000 );
    }
    // Again easy enough.
}

Now instead of typing it out like that I would like to use typedefs

#include <vector>

typedef std::vector<int> Ints;
typedef std::vector<Ints> vecInts;   

int main() {
    vecInts a;

    a.resize( 1000 ); // seems okay
    // Assuming this would work...
    for ( auto& n : a ) {
        n.resize( 1000 );
    }
}

My question is does the 2nd code snippet do what is expected and is it equivalent to the 1st code snippet or am I missing something?

Second quick question does 1k * 1k exceed the size limits of std::vector?

Getting a c++11 library on an older version of c++?

A remote machine that I don't own uses gcc 4.1.2 (2007 or so). I'd like to use the random library and its functions, which comes with the c++11 standard. Is there some way I can use the contents of ? Can I dump all of into a custom header?

I lack understanding of libraries and wonder if there's a reasonable workaround for this situation.

C++ reading files into vectors

I am trying to read values from a file to C++ vectors. The file looks like this:

file f1.txt:
1.,2.
3.,4.
5.,6.
7.,8.
9.,10.

I have code in python 3 to read the file and store values in lists.

def main():
    vec1=[]
    vec2=[]
    with open('f1.txt','r') as f1:
        for line1 in f1:
            a=(line1.strip()).split(sep=',')
            vec1.append(float(a[0]))
            vec2.append(float(a[1]))
    print('First vercor : {0} \nSecond vector: {1}'.format(vec1,vec2))    

#

if __name__=='__main__':
    main()

Output:

First vercor : [1.0, 3.0, 5.0, 7.0, 9.0] 
Second vector: [2.0, 4.0, 6.0, 8.0, 10.0]

I want either to import vec1,vec2 in C++ or create C++ code to achieve the same. The importing option is complicated. I took a look at few C++ examples, but couldn't get as effective (short and simple) way as python code has. Can someone suggest a way to achieve this in C++ - especially splitting the string and putting first part into one vector and second part into the other?

Error using std::cref and std::ref

Old compilers for c++11 does not support std::cref and std::ref.... May I know if there is an alternative to these. I am getting below errors..

Error 1 :

/usr/include/boost/concept/detail/has_constraints.hpp:32:62:   [ skipping 8 instantiation contexts, use -ftemplate-backtrace-limit=0 to disable ]

Error 2 :

/usr/include/boost/iterator/transform_iterator.hpp:84:26: error: no matching function for call to ‘std::reference_wrapper<const SequencePair<T_INDEX, T_ELEMENT>::new5() [with T_INDEX = unsigned int; T_ELEMENT = double]::__lambda0>::reference_wrapper()’
     transform_iterator() { }
                          ^
/usr/include/boost/iterator/transform_iterator.hpp:84:26: note: candidates are:
In file included from /usr/include/c++/4.8/memory:79:0,
                 from /usr/include/boost/unordered/unordered_set_fwd.hpp:14,
                 from /usr/include/boost/unordered/unordered_set.hpp:16,
                 from /usr/include/boost/unordered_set.hpp:16,
                 from /usr/include/boost/graph/adjacency_list.hpp:21,
                 from /usr/include/boost/graph/directed_graph.hpp:10,
                 from ../main.cpp:12:
/usr/include/c++/4.8/functional:445:7: note: std::reference_wrapper<_Tp>::reference_wrapper(const std::reference_wrapper<_Tp>&) [with _Tp = const SequencePair<T_INDEX, T_ELEMENT>::new5() [with T_INDEX = unsigned int; T_ELEMENT = double]::__lambda0]
       reference_wrapper(const reference_wrapper<_Tp>& __inref) noexcept
       ^
/usr/include/c++/4.8/functional:445:7: note:   candidate expects 1 argument, 0 provided
/usr/include/c++/4.8/functional:439:7: note: std::reference_wrapper<_Tp>::reference_wrapper(_Tp&) [with _Tp = const SequencePair<T_INDEX, T_ELEMENT>::new5() [with T_INDEX = unsigned int; T_ELEMENT = double]::__lambda0]
       reference_wrapper(_Tp& __indata) noexcept
       ^
/usr/include/c++/4.8/functional:439:7: note:   candidate expects 1 argument, 0 provided
make: *** [main.o] Error 1

Deduce/erase type of template template argument

When using template template arguments how can I have the template type of the template template deduced or erased?

Consider the following SSCCE:

#include <cstdint>
#include <cstddef>
#include <iostream>
using namespace std;

template<int i>
struct Value { };

template<int i>
struct BadValue { };

template<typename... G>
struct Print;

template<template<int> class ValueType, int... Is>
struct Print< ValueType<Is>... > {
    static void print() {
        const int is[] = { Is... };
        for (int i: is)
            cout << i;
        cout << endl;
    }

};

using V1 = Value<1>;
using V2 = Value<2>;
using V3 = Value<3>;
using BV = BadValue<1>;

int main() {
    Print<V2, V1, V2, V3>::print();
    Print<V2, V1, V2, VB>::print(); // <-- Error
}

Deducing the template<int> class ValueType argument of the Print class to a template class like the Value and BadValue classes enforces that all the template arguments in the parameter pack to the Print class are specializations of the same ValueType template class. That is, the second line in the main() function causes a compile-time error as the ValueType argument cannot be deduced to match both the Value and BadValue classes.

The above implementation, however, still has the int type fixed for the inner template argument of the ValueType template template argument. How can I erase it and have it deduced as well?

Generally speaking, when deducing a template template argument, how can I access the inner template argument?

C++ lambda to std::function error with non const strings

The following line gives error in c++ 11:

function<bool(string,string)> comp = [] (string& s1, string& s2) {return s1.length() > s2.length(); };

but this does not:

function<bool(string,string)> comp = [] (const string& s1, const string& s2) {return s1.length() > s2.length(); };

The second call has const in parameters. Any explanation?

Ignore template argument to provide swap function

i want to provide a swap function for my template class. Here's a simplified version:

template <int size, typename...DataTypes>
class ExampleClass
{
public:
   ExampleClass() : data(size) {}
   void swap(ExampleClass& _Right)
   {
      data.swap(_Right);
   }


protected:
   std::vector<std::tuple<Types...>> data;
}

The swap function doesn't work in this case:

ExampleClass<1,int,float> ec1;
ExampleClass<2,int,float> ec2;
ec1.swap(ec2);

If i swap those vectors of tuples outside without using this class it works:

std::vector<std::tuple<int, float> data1(2);
std::vector<std::tuple<int, float> data2(3);
data1.swap(data2);

Is it possible to provide a swap function using the template class i described first?

Using template paramenter pack in function pointer

I want to know how i can use Parameter pack from template as arguments for void function. I try something like this:

template<class... Parametres>
class Function{

void (*function)(Parametres);

}

void Foo(int number){
     //Whatever
}

int main(){

    Function<int> object;

    object.function = Foo;

}

Then you can use the class for calling this function Foo.

Is something like this possible?

Thanks.

Child calls the default contractor of its parent after calling parent's construct with argument

I have following inheritance schema;

class Shader{ [...] }

class Program{ [...] }

class Object : public Shader, public Program{ 
Object::Object(const char * ObjFilePath, const std::string sourcePathVertexShader, const std::string sourcePathFramentShader) : Shader(sourcePathVertexShader, sourcePathFramentShader), Program(this->m_gShader[0], this->m_gShader[1])
{[...]}

}

i.e we are deriving Object class from Shader and Program class, and while initialising the Object class, we are calling the parents' contractors with argument.

Note m_gShader vector is a member in Shader class.

I have traced the code with Xcode, and the code does the thing that it is supposed to do, after calling the parents' constructors with argument, it also calls the same parents' default constructors, which causes all of the member variables of the parents' to reset their value.

Why is this happening ? and how can we prevent this from happening ?

How to get hight (int16) value back to rgb form?

I have int16 * heights[width * height] array, that hold the terrain height, i load them form a file directly as int16 *.

I need to write the heights into a bmp file.

How do i get int16 back into rgb format considering they came form a bmp file (rgb format) in the first place?

Thanks.

Why does the [] notation work with pointers to arrays on the free store? [duplicate]

This question already has an answer here:

int* pd = new int [5];
pd[1] = 10; // now the second element of the array equals 10.

I'm wondering why this notation is allowed, since I've never seen the [] in conjunction with pointers before.

Is it because normal array variables point to their first element, and pointers to arrays do this as well? Which leads me to believe pointers to arrays and arrays themselves are the same thing.

int arr [5];
int* pd = arr; // this statement seems to show how the pointer and the array are identical.

Test Case Failure of vector with size 10

Ratiorg got statues of different sizes as a present from CodeMaster for his birthday, each statue having an non-negative integer size. Since he likes to make things perfect, he wants to arrange them from smallest to largest so that each statue will be bigger than the previous one exactly by 1. He may need some additional statues to be able to accomplish that. Help him figure out the minimum number of additional statues needed.

Example

For statues = [6, 2, 3, 8], the output should be makeArrayConsecutive2(statues) = 3.

This is a problem from codefights. Here is my code written below

#include <iostream>
#include <vector>
#include<algorithm>

using std::vector;

int makeArrayConsecutive2(std::vector <int> statues) {

    vector<int>::size_type size = statues.size();
    sort( statues.begin(), statues.end() );
    int counter = 0;
    for( int i = 0; i<size; i++ )
    {
        int dif =  statues[i+1] - statues[i] - 1; 
        if( dif >= 1 ) {counter+=dif;}
    }
    return counter;
}
int main()
{
  vector<int> c = {1,2,3,4,5,6,7,8,9,10};

  std :: cout<<"You need "<<makeArrayConsecutive2(c)<<" statues"<<std::endl;

  return 0;
}

When I run code with this certain value of vector c it outputs misunderstanding value.All other cases runs correct, but when I declare 10 dimensional vector(I mean vector with 10 values) it doesn't work correct .Could you please explain what's the problem?

samedi 27 janvier 2018

Value semantics with wrapper around polymorphic class: how to avoid copying to const-ref

I've got a common abstract superclass Base, with a variety of Derived classes. For convenience, I'd like to be able to operate on the base class as a value, rather than via pointers. I can achieve this by creating a Wrapper using the technique described in this answer. The Wrapper stores a unique_ptr<Base> and forwards method calls to that pointer, and has appropriate constructors allowing me to do

Derived derived;
Wrapper wrap = derived;
wrap.callMethodOnDerived();

so the user can pass, return, and store Wrapper without thinking about the underlying pointers. Base remains entirely hidden.

However, this ends up creating copies when they don't need to be. I.e

void fun(const Wrapper&);

fun(derived);                  // makes copy
const Wrapper& view = derived; // makes copy

will call the Wrapper(const Derived&) converting constructor, then passes a reference to that. Instead, I'd like it to create a const Wrapper& which points to the original object, with no copy being made. How can I do this?

#include <memory>

using BigVal = int; // Could be some expensive-to-copy type
using namespace std;

struct Base{
    Base(BigVal x) : value(x){
    }

    unique_ptr<Base> clone() const{
        return make_unique<Base>(value);
    }

    BigVal getValue() const{
        return value;
    }
protected:
    BigVal value;
};

struct Derived : public Base{
    Derived(BigVal x) : Base(x){
    }
};

struct Wrapper{
    unique_ptr<Base> ptr_;

    BigVal getValue() const{
        return ptr_->getValue();
    }

    // Ignore missing copy/move assignment operators
    Wrapper(const Wrapper& other){ 
        ptr_ = other.ptr_->clone();
    }

    Wrapper(Wrapper&& other){ 
        ptr_ = move(other.ptr_);
    }

    Wrapper(const Base& other){
        ptr_ = other.clone();
    }  

    Wrapper(Base&& other){
        ptr_ = make_unique<Base>(std::move(other));
    } 
};

void constFun(const Wrapper& t){
    cout<<"Const fun "<<t.getValue()<<endl;
}

int main()
{
    Base b1(1);
    Base b2(2);
    Derived d1(3);

    Wrapper w = b1; // copies

    Wrapper w2 = move(w); // moves
    Wrapper w3 = move(b1); // moves

    // No copy, just taking a reference:
    const Wrapper& w4 = w2; 
    constFun(w2);

    // Can I avoid a copy here?
    const Wrapper& w5 = b2;
    constFun(b2); 
}

I've attempted to fiddle with converting constructors of the form

Base::operator const Wrapper& (){ 
  // return 'view' on this object
} 

But that results in ambiguity when doing Wrapper w = Derived();

Another option could be to make Wrapper never make copies unless you call clone, or lazily make copies when it changes. But is there a way to make copies happen normally during assignment, but not when creating a reference?

Reading from an i string stream

let say we have a line "Christian , 1234, name, James, 2345" how to used I string stream to read the strings in which the name can either be first and last name or the first name. The lines gonna come from a text file which looks like: Christian, 1234, first name last name, 2345 Christian, 247, first name, 5894

Unpacking parameter packs multiple times

Is it possible to unpack a parameter pack more than one time?

For example: I want to get a tuple containing 4 vectors - 2 of type int and 2 of type float. To create such a tuple I want to use the syntax as follows:

ExampleClass<2, int, float> class;

Is it possible to create such a class? I'm thinking about something like this:

template <int numUnpacks, typename ... Types>
class ExampleClass
{
     using Types = std::tuple<std::vector<Types>...>; // here i don't know how to unpack "std::vector<Types>...>" as often as "numUnpacks">
}