lundi 31 août 2020

C++ What atomic operations we can use on trival user defined data type

I am trying to understand std::atomic types and atomic operations. Below is my code:

#include <atomic>
#include <iostream>

class A
{
public:
    int x;
    void Show() {}
};

int main()
{
    std::atomic<A> fooA;
    // fooA.Show(); -- gives me std::atomic<A> has no member Show()
}

What are the atomic operations we can do when we define a user type - like Mtype.load() etc - how can we use Mtype with load() atomic operations - where load atomically obtains the value of the atomic object?

I encountered a problem about c++ with opencv

error: expected identifier before ‘int’

#define INT int

my code :

#define BYTE unsigned char
#define CHAR char
#define UCHAR unsigned char
#define UINT unsigned int
#define DWORD unsigned int
#define PVOID void*
#define ULONG unsigned int

i don't know how to deal with it

assign a templated variable at runtime

I have some code that worked great until now but there is a new change that is breaking it. Looking for ideas on how to deal with it. I am not a C++ template expert and have basic working knowledge.

namespace foo {
enum {
ITEM0,
ITEM1,
..
ITEMN
};

constexpr int A = 
#if defined(SOME_DEFINE1)
A1,
#elif defined(SOME_DEFINE2)
A2,
...
#elif defined(SOME_DEFINEN)
AN
#endif
;

// Then I have some variables that depend on A
template<int> struct var1;
template<>struct var1<A1> { static constexpr auto value = v1; }
template<>struct var1<A2> { static constexpr auto value = v2; }
template<>struct var1<A3> { static constexpr auto value = v3; }

template<int> struct var2;
template<>struct var2<A1> { static constexpr auto value = x1; }
template<>struct var2<A2> { static constexpr auto value = x2; }
template<>struct var2<A3> { static constexpr auto value = x3; }
} // namespace foo

constexpr auto VAR1 = foo::var1<foo::A>::value;
constexpr auto VAR2 = foo::var2<foo::A>::value;

now VAR1 and VAR2 are used in multiple places. I understand that all of this code will be optimized by the compiler and things work.

Now because of the new change I can only know the value of 'A' at runtime and as a result cannot declare is at constant anymore. A will be determined from a value of a global variable somewhere. Any ideas on how to implement this so I make very minimal changes to my code.

Let us say there is a gVal which can be 1,2 or 3 and based on that I want to set A to be A1,A2 or A3 which affect the values of other variables. Any help is greatly appreciated.

Variadic Template Expansion - expand all except the i-th entry

Is there a way to remove one of the types from type expansion?

Let's use tuple as an example,

void foo() {
     tuple<int, double, string> t;
     // some facility to expand except the i-th type:
     expand_except_ith<0>(t);   // returns tuple<double, string>
     expand_except_ith<1>(t);   // returns tuple<int, string>
}

fork() vs std::async in C++

I am new to concepts of asyc and fork, what I understood till now is that the fork() creates chid processes which will run asynchronously. And the std::async will create a thread from the system pool and launch it asynchronously here if I mention std::launch::async.

For instance how does below set of code differs? 1: using std::async

std::vector<std::future<void>> result;
for(i=0;i<5;i++){
    result. push_back(std::async(std::launch::asyc, foo, var1));
}

for( auto e : result) 
    e.get();

2nd: Using fork()

for(i=0;i<5;i++){ 
    if(fork()==0){
        foo(var1);
        exit(0);
    }
}

Assume the foo function return type is void, and the arguments are passed as reference or pointers.

How to copy a string to other string ignoring cases? [duplicate]

I want to change all the characters to lowercase in a string and copy it to another string.I tried the below approach in c++ but not working as expected. It is returning the string before a whitespace.

#include<bits/stdc++.h>
using namespace std;
int main()
{
    string s,t="";
    cin>>s;
    for(int i=0;i<s.size();i++){
        t+=tolower(s[i]);
    }
    cout<<t<<"\n";
    return 0;
}

For example if i give the input string "HELLO WORLD", giving result only "hello". Ignoring anything after space.

Is there any way to solve this is C++?

Non-template function declared in header for use in template function causing /bin/ld: DWARF error: could not find variable specification

Thank you for taking the time too look at this question. I have searched for answers to this problem but it's difficult to find an answer when you don't know exactly what to search for.

I want to use a function declared in the header file in a template function declared in the same file. I have two files, a header and source file. The non-template function is defined in a cpp file. For some reason though this causes. This is a simplified example of the functions causing the issue. Please let me know if you need anymore information and thanks for any insight in advance.

Note, dropping the code from the function defined in func.cpp into the template function directly allows it to compile and run. The issue with that is the length that my function would reach if I can't define other functions to be used inside the template function. It would be a giant mess that I am trying to avoid.

func.h:

void getDerivative(std::map<std::string,double> comp, double* omega,std::map<std::string,size_t> indexMap);

template<class MATTYPE> void Precondition(Matrix<MATTYPE> *preconditioner)
{
  double* omega = new double[numberOfEquations];
  std::map<std::string,double> comp = getComp(); //Included function to get comp
  getOmega(omega); //Included function to get omega
  std::map<std::string,size_t> indexMap = getIndexMap(); //Included function to get index map
  getDerivative(comp,omega,indexMap);
  .
  .
}

func.cpp

void getDerivative(Composition comp, double* omega,std::map<std::string,size_t> indexMap)
{ 
  //flattened index for derivatives
  size_t idx; 
  
  for (std::map<std::string,double>::iterator iter1 = comp.begin(); iter1 != comp.end(); iter1++) //Independent variable
    {
      for (std::map<std::string,double>::iterator iter2 = comp.begin(); iter2 != comp.end(); iter2++) //Dependent variable
      {
        idx = indexMap[iter1->first]+indexMap[iter2->first]*indexMap.size();
        std::cout<<idx<<std::endl;
      }
    }
}

The error error

/bin/ld: /bin/ld: DWARF error: could not find variable specification at offset 2045
/bin/ld: DWARF error: could not find variable specification at offset 209e
.
.
.
undefined reference to getDerivative(std::map<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, double, std::less<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const, double> > >, double*, std::map<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, unsigned long, std::less<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const, unsigned long> > >)
collect2: error: ld returned 1 exit status
scons: *** [dev-test] Error 1
scons: building terminated because of errors.

Will compiler unroll "for" loop when iterating a const container?

In C++11, we can use a much simpler "for" loop when iterating a container like the following:

for (auto i : {1, 2, 3, 4})
    ...;

However, I don't know the efficiency of such code. Specifically:

  • What is the type of {1, 2, 3, 4}? It is an raw array, or converted to other containers such as std::vector?
  • Will compiler unroll the loop?

Update: Suppose we are using -O2, and the codes in the loop are only a few operations. As my case, I want to enumarate four directions UP DOWN LEFT RIGHT and call a function with the direction parameter. I just care if the program can have the best performance.

Thank you very much!

how to find missing library dependency(or root cause) in static library and when cmake target is built using externalproject method

I want to use static target for jaeger instead of linking to a dynamic target, static target compiles fine but when I use it in my codebase, I see undefined reference errors: tried:

  1. dynamic/static linking for thrift explicitly to ceph(primary codebase):
[100%] Linking CXX executable ../bin/ceph-osd
/usr/bin/ld: jaeger/lib/libjaegertracing.a(UDPTransporter.cpp.o): in function `apache::thrift::transport::TTransportException::TTransportException(apache::thrift::transport::TTransportException::TTransportExceptionType, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)':
UDPTransporter.cpp:(.text._ZN6apache6thrift9transport19TTransportExceptionC2ENS2_23TTransportExceptionTypeERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE[_ZN6apache6thrift9transport19TTransportExceptionC5ENS2_23TTransportExceptionTypeERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE]+0x2d): undefined reference to `vtable for apache::thrift::transport::TTransportException'
/usr/bin/ld: jaeger/lib/libjaegertracing.a(UDPTransporter.cpp.o): in function `apache::thrift::transport::TTransportException::~TTransportException()':
UDPTransporter.cpp:(.text._ZN6apache6thrift9transport19TTransportExceptionD2Ev[_ZN6apache6thrift9transport19TTransportExceptionD5Ev]+0x13): undefined reference to `vtable for apache::thrift::transport::TTransportException'
/usr/bin/ld: jaeger/lib/libjaegertracing.a(UDPTransporter.cpp.o): in function `apache::thrift::transport::TTransport::open()':
UDPTransporter.cpp:(.text._ZN6apache6thrift9transport10TTransport4openEv[_ZN6apache6thrift9transport10TTransport4openEv]+0x8b): undefined reference to `typeinfo for apache::thrift::transport::TTransportException'
/usr/bin/ld: jaeger/lib/libjaegertracing.a(UDPTransporter.cpp.o): in function `apache::thrift::transport::TTransport::close()':
UDPTransporter.cpp:(.text._ZN6apache6thrift9transport10TTransport5closeEv[_ZN6apache6thrift9transport10TTransport5closeEv]+0x8b): undefined reference to `typeinfo for apache::thrift::transport::TTransportException'
/usr/bin/ld: jaeger/lib/libjaegertracing.a(UDPTransporter.cpp.o): in function `apache::thrift::transport::TTransport::read_virt(unsigned char*, unsigned int)':
UDPTransporter.cpp:(.text._ZN6apache6thrift9transport10TTransport9read_virtEPhj[_ZN6apache6thrift9transport10TTransport9read_virtEPhj]+0x92): undefined reference to `typeinfo for apache::thrift::transport::TTransportException'
/usr/bin/ld: jaeger/lib/libjaegertracing.a(UDPTransporter.cpp.o): in function `apache::thrift::transport::TTransport::write_virt(unsigned char const*, unsigned int)':
UDPTransporter.cpp:(.text._ZN6apache6thrift9transport10TTransport10write_virtEPKhj[_ZN6apache6thrift9transport10TTransport10write_virtEPKhj]+0x92): undefined reference to `typeinfo for apache::thrift::transport::TTransportException'
/usr/bin/ld: jaeger/lib/libjaegertracing.a(UDPTransporter.cpp.o): in function `apache::thrift::transport::TTransport::consume_virt(unsigned int)':
UDPTransporter.cpp:(.text._ZN6apache6thrift9transport10TTransport12consume_virtEj[_ZN6apache6thrift9transport10TTransport12consume_virtEj]+0x8e): undefined reference to `typeinfo for apache::thrift::transport::TTransportException'
/usr/bin/ld: jaeger/lib/libjaegertracing.a(UDPTransporter.cpp.o): in function `apache::thrift::protocol::TProtocol::TProtocol(std::shared_ptr<apache::thrift::transport::TTransport>)':
UDPTransporter.cpp:(.text._ZN6apache6thrift8protocol9TProtocolC2ESt10shared_ptrINS0_9transport10TTransportEE[_ZN6apache6thrift8protocol9TProtocolC5ESt10shared_ptrINS0_9transport10TTransportEE]+0x17): undefined reference to `vtable for apache::thrift::protocol::TProtocol'
/usr/bin/ld: jaeger/lib/libjaegertracing.a(UDPTransporter.cpp.o): in function `apache::thrift::protocol::TProtocolFactory::TProtocolFactory()':
UDPTransporter.cpp:(.text._ZN6apache6thrift8protocol16TProtocolFactoryC2Ev[_ZN6apache6thrift8protocol16TProtocolFactoryC5Ev]+0xf): undefined reference to `vtable for apache::thrift::protocol::TProtocolFactory'
/usr/bin/ld: jaeger/lib/libjaegertracing.a(UDPTransporter.cpp.o): in function `apache::thrift::transport::TBufferBase::consume(unsigned int)':
UDPTransporter.cpp:(.text._ZN6apache6thrift9transport11TBufferBase7consumeEj[_ZN6apache6thrift9transport11TBufferBase7consumeEj]+0xe4): undefined reference to `typeinfo for apache::thrift::transport::TTransportException'
/usr/bin/ld: jaeger/lib/libjaegertracing.a(UDPTransporter.cpp.o): in function `apache::thrift::transport::TMemoryBuffer::TMemoryBuffer(unsigned int)':
UDPTransporter.cpp:(.text._ZN6apache6thrift9transport13TMemoryBufferC2Ej[_ZN6apache6thrift9transport13TMemoryBufferC5Ej]+0x23): undefined reference to `vtable for apache::thrift::transport::TMemoryBuffer'
/usr/bin/ld: jaeger/lib/libjaegertracing.a(UDPTransporter.cpp.o): in function `unsigned int apache::thrift::transport::readAll<apache::thrift::transport::TTransport>(apache::thrift::transport::TTransport&, unsigned char*, unsigned int)':
UDPTransporter.cpp:(.text._ZN6apache6thrift9transport7readAllINS1_10TTransportEEEjRT_Phj[_ZN6apache6thrift9transport7readAllINS1_10TTransportEEEjRT_Phj]+0xd6): undefined reference to `typeinfo for apache::thrift::transport::TTransportException'
/usr/bin/ld: jaeger/lib/libjaegertracing.a(UDPTransporter.cpp.o): in function `unsigned int apache::thrift::transport::readAll<apache::thrift::transport::TBufferBase>(apache::thrift::transport::TBufferBase&, unsigned char*, unsigned int)':
UDPTransporter.cpp:(.text._ZN6apache6thrift9transport7readAllINS1_11TBufferBaseEEEjRT_Phj[_ZN6apache6thrift9transport7readAllINS1_11TBufferBaseEEEjRT_Phj]+0xd6): undefined reference to `typeinfo for apache::thrift::transport::TTransportException'
/usr/bin/ld: jaeger/lib/libjaegertracing.a(UDPTransporter.cpp.o): in function `apache::thrift::protocol::TCompactProtocolFactoryT<apache::thrift::transport::TTransport>::~TCompactProtocolFactoryT()':
UDPTransporter.cpp:(.text._ZN6apache6thrift8protocol24TCompactProtocolFactoryTINS0_9transport10TTransportEED2Ev[_ZN6apache6thrift8protocol24TCompactProtocolFactoryTINS0_9transport10TTransportEED5Ev]+0x2a): undefined reference to `apache::thrift::protocol::TProtocolFactory::~TProtocolFactory()'
/usr/bin/ld: jaeger/lib/libjaegertracing.a(UDPTransporter.cpp.o):(.data.rel.ro._ZTVN6apache6thrift8protocol17TProtocolDefaultsE[_ZTVN6apache6thrift8protocol17TProtocolDefaultsE]+0x170): undefined reference to `apache::thrift::protocol::TProtocol::skip_virt(apache::thrift::protocol::TType)'
/usr/bin/ld: jaeger/lib/libjaegertracing.a(UDPTransporter.cpp.o):(.data.rel.ro._ZTIN6apache6thrift8protocol24TCompactProtocolFactoryTINS0_9transport10TTransportEEE[_ZTIN6apache6thrift8protocol24TCompactProtocolFactoryTINS0_9transport10TTransportEEE]+0x10): undefined reference to `typeinfo for apache::thrift::protocol::TProtocolFactory'
/usr/bin/ld: jaeger/lib/libjaegertracing.a(UDPTransporter.cpp.o):(.data.rel.ro._ZTIN6apache6thrift8protocol17TProtocolDefaultsE[_ZTIN6apache6thrift8protocol17TProtocolDefaultsE]+0x10): undefined reference to `typeinfo for apache::thrift::protocol::TProtocol'
/usr/bin/ld: jaeger/lib/libjaegertracing.a(UDPTransporter.cpp.o): in function `apache::thrift::protocol::TProtocolDefaults::~TProtocolDefaults()':
UDPTransporter.cpp:(.text._ZN6apache6thrift8protocol17TProtocolDefaultsD2Ev[_ZN6apache6thrift8protocol17TProtocolDefaultsD5Ev]+0x2a): undefined reference to `apache::thrift::protocol::TProtocol::~TProtocol()'
/usr/bin/ld: jaeger/lib/libjaegertracing.a(HTTPTransporter.cpp.o): in function `jaegertracing::utils::HTTPTransporter::HTTPTransporter(jaegertracing::net::URI const&, int)':
HTTPTransporter.cpp:(.text+0x19f): undefined reference to `apache::thrift::transport::THttpClient::THttpClient(std::shared_ptr<apache::thrift::transport::TTransport>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
/usr/bin/ld: jaeger/lib/libjaegertracing.a(HTTPTransporter.cpp.o): in function `apache::thrift::protocol::TBinaryProtocolFactoryT<apache::thrift::transport::TTransport, apache::thrift::protocol::TNetworkBigEndian>::~TBinaryProtocolFactoryT()':
HTTPTransporter.cpp:(.text._ZN6apache6thrift8protocol23TBinaryProtocolFactoryTINS0_9transport10TTransportENS1_17TNetworkBigEndianEED2Ev[_ZN6apache6thrift8protocol23TBinaryProtocolFactoryTINS0_9transport10TTransportENS1_17TNetworkBigEndianEED5Ev]+0x2a): undefined reference to `apache::thrift::protocol::TProtocolFactory::~TProtocolFactory()'
/usr/bin/ld: jaeger/lib/libjaegertracing.a(HTTPTransporter.cpp.o):(.data.rel.ro._ZTIN6apache6thrift8protocol23TBinaryProtocolFactoryTINS0_9transport10TTransportENS1_17TNetworkBigEndianEEE[_ZTIN6apache6thrift8protocol23TBinaryProtocolFactoryTINS0_9transport10TTransportENS1_17TNetworkBigEndianEEE]+0x10): undefined reference to `typeinfo for apache::thrift::protocol::TProtocolFactory'
/usr/bin/ld: jaeger/lib/libjaegertracing.a(ThriftSender.cpp.o): in function `apache::thrift::transport::TMemoryBuffer::TMemoryBuffer()':
ThriftSender.cpp:(.text._ZN6apache6thrift9transport13TMemoryBufferC2Ev[_ZN6apache6thrift9transport13TMemoryBufferC5Ev]+0x20): undefined reference to `vtable for apache::thrift::transport::TMemoryBuffer'
/usr/bin/ld: jaeger/lib/libjaegertracing.a(Agent.cpp.o): in function `jaegertracing::agent::thrift::AgentProcessor::dispatchCall(apache::thrift::protocol::TProtocol*, apache::thrift::protocol::TProtocol*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, int, void*)':
Agent.cpp:(.text+0x1037): undefined reference to `apache::thrift::TApplicationException::write(apache::thrift::protocol::TProtocol*) const'
/usr/bin/ld: jaeger/lib/libjaegertracing.a(Agent.cpp.o): in function `jaegertracing::agent::thrift::AgentConcurrentClient::send_emitZipkinBatch(std::vector<twitter::zipkin::thrift::Span, std::allocator<twitter::zipkin::thrift::Span> > const&)':
Agent.cpp:(.text+0x1b32): undefined reference to `apache::thrift::async::TConcurrentSendSentry::TConcurrentSendSentry(apache::thrift::async::TConcurrentClientSyncInfo*)'
/usr/bin/ld: Agent.cpp:(.text+0x1c63): undefined reference to `apache::thrift::async::TConcurrentSendSentry::commit()'
/usr/bin/ld: Agent.cpp:(.text+0x1c7b): undefined reference to `apache::thrift::async::TConcurrentSendSentry::~TConcurrentSendSentry()'
/usr/bin/ld: Agent.cpp:(.text+0x1d04): undefined reference to `apache::thrift::async::TConcurrentSendSentry::~TConcurrentSendSentry()'
/usr/bin/ld: jaeger/lib/libjaegertracing.a(Agent.cpp.o): in function `jaegertracing::agent::thrift::AgentConcurrentClient::send_emitBatch(jaegertracing::thrift::Batch const&)':
Agent.cpp:(.text+0x1da4): undefined reference to `apache::thrift::async::TConcurrentSendSentry::TConcurrentSendSentry(apache::thrift::async::TConcurrentClientSyncInfo*)'
/usr/bin/ld: Agent.cpp:(.text+0x1ed5): undefined reference to `apache::thrift::async::TConcurrentSendSentry::commit()'
/usr/bin/ld: Agent.cpp:(.text+0x1eed): undefined reference to `apache::thrift::async::TConcurrentSendSentry::~TConcurrentSendSentry()'
/usr/bin/ld: Agent.cpp:(.text+0x1f76): undefined reference to `apache::thrift::async::TConcurrentSendSentry::~TConcurrentSendSentry()'
/usr/bin/ld: jaeger/lib/libjaegertracing.a(Agent.cpp.o): in function `apache::thrift::TDispatchProcessor::process(std::shared_ptr<apache::thrift::protocol::TProtocol>, std::shared_ptr<apache::thrift::protocol::TProtocol>, void*)':
Agent.cpp:(.text._ZN6apache6thrift18TDispatchProcessor7processESt10shared_ptrINS0_8protocol9TProtocolEES5_Pv[_ZN6apache6thrift18TDispatchProcessor7processESt10shared_ptrINS0_8protocol9TProtocolEES5_Pv]+0x7e): undefined reference to `apache::thrift::GlobalOutput'
/usr/bin/ld: Agent.cpp:(.text._ZN6apache6thrift18TDispatchProcessor7processESt10shared_ptrINS0_8protocol9TProtocolEES5_Pv[_ZN6apache6thrift18TDispatchProcessor7processESt10shared_ptrINS0_8protocol9TProtocolEES5_Pv]+0x8b): undefined reference to `apache::thrift::TOutput::printf(char const*, ...)'
/usr/bin/ld: jaeger/lib/libjaegertracing.a(Agent.cpp.o): in function `apache::thrift::concurrency::Mutex::~Mutex()':
Agent.cpp:(.text._ZN6apache6thrift11concurrency5MutexD2Ev[_ZN6apache6thrift11concurrency5MutexD5Ev]+0x13): undefined reference to `vtable for apache::thrift::concurrency::Mutex'

  1. tried changing the order of thrift static library linking.
  2. HINT: the static target created by Project's CMake works fine with example code, but I don't know how to test that target when it has been built as ExternalProject(CMake), can I in some way do this?

on using **nm -uC libjaegertracing.a** gives hint for missing definitions, but I don't know why it is not getting included in the static file, while when I link to static target for example code(standalone) not with code I want to link it with, everything works fine. I want to know how can I know and include missing library/definition so that I don't get these errors while trying to use a manually created target with libjaegertracing.a

U jaegertracing::thrift::Tag::Tag(jaegertracing::thrift::Tag const&)
                 U jaegertracing::thrift::Tag::~Tag()
                 U jaegertracing::thrift::Span::Span(jaegertracing::thrift::Span const&)
                 U jaegertracing::thrift::Span::~Span()
                 U jaegertracing::thrift::Batch::__set_spans(std::vector<jaegertracing::thrift::Span, std::allocator<jaegertracing::thrift::Span> > const&)
                 U jaegertracing::thrift::Batch::__set_process(jaegertracing::thrift::Process const&)
                 U jaegertracing::thrift::Batch::~Batch()
                 U jaegertracing::thrift::Process::__set_tags(std::vector<jaegertracing::thrift::Tag, std::allocator<jaegertracing::thrift::Tag> > const&)
                 U jaegertracing::thrift::Process::~Process()
                 U jaegertracing::Tag::thrift(jaegertracing::thrift::Tag&) const
                 U jaegertracing::Span::thrift(jaegertracing::thrift::Span&) const
                 U std::runtime_error::what() const
                 U std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::c_str() const
                 U std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::empty() const
                 U std::__cxx11::basic_ostringstream<char, std::char_traits<char>, std::allocator<char> >::str() const
                 U std::allocator<char>::allocator()
                 U std::allocator<char>::~allocator()
                 U std::ostream::operator<<(int)
                 U std::runtime_error::runtime_error(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)
                 U std::runtime_error::~runtime_error()
                 U std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::operator=(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)
                 U std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&)
                 U std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)
                 U std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string()
                 U std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()
                 U std::__cxx11::basic_ostringstream<char, std::char_traits<char>, std::allocator<char> >::basic_ostringstream()
                 U std::__cxx11::basic_ostringstream<char, std::char_traits<char>, std::allocator<char> >::~basic_ostringstream()
                 U std::ios_base::Init::Init()
                 U std::ios_base::Init::~Init()
                 U std::bad_alloc::~bad_alloc()
                 U std::exception::~exception()
                 U operator new(unsigned long)

also to verify whether I had the dependency library compiled to build static library, I used:

$ ar t libjaegertracing.a

which gave the complied files as expected:

Config.cpp.o
DynamicLoad.cpp.o
LogRecord.cpp.o
Logging.cpp.o
Reference.cpp.o
Span.cpp.o
SpanContext.cpp.o
Tag.cpp.o
TraceID.cpp.o
Tracer.cpp.o
TracerFactory.cpp.o
Sender.cpp.o
ThriftSender.cpp.o
BaggageSetter.cpp.o
RemoteRestrictionJSON.cpp.o
RemoteRestrictionManager.cpp.o
Restriction.cpp.o
RestrictionManager.cpp.o
RestrictionsConfig.cpp.o
Counter.cpp.o
Gauge.cpp.o
InMemoryStatsReporter.cpp.o
Metric.cpp.o
Metrics.cpp.o
NullCounter.cpp.o
NullGauge.cpp.o
NullStatsFactory.cpp.o
NullStatsReporter.cpp.o
NullTimer.cpp.o
StatsFactory.cpp.o
StatsFactoryImpl.cpp.o
StatsReporter.cpp.o
Timer.cpp.o
IPAddress.cpp.o
Socket.cpp.o
URI.cpp.o
Error.cpp.o
Header.cpp.o
Method.cpp.o
Request.cpp.o
Response.cpp.o
Endian.cpp.o
Hostname.cpp.o
Extractor.cpp.o
HeadersConfig.cpp.o
Injector.cpp.o
Propagator.cpp.o
CompositeReporter.cpp.o
Config.cpp.o
InMemoryReporter.cpp.o
LoggingReporter.cpp.o
NullReporter.cpp.o
RemoteReporter.cpp.o
Reporter.cpp.o
AdaptiveSampler.cpp.o
Config.cpp.o
ConstSampler.cpp.o
GuaranteedThroughputProbabilisticSampler.cpp.o
ProbabilisticSampler.cpp.o
RateLimitingSampler.cpp.o
RemoteSamplingJSON.cpp.o
RemotelyControlledSampler.cpp.o
Sampler.cpp.o
SamplingStatus.cpp.o
Agent.cpp.o
AggregationValidator.cpp.o
BaggageRestrictionManager.cpp.o
Collector.cpp.o
Dependency.cpp.o
SamplingManager.cpp.o
ZipkinCollector.cpp.o
agent_constants.cpp.o
agent_types.cpp.o
aggregation_validator_constants.cpp.o
aggregation_validator_types.cpp.o
baggage_constants.cpp.o
baggage_types.cpp.o
dependency_constants.cpp.o
dependency_types.cpp.o
jaeger_constants.cpp.o
jaeger_types.cpp.o
sampling_constants.cpp.o
sampling_types.cpp.o
zipkincore_constants.cpp.o
zipkincore_types.cpp.o
ErrorUtil.cpp.o
HexParsing.cpp.o
EnvVariable.cpp.o
RateLimiter.cpp.o
UDPTransporter.cpp.o
HTTPTransporter.cpp.o
YAML.cpp.o
ThriftMethods.cpp.o

c++ thread worker failure under high load

I have been working on a idea for a system where I can have many workers that are triggered on a regular basis by a a central timer class. The part I'm concerned about here is a TriggeredWorker which, in a loop, uses the mutex & conditionVariable approach to wait to be told to do work. It has a method trigger that is called (by a different thread) that triggers work to be done. It is an abstract class that has to be subclassed for the actual work method to be implemented.

I have a test that shows that this mechanism works. However, as I increase the load by reducing the trigger interval, the test starts to fail. When I delay 20 microseconds between triggers, the test is 100% reliable. As I reduce down to 1 microsecond, I start to get failures in that the count of work performed reduces from 1000 (expected) to values like 986, 933, 999 etc..

My questions are: (1) what is it that is going wrong and how can I capture what is going wrong so I can report it or do something about it? And, (2) is there some better approach that I could use that would be better? I have to admit that my experience with c++ is limited to the last 3 months, although I have worked with other languages for several years.

Many thanks for reading...

Here are the key bits of code:

Triggered worker header file:

#ifndef TIMER_TRIGGERED_WORKER_H
#define TIMER_TRIGGERED_WORKER_H

#include <thread>
#include <plog/Log.h>

class TriggeredWorker {
private:
    std::mutex mutex_;
    std::condition_variable condVar_;
    std::atomic<bool> running_{false};
    std::atomic<bool> ready_{false};

    void workLoop();
protected:
    virtual void work() {};
public:
    void start();
    void stop();
    void trigger();
};

#endif //TIMER_TRIGGERED_WORKER_H

Triggered worker implementation:

#include "TriggeredWorker.h"

void TriggeredWorker::workLoop() {
    PLOGD << "workLoop started...";

    while(true) {
        std::unique_lock<std::mutex> lock(mutex_);
        condVar_.wait(lock, [this]{
            bool ready = this->ready_;
            bool running = this->running_;
            return ready | !running; });
        this->ready_ = false;

        if (!this->running_) {
            break;
        }

        PLOGD << "Calling work()...";
        work();

        lock.unlock();
        condVar_.notify_one();
    }

    PLOGD << "Worker thread completed.";
}

void TriggeredWorker::start() {
    PLOGD << "Worker start...";
    this->running_ = true;
    auto thread = std::thread(&TriggeredWorker::workLoop, this);
    thread.detach();
}

void TriggeredWorker::stop() {
    PLOGD << "Worker stop.";
    this->running_ = false;
}

void TriggeredWorker::trigger() {
    PLOGD << "Trigger.";
    std::unique_lock<std::mutex> lock(mutex_);
    ready_ = true;
    lock.unlock();
    condVar_.notify_one();
}

and the test:

#include "catch.hpp"
#include "TriggeredWorker.h"
#include <thread>

TEST_CASE("Simple worker performs work when triggered") {
    static std::atomic<int> twt_count{0};

    class SimpleTriggeredWorker : public TriggeredWorker {
    protected:
        void work() override {
            PLOGD << "Incrementing counter.";
            twt_count.fetch_add(1);
        }
    };

    SimpleTriggeredWorker worker;

    worker.start();

    for (int i = 0; i < 1000; i++) {
        worker.trigger();
        std::this_thread::sleep_for(std::chrono::microseconds(20));
    }

    std::this_thread::sleep_for(std::chrono::seconds(1));

    CHECK(twt_count == 1000);

    std::this_thread::sleep_for(std::chrono::seconds(1));
    worker.stop();
}

runtime error: addition of unsigned offset to 0x7ffeba23a6e0

Here is my code, I wrote it on leetcode platform

const int N1 = 100+1;
const int N2 = 10e4+1;
class Solution {
public:
    bool cache[N1][N2];
    bool isSubsequence(string s, string t) {
        int n1 = s.size();
        int n2 = t.size();
        for(int i=0; i<=n1; i++) {
            for(int j=0; j<=n2; j++) {
                if(i == 0)
                    cache[i][j] = true;
                if(j == 0)
                    cache[i][j] = false;
                if(s[i-1] == t[j-1])
                    cache[i][j] = cache[i-1][j-1];
                else
                    cache[i][j] = cache[i][j-1];
            }
        }
        return cache[n1][n2];
    }
};

It gives following error, I don't know why. Please help. error image

EDIT: (Solved issue):

if(i == 0)
   cache[i][j] = true;
else if(j == 0)
   cache[i][j] = false;
else if(s[i-1] == t[j-1])
   cache[i][j] = cache[i-1][j-1];
else
   cache[i][j] = cache[i][j-1];
};

How to debug if a constexpr function doesn't run on compile time?

For example I have a constexpr function, but I use a runtime variable (not marked as constexpr) to take the return value. In this case, I'm not sure whether the function runs on compile time or runtime, So is there any way to debug?

At first I thinked about static_assert, but it looks like static_assert cannot do this. Then I thought convert the code to assembly code, but it is way too difficult to check the assembly code to figure out.

dimanche 30 août 2020

Fractional knapsack problem : I'm unable to pass the 6th test case at Coursera .I'm getting more answer than the correct answer?

This is a C++ Program to solve fractional knapsack. The knapsack problem or rucksack problem is a problem in combinatorial optimization: Given a set of items, each with a mass and a value, determine the number of each item to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible. It derives its name from the problem faced by someone who is constrained by a fixed-size knapsack and must fill it with the most valuable items.

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
double bag( double w, vector<double> values,vector<double> weights, vector<double> vv){
    double index, ma;
    double W1=0.0;
    double V=0.0;
    while(!values.empty())
    {
ma=*max_element(vv.begin(), vv.end())   ;
auto it = find(vv.begin(), vv.end(), ma);
index = distance(vv.begin(),it);
//cout<<index<<endl;

if(w-W1>=weights[index] )
{
V=V+values[index];
W1=W1+weights[index];
}

else if(w-W1<weights[index]&&w-W1>0)
{
    V=V+vv[index]*(w-W1);
    }
    weights.erase(std::next(weights.begin(), std::distance(vv.begin(), it)));
values.erase(std::next(values.begin(), std::distance(vv.begin(), it)));
vv.erase(it);
    }
    return V;
}
int main() {
  int n;
  double w;
  double ans;
  std::cin >> n >> w;
  vector<double> values(n);
  vector<double> weights(n);
  vector<double> vv(n);
  for (int i = 0; i < n; i++) {
    std::cin >> values[i] >> weights[i];
    vv[i]=values[i]/weights[i];
  }
    ans = bag(w,values,weights,vv);
    cout<<ans;
}
    

What is the common idiom(s) for resetting the moved object?

In C++ move constructor is required to reset the moved object which to me seems to be a duplication of what the destructor does in most of the cases.

Is it correct that defining a reset-method and using it in both destructor and move-constructor is the best approach? Or maybe there are better ways?

deque unable to insert after erase

Why does this not work as expected?

Output: a

Expected Output: a c

I'm assuming that erase should return a valid iterator which I can use to insert more elements. If I add more inserts, I get duplicates of the first element.

#include <iostream>
#include <deque>

using namespace std;

int main()
{
    deque<char> tempQueue ;
    deque<char>::iterator it = tempQueue.begin();
    char temp = 'a';
    
    it = tempQueue.insert(it, temp);
    it++;
    
    temp = 'b';
    it = tempQueue.insert(it, temp);
    it++;
    
    it = tempQueue.erase(it);
    
    temp = 'c';
    it = tempQueue.insert(it, temp);
    it++;
    
    for (deque<char>::iterator tempIt = tempQueue.begin(); tempIt != tempQueue.end(); tempIt++)
    {
        cout << *tempIt << "\t";
    }
    
    return 0;
}

Why in C++11 or C++14 standards compiler implicitly deletes my explicitly declared copy assignment operator when I declare move assignment operator?

I wanted to create list data structure with iterator class in it. Everything works good but when I declare move assignment operator the program doesn't compile if it's C++14 or C++11 standards but works fine in C++17, C++2a.

list.h:

#pragma once

#include <iostream>

template <typename T>
class list {
    struct node {
        node(T data, node* prev = nullptr, node* next = nullptr)
            : data{ data }, prev{ prev }, next{ next } {}
        
        T data;
        node* prev;
        node* next;
    };
public:
    struct iterator {
        template <typename>
        friend class list;

        explicit iterator(node *_node = nullptr) 
            : _node(_node) {}

        iterator& operator=(iterator const &it) {
            _node = it._node;
        
            return *this;
        }
       
        iterator& operator=(iterator &&it) {
            // does nothing
            return *this;
        }

        T& operator*() {
            return _node->data;
        }

    private:
        node *_node;
    };

    list(T data) {
        Head = Tail = new node(data);

        size = 1;
    }

    iterator begin() {
        return iterator(Head);
    }
private:
    node* Head;
    node* Tail;

    int size;
};

main.cpp:

#include "list.h"

int main() {

    list<int> lst(100);

    std::cout << *lst.begin() << std::endl;

}

It's a stripped down version but it's enough to describe the problem.

Compiler error and note message:

error: use of deleted function ‘constexpr list::iterator::iterator(const list::iterator&)’
     return iterator(Head);
                         ^

note: ‘constexpr list::iterator::iterator(const list::iterator&)’ is implicitly declared as
       deleted because ‘list::iterator’ declares a move constructor or move assignment operator
     struct iterator {
        ^~~~~~~~

samedi 29 août 2020

using C++11 templates to generate multiple versions of an algorithm

Say I'm making a general-purpose collection of some sort, and there are 4-5 points where a user might want to choose implementation A or B. For instance:

  • homogenous or heterogenous
  • do we maintain a count of the contained objects, which is slower
  • do we have it be thread-safe or not

I could just make 16 or 32 implementations, with each combination of features, but obviously this won't be easy to write or maintain.

I could pass in boolean flags to the constructor, that the class could check before doing certain operations. However, the compiler doesn't "know" what those arguments were so has to check them every time, and just checking enough boolean flags itself imposes a performance penalty.

So I'm wondering if template arguments can somehow be used so that at compile time the compiler sees if (false) or if (true) and therefore can completely optimize out the condition test, and if false, the conditional code. I've only found examples of templates as types, however, not as compile-time constants.

The main goal would be to utterly eliminate those calls to lock mutexes, increment and decrement counters, and so on, but additionally, if there's some way to actually remove the mutex or counters from the object structure as well that's be truly optimal.

How to find Max and its index in vector in c++? [duplicate]

Please have a look at the following code. I've tried using max_element function and find function to complete the task, but shows segmentation error, when compiled. I've checked it is not out of bound. Kindly help me out, Also, if possible kindly suggest me some resource on C++ I know badics, I'm having difficulty in the STL part.

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
double bag( int w, vector<int> values,vector<int> weights){
    int index, ma;
    double W1=0.0;
    double V=0.0;
    while(W1<=w)
    {
ma=*max_element(values.begin(), values.end())   ;
auto it = find(values.begin(), values.end(), ma);
index = distance(values.begin(),it);

if(w-W1>=weights[index])
{
V=V+values[index];
W1=W1+weights[index];
}

else 
{
    V=V+values[index]*(w-W1)/weights[index];
    }
    
    values.erase(it);
    weights.erase(it);
    }
    return V;
}
int main() {
  int n;
  int w;
  double ans;
  std::cin >> n >> w;
  vector<int> values(n);
  vector<int> weights(n);
  for (int i = 0; i < n; i++) {
    std::cin >> values[i] >> weights[i];
  }
    cout<<values[n-1];
    ans = bag(w,values,weights);
    cout<<ans;
} 

C++ stack array without constant expression [duplicate]

From A Tour of C++

The size of an array must be a constant expression

I can not understand why this compiles and runs without errors

int main() 
{
    int input;
    cin >> input;
    char v[input];
    cout << sizeof(v) << endl;
}

While this doesn't

int value(int value)
{
    for(int i = 0; i < value; i++) {
        value++;       
    }
    return value;
}

int main() 
{
    int input;
    cin >> input;
    char v[value(input)];
    cout << sizeof(v) << endl;
}

Can somebody explain to me why does this happen?

Timer calling a function at regular interval interval

static void timer_start(std::function<void(void)> func, unsigned int interval)
{
  
  std::thread([func, interval]()
  { 
    while (true)
    { 
      auto x = std::chrono::steady_clock::now() + std::chrono::milliseconds(interval);
      func();
      std::this_thread::sleep_until(x);
    }
  }).detach();
}

static void interfacetoBackend()
{ 

}

int main(){
    timer_start(interfacetoBackend, 2000);  

}

I have a timer calling a function at regular interval as shown above. I like to stop before the program end. Currently, I can't stop the time. How can I stop the time call?

How to choose type from some different on compilation time?

I want to do something like this:

template <uint64_t N>
struct a {
  static constexpr T1 v1 = {};
  static constexpr T2 v2 = {};
  static constexpr auto v3 = (N % 2 == 1 ? v1 : v2);
};

But I can't use (? :) with different types. How I can do this?

Define two class enums in the same header file with the output operator overriden

I have the Colors.hpp header in which I would like to define the two enums that are seen in the code. Also, I would like to print the number value, so I have overridden the << operator for the two enums:

#ifndef COLORS_HPP
#define COLORS_HPP

#include <iostream>

namespace CliWidget {

enum class ForegroundColor {
    black   = 30, 
    red     = 31, 
    green   = 32, 
    yellow  = 33, 
    blue    = 34, 
    magenta = 35, 
    cyan    = 36, 
    white   = 37
};  

std::ostream& operator << (std::ostream& os, const ForegroundColor& fColor){
   os << fColor; 
   return os; 
}   

enum class BackgroundColor {
    black   = 40, 
    red     = 41, 
    green   = 42, 
    yellow  = 43, 
    blue    = 44, 
    magenta = 45, 
    cyan    = 46, 
    white   = 47
};  

std::ostream& operator << (std::ostream& os, const BackgroundColor& bColor){
   os << bColor; 
   return os; 
}   
}
#endif

The problem I'm having is that the compiler finds the two functions of operator override and seems that for it they are the same (multiple definitions) as the error shows.

In function CliWidget::operator<<(std::ostream&, CliWidget::ForegroundColor const&)': /home/albert/Projects/CliWidget/src/ColorsEnum.hpp:20: multiple definition of CliWidget::operator<<(std::ostream&, CliWidget::ForegroundColor const&)'

Should I only make one operator for the two enums, or there is a better solution?

How does auto decide the type of variable?

#include <iostream>
int main() 
{
    auto n {42};
    cout << "The n has value of " << n <<
    " and a size of " << sizeof(n) << endl; // Works as expected
}
#include <iostream>
int main() 
{
    auto n = {42};
    cout << "The n has value of " << n <<
    " and a size of " << sizeof(n) << endl; // Does not work!
}

Why is that? In "Tour of C++" it is explicitly said:

1.4.2 Initialization Before an object can be used, it must be given a value. C++ offers a variety of notations for expressing initialization, such as the = used above, and a universal form based on curly-brace delimited initializer lists:

    double d1 = 2.3; // initialize d1 to 2.3  
    double d2 {2.3}; // initialize d2 to 2.3  
    double d3 = {2.3}; // initialize d3 to 2.3 (the = is optional with { ... })
    complex<double> z2 {d1,d2};   
    complex<double> z3 = {d1,d2}; // the = is optional with { ... }  

The = is optional with {}.
so, why does this happen?

What is the benefit of moving a range of elements in a vector vs. copying?

Consider the following snippet (saw something analogous to this in a large simulation code)

std::vector<int> v1{1,2,3,4,5,6,7};
std::vector<int> v2;

std::move(v1.begin() + 2, v1.end(), back_inserter(v2));

Here, I am moving a range of elements from v1 to v2, but is there any particular advantage to doing this vs. copying? I do not actually see what the advantage of the move here would be since it's operating on a range of ints. In fact, I do not believe any move is occurring since we are dealing with POD types.

If we instead wanted to transfer the entire v1 to v2, then we could do:

v2 = std::move(v1);

The cast here would allow v2 to now own the pointer to the contiguous range of memory previously owned by v1, thus avoiding a copy.

But in the former move of a range of elements, I do not see the usefulness.

vendredi 28 août 2020

try and except, but in c++

Suppose I want to compute the binary value of a series of numbers entered by a user but I don't want to set a limit to how many numbers the user can enter, so I do this in Python 3:

try:
    lst = list()
    while True:
        n = int(input("Enter the number: "))
        b = binary_of(n)                      // Function to find binary value
        lst.append(b)
except:
    print("The respective binary values are", '\n')
    print(lst)

In above code, the 'try' stops executing when the user enters a non-integer value and the program moves to 'except' to print the list and this is exactly what I want.

Can I do something similar in C++? Is there a 'try and except' version of C++ too??

How to pass array of shared pointer to other function in c++ [duplicate]

I'd like to pass an array of shared pointer to another class.

How to use a function parameter for it?

Below is example.

// < BaseClass >
 std::shared_pointer<queue> queue_[3];

// init 0,1,2
 queue[0] = std::make_shared<queue>

// move queue to inner class
 InnerClass.init(queue)
<InnberClass>
    // I don't know how to use func param
    // this is normal usage to pass shared pointer
    init(const std::shared_pointer<queue>& queue)
    {
      queue_ = queue;
    }
    // array of share pointer(const ref) to func
    init(const ?& queue)
    {
    queue_array_ = queue;
    }

Is there a way to rewrite this?

string toLowerCase(string word)
{

  for (int a = 0; a < word.length(); a++)
  {

      if (word[a] >= 'A' && word[a] <= 'Z')
      {

          word[a] = word[a] + 32;
      }
  }


  return word;
}

Is there another way to code this? It can't be c-strings. Thanks.

Dumping and parsing std::vector

In order to parse, with https://github.com/nlohmann/json,

std::vector<std::shared_ptr<VPN>>

where VPN can be the subtypes OpenVPN and other types like MicrosoftVPN, CiscoVPN, etc, I had to do the following:

        void to_json(json &j, const std::shared_ptr<VPN> &p)
        {
            //Dont forget to set type on each subtype!!!
            if (auto pp = std::dynamic_pointer_cast<OpenVPN>(p))
            {
                to_json(j, pp);
            }
            else
            {
                //try other subtypes then throw if none
            }
        }

        void from_json(const json &j, std::shared_ptr<VPN> &p)
        {
            if (j.at("type") == "OPENVPN")
            {
                p = std::make_shared<OpenVPN>();
                //Important: re-set the type since we recreated the instance
                p->type = VPN::Type::OPENVPN;
                auto pp = std::dynamic_pointer_cast<OpenVPN>(p);
                from_json(j, pp);
            }
            else
            {
                //throw
            }
        }

then, for each subtype, I implement the to_json and from_json:


        void to_json(json &j, const std::shared_ptr<OpenVPN> &p)
        {
            //Important: always set type
            j = json{
                {"type", p->type},
                {"openvpnVersion", p->openvpnVersion},
                {"profile", p->profile}};
                //...
        }

        void from_json(const json &j, std::shared_ptr<OpenVPN> &p)
        {
            j.at("openvpnVersion").get_to(p->openvpnVersion);
            j.at("profile").get_to(p->profile);
            //...
        }

As you can see, I got many problems, like if (j.at("type") == "OPENVPN"). I have to compare with the string literal instead of the enum before I create the instance of VPN with the subtype OpenVPN for example. I had multiple tries after a lot of segfaults to realize what I was doing. Also I have to instantiate the pointers myself which is very easy to forget and cause segfault.

Apparently std::vector<CustomObject> works without me having to do anything except implementing from_json and to_json for CustomObject. But if CustomObject = std::shared_ptr<OtherCustomObject> then I need to implement from_json and to_json for std::shared_ptr<OtherCustomObject>.

Shouldn't or couldn't the library handle std::vector<std::shared_ptr<CustomObject>> on its own? Do anybody have a better solution?

Deterministic finite Automata design

Can anybody refer me to algorithm for this?

A simulation of a DFSM: Design and implement a program to simulate a DFSM. This program must take two arguments and output ‘yes/no’. The first argument is a file name (the name of a file containing the specification of a DFSM) and the second argument is a string. Both arguments must be command-line arguments. The output of the program is ‘yes’ if the DFSM accepts the string and ‘no’ otherwise. The DFSM specification, given in a file, is structured as follows:

The first line of the file contains the input alphabet separated by one or more spaces. Each alphabet should be a single character.

The transition function is given as a table. The order of the alphabet listing will be the same as the order of the columns of the transition table.

The last line of the file contains the set of final states separated one or more spaces.

The transition function is given between the first and the last lines of the file.

Each row of the transition table will be a line. Elements of the row are separated one or more spaces. Assuming that there are at least three lines in the file, the second line corresponds to the first row of the transition table indexed by state 1. The row indices are implicit starting from the second line of the file. Columns of the table are indexed by the ordering of the alphabet as it appears in the first line. States are denoted by integers starting from 1, which is the start state.

The rows of the transition table are given between the first and last lines of the file with one row per line.

enter image description here

reinterpret_cast - the same pointer may have multiple integer representations [duplicate]

https://en.cppreference.com/w/cpp/language/reinterpret_cast

A pointer converted to an integer of sufficient size and back to the same pointer type is guaranteed to have its original value, otherwise the resulting pointer cannot be dereferenced safely (the round-trip conversion in the opposite direction is not guaranteed; the same pointer may have multiple integer representations)

What does the statement in bold mean?

reinterpret_cast - A value of any integral or enumeration type can be converted to a pointer type

https://en.cppreference.com/w/cpp/language/reinterpret_cast

A value of any integral or enumeration type can be converted to a pointer type.

They are not talking about structs and classes here, so they are not included?

They also mean that if I have an object of an enum like MyEnum obj; then obj can be converted to MyEnum *obj;?

reinterpret_cast - An expression of integral, enumeration, pointer, or pointer-to-member type can be converted to its own type

https://en.cppreference.com/w/cpp/language/reinterpret_cast

An expression of integral, enumeration, pointer, or pointer-to-member type can be converted to its own type. The resulting value is the same as the value of expression. (since C++11)

Why should I be interested in converting something to its own type? This reads to me as I would want to convert int to int.

Please correct me.

reinterpret_cast - A pointer can be converted to any integral type large enough to hold all values of its type [closed]

https://en.cppreference.com/w/cpp/language/reinterpret_cast

An expression of integral, enumeration, pointer, or pointer-to-member type can be converted to its own type. The resulting value is the same as the value of expression. (since C++11)

Why should I be interested in converting something to its own type? This reads to me as I would want to convert int to int.

Please correct me.

Which Version of Code::Blocks supports C++11, C++14 and C++17 Compilers?

Please give me the Version of Code::blocks, currently i'm using Code::Blocks 10.05 on Windows 7 with Server Pack 1 installed. The Code::blocks i'm using does not support either of the three Compilers that i had mentioned above, Thank You. [I'm not going to install VS, because of data limit, i atleast need C++11, so even if you Coders can give me that version of Code::blocks it would be more than enough]

How can I use struct as key? [duplicate]

I have the following code, I've got some errors like:

struct duplicatedTurns
    {
        int nodeId;
        int min;
        int max;

        bool operator==(const duplicatedTurns& other) const
        {
            return nodeId == other.nodeId && min == other.min && max == other.max;
        }

I solved it here to following code:
bool operator<(const duplicatedTurns& other) const
{
if (nodeId != other.nodeId) return nodeId < other.nodeId;
if (min != other.min) return min < other.min;
if (max != other.max) return max < other.max;
return false;
}

    };

The container that I want to use:

std::map<duplicatedTurns, int> selected;

After i would like to insert elements there:

selected.insert(duplicatedturns{it->nodeId, std::min(it->toLinkId, it->fromLinkId), std::max(it->toLinkId, it->fromLinkId)}, "here: increment the number if the key are the same" );

difference between uniform_init_distrubtion and default_random_engine

I'm new of C++11 random generators, and I can't get what's difference between all these different number generators. how can i decide which one is best for me?

Rethrow custom exceptions in several methods C++11

I have a use case where I have to catch various exception that can be thrown and pass an equivalent exception from my library

example:

def subscribe() {
    try {
       .....
       .....
    catch (A e) { throw new MY_A(e);}
    catch (B e) { throw new MY_B(e);}
    catch (C e) { throw new MY_C(e);}
    catch(...) { throw default(e)}
}

I wanted to do this for several methods - subscribe, unsubscribe, stop, start etc., Is there any easy way of doing this ?

Had it been in python, I would have simply written a decorator and achieved this. What will be the easy way to do this in C++11 ?

Does dynamic_cast work even when thereis no inheritance?

std::bad_cast: https://en.cppreference.com/w/cpp/types/bad_cast

An exception of this type is thrown when a dynamic_cast to a reference type fails the run-time check (e.g. because the types are not related by inheritance)

So, if the types are not related by inheritance then it throws an error, so how it the following quote hold true?

https://stackoverflow.com/a/332086/462608

You can use it for more than just casting downwards – you can cast sideways or even up another chain.

What does this quote mean? Please give examples.

const_cast: modifying a formerly const value is only undefined if the original variable is const

https://stackoverflow.com/a/332086/462608

modifying a formerly const value is only undefined if the original variable is const

...

if you use it to take the const off a reference to something that wasn't declared with const, it is safe.

...

This can be useful when overloading member functions based on const, for instance. It can also be used to add const to an object, such as to call a member function overload.

I am unable to understand the meanings of the above quotes. I request you to give me examples to practically show what these quotes mean.

jeudi 27 août 2020

Functional composition with std::bind

I am reading the second edition of the beautiful book of Nicolai Josuttis on C++11 STL.

I found the following piece of code:

#include <functional>
#include <iostream>

int main()
{
   auto plus10 = std::bind(std::plus<int>(),
      std::placeholders::_1,
      10);
   std::cout << "+10:    " << plus10(7) << std::endl;

   auto plus10times2 = std::bind(std::multiplies<int>(),
      std::bind(std::plus<int>(),
         std::placeholders::_1,
         10),
      2);
   // ...
}

I am not able to understand how the bind object "plus10times2" works. It should not bind to int parameters?

How can it bind another bind object? How it works when the call operator of plus10times2 is called (like plus10times2(7) for example)?

Variadic function that accepts arguments of same type at compile time and iterate on them

I am looking for a way to implement Variadic function that accepts arguments of same type at compile time and should be able to iterate on them. Something like below -

 void SampleFunc(int... arg)
    {
           for(const auto& val : arg)
           {
               // Each argument available here.
           }
    }

then I will call this function like below -

SampleFunc({1,2,3,4})

Most important thing is that parameters are hard coded every time the function is called so I should be able to generate this Variadic arguments at compile time.

Right now I am accepting function parameters as shown below -

 void SampleFunc(std::vector<int>& nums)

But this adds run time cost of constructing a vector every time function is called which I want to avoid. Thanks a tone in advance!!!

Error with << operator, "no operator "<> << void"

My code is for a class which already has an oprator<< function

friend ostream& operator<<(ostream &os, const Alist& other);

ostream& operator<<(ostream &os, const Alist& other)
{
  for (int i = 0; i <= other.val; i++)
   os << other.a[i] << ", ";
  return os;  
}

it doesn't satisfy the parameters for this statement in my main function

cout << "Double remove: " << a1.remove(n) << " " << a1.remove(n) << endl;

and I receive this error

no operator "<<" matches these operands -- operand types are: std::basic_ostream<char, std::char_traits<char>> << void

I'm not sure how to go about writing the function for another << operator but so far I have what's shown below as that seems to meet the needs.

friend ostream& operator<<(ostream &os, const unsigned char *s);

is this correct? and how would I write the function for this? Below is the remove function.

bool Alist::remove(int n)
{
  for (int i = 0; i < val; i++)
   if(a[i] = n)
    {
      for ( int j = i; j < (val - 1); j++)
        a[j] = a[j+1];
    }
  for (int i = 0; i < val; i++)
   if(a[i] != n)
    return true;
  else
    return false;
}

Passing vector with std::ref to threads does not seem to update the actual vector rather threads only updating local vector copy

I am facing a strange issue when passing a vector std::ref to pool of threads.

I cannot put the exact code but I have something like : Approach A

void myfunc(int start, int end, std::vector<double>& result)
{
   for(int i=start; i<end; ++i)
    {
        result[i] = ...
    }
}


vector<double> myvec(N);
const size_t num_threads = std::thread::hardware_concurrency();
vector<std::thread> threads;
threads.reserve(num_threads);

for(int idx=0; idx<num_threads; ++idx)
   threads.push_back(std::thread(myfunc, (idx*nloop/num_threads), (idx+1)*nloop/num_threads), std::ref(myvec)));

for(std::thread& t : threads)
  { 
    if(t.joinable())
     t.join();
  }

some_read_opration(myvec)...

But if I explicitly create threads and divide tasks by hard coding ranges, it gives me expected values.

This works: Approach B

std::thread t1(myfunc, 0, nloop/2, std::ref(myvec));
std::thread t2(myfunc, nloop/2, nloop, std::ref(myvec));

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

some_read_opration(myvec)...

I want parallelize my loop in more generic way, not sure where I am going wrong here. In the A approach : The issue I am facing is that, it seems like each thread updates result[] element locally but its not being reflected at myvec in the function which creates threads, even if I am passing std::ref(myvec). Any help would be great.

Process was terminated. It took longer than 12000ms to complete

Create a function that takes a sentence and turns every "i" into "wi" and "e" into "we", and add "owo" at the end.

I was creating the function for the above question and received an error:

Process was terminated. It took longer than 12000ms to complete

Can anyone please help me with the fix?

#include<string>

std::string owofied(std::string sentence) {
    int pos=0;
    for(int i =0 ; i<sentence.size(); i++)
    {
        if(sentence[i]=='i')
            sentence.replace(i,1,"wi");
        else if(sentence[i]=='e')
            sentence.replace(i,1,"we");
        pos=i;
    }
    sentence.insert(pos,"owo");
    return sentence;
}

Is the following code thread unsafe? Is so, how can I make a possible result more likely to come out?

Is the screen output of the following program deterministic? My understanding is that it is not, as it could be either 1 or 2 depending on whether the latest thread to pick up the value of i picks it up before or after the other thread has written 1 into it.

On the other, hand I keep seeing the same output as if each thread waits the previous to finish, as in I get 2 on screen in this case, or 100 if I create similar threads from t1 to t100 and join them all.

If the answer is no, the result is not deterministic, is there a way with a simple toy program to increase the odds that the one of the possible results comes out?

#include <iostream>
#include <thread>

int main() {

    int i = 0;

    std::thread t1([&i](){ ++i; });
    std::thread t2([&i](){ ++i; });

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

    std::cout << i << '\n';
}

(I'm compiling and running it like this: g++ -std=c++11 -lpthread prova.cpp -o exe && ./exe.)

std::shared_ptr + pure virtual + overriding in python using Boost.python

I have the below use case where I want to override a pure virtual class in python and pass the shared_ptr to a C++ class. I tried the below but unable to get it work.

#define BOOST_BIND_GLOBAL_PLACEHOLDERS
#include <boost/python/class.hpp>
#include <boost/python/module_init.hpp>
#include <boost/python/def.hpp>
#include <boost/python/call_method.hpp>
#include <boost/ref.hpp>
#include <memory>
#include <boost/utility.hpp>
#include <iostream>
#include <memory>
using namespace std;

class Vector : public std::enable_shared_from_this<Vector> {
    public:
        Vector() {}
        virtual void prints()
        {  std::cout << "Vector" << std::endl;    }
};

struct PyVector : Vector , boost::python::wrapper<Vector> {
    PyVector(): Vector() {}
    void prints() { this->get_override("prints")(); }
};

class Foo {
    public:
        Foo(boost::shared_ptr<Vector> vec) : _vec(vec){}
        boost::shared_ptr<Vector> _vec;
        void prints() {
            _vec -> prints();
        }
};

#include <boost/python.hpp>
using namespace boost::python;
    
BOOST_PYTHON_MODULE(Virtually) {

    class_<Vector, boost::shared_ptr<Vector>, PyVector>("vector", init<>());

    class_<Foo, boost::shared_ptr<Foo>>("foo", init<boost::shared_ptr<Vector>>())
        .def("prints", &Foo::prints);

}

For the blow python code it gives wrong values


In [3]: class MyVector(m.vector):
   ...: 
   ...:     def prints(self):
   ...:         print("MyVector")
   ...:         
   ...:     def __del__(self):
   ...:         print("I was deleted")

In [4]: x = MyVector()

In [5]: fo = m.foo(x)

In [6]: fo.prints()
Vector // It should have printed MyVector

Questions:

  1. Why am I seeing this behavior ? The method that I am overriding is not recognized ?
  2. I'd like to enhance this to work with pure virtual class (ie, Vector.prints has to be made pure virtual). How can I do that ?
  3. Instead of boost::shared_ptr, I want to use std::shared_ptr

How can I achieve them using Boost.python. If not boost python which tool and how can I implement it ?

Cannot make std::reference_wrapper work with std::unique_ptr

I have an object pool that holds objects in std::unique_ptr<T>.

The pool, like most pools, holds objects that are expensive to create, but once an object is borrowed there is no way of preventing an object with the same settings from being added to the pool so I'd like to extend it to prevent that from happening.

I see 3 options for this:

  1. Replace std::unique_ptr<T> with std::shared_ptr<T> but there's no plans to have multithreaded code and this breaks the convention of ownership - the pool should not own an object just to read one of its properties.

  2. Keep a copy of a property of T with the pool in a std::vector, adding and removing when std::unique_ptr<T> is borrowed from and returned to the pool. Easy to implement but feels wrong as I'm duplicating data.

  3. Use a std::vector<std::reference_wrapper<std::unique_ptr<T>>>. By keeping a reference to borrowed std::unique_ptr<T> I have access to its properties and I can easily prevent objects with the same settings from being created.

I'm currently trying to implement 3 but am stuck on how to add a reference to std::unique_ptr<T> to std::vector<std::reference_wrapper<std::unique_ptr<T>>>. Is this even possible?

mercredi 26 août 2020

Io_obj*(istream&) as a pointer to function in Stroustrup

In The C++ Programming Language (p.650 of Fourth Edition paperback), Stroustrup writes some code for a map with a string as the key and function pointer as the mapped type (comment is his own):

using Pf = Io_obj*(istream&); // pointer to function returning an Io_obj*
std::map<std::string,Pf> io_map;

I am not really familiar with function pointers and I wanted to make my own test code where you have a string like "add 1 2", break off the first word to pass as the key to map, and pass the remainder as the argument to the calculating function pointer that map returns. My types are simpler (plain old int and plain old string) but it took me some googling to get it into a form the compiler would accept. Leaving out the alias here for simplicity:

std::map<std::string,int(std::string)> calc_map; // Stroustrup's syntax (comipile error)...

became...

std::map<std::string,int(*)(std::string)> calc_map; // syntax that compiles...

Question 1: Is this some idiosyncratic issue with clang (I am on an old Mac laptop because my linux machine is dead!) or did Stroustrup forget to add the (*) in his example? Am I missing something else?

Further, his example uses an alias, which in my simple calculation example translated at first to:

using Pf = int(std::string); // compiler actually seems to think this is fine
std::map<std::string,Pf> calc_map; // compiler does not like this

and when fixed became...

using Pf = int(*)(std::string); // compiler thinks this is fine too
std::map<std::string,Pf> calc_map; // compiler also likes this and everything works

Question 2: What kind of thing is an int(std::string) that the compiler doesn't mind it as an alias?

Possibly useful version stuff from clang:

Apple LLVM version 6.0 (clang-600.0.57) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin13.1.0

Thanks!

Can someone help me with this compilation error I recieved when compiling C++ code?

I got an error whilt trying to compile this code from C++ Primer. The system architecture is x86_64 and is running macOS 10.15.6. The code is provided in C++ Primer 6, and I compiled it with C++11 and C++ 17 standard, both gave me an error.

#include <iostream>
using namespace std;
int main()
{
using namespace std; int chest = 42;
int waist = 42;
int inseam = 42;
cout << "Monsieur cuts a striking figure!" << endl;
cout << "chest = " << chest << " (decimal for 42)" << endl; cout << hex; // manipulator for changing number base
cout << "waist = " << waist << " (hexadecimal for 42)" << endl; cout << oct; // manipulator for changing number base
cout << "inseam = " << inseam << " (octal for 42)" << endl; return 0;
}

Undefined symbols for architecture x86_64:
  "std::__1::locale::use_facet(std::__1::locale::id&) const", referenced from:
      std::__1::ctype<char> const& std::__1::use_facet<std::__1::ctype<char> >(std::__1::locale const&) in hextest-ea1278.o
  "std::__1::ios_base::getloc() const", referenced from:
      std::__1::basic_ios<char, std::__1::char_traits<char> >::widen(char) const in hextest-ea1278.o
  "std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::__init(unsigned long, char)", referenced from:
      std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::basic_string(unsigned long, char) in hextest-ea1278.o
  "std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::~basic_string()", referenced from:
      std::__1::ostreambuf_iterator<char, std::__1::char_traits<char> > std::__1::__pad_and_output<char, std::__1::char_traits<char> >(std::__1::ostreambuf_iterator<char, std::__1::char_traits<char> >, char const*, char const*, char const*, std::__1::ios_base&, char) in hextest-ea1278.o
  "std::__1::basic_ostream<char, std::__1::char_traits<char> >::put(char)", referenced from:
      std::__1::basic_ostream<char, std::__1::char_traits<char> >& std::__1::endl<char, std::__1::char_traits<char> >(std::__1::basic_ostream<char, std::__1::char_traits<char> >&) in hextest-ea1278.o
  "std::__1::basic_ostream<char, std::__1::char_traits<char> >::flush()", referenced from:
      std::__1::basic_ostream<char, std::__1::char_traits<char> >& std::__1::endl<char, std::__1::char_traits<char> >(std::__1::basic_ostream<char, std::__1::char_traits<char> >&) in hextest-ea1278.o
  "std::__1::basic_ostream<char, std::__1::char_traits<char> >::sentry::sentry(std::__1::basic_ostream<char, std::__1::char_traits<char> >&)", referenced from:
      std::__1::basic_ostream<char, std::__1::char_traits<char> >& std::__1::__put_character_sequence<char, std::__1::char_traits<char> >(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, char const*, unsigned long) in hextest-ea1278.o
  "std::__1::basic_ostream<char, std::__1::char_traits<char> >::sentry::~sentry()", referenced from:
      std::__1::basic_ostream<char, std::__1::char_traits<char> >& std::__1::__put_character_sequence<char, std::__1::char_traits<char> >(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, char const*, unsigned long) in hextest-ea1278.o
  "std::__1::basic_ostream<char, std::__1::char_traits<char> >::operator<<(int)", referenced from:
      _main in hextest-ea1278.o
  "std::__1::cout", referenced from:
      _main in hextest-ea1278.o
  "std::__1::ctype<char>::id", referenced from:
      std::__1::ctype<char> const& std::__1::use_facet<std::__1::ctype<char> >(std::__1::locale const&) in hextest-ea1278.o
  "std::__1::locale::~locale()", referenced from:
      std::__1::basic_ios<char, std::__1::char_traits<char> >::widen(char) const in hextest-ea1278.o
  "std::__1::ios_base::__set_badbit_and_consider_rethrow()", referenced from:
      std::__1::basic_ostream<char, std::__1::char_traits<char> >& std::__1::__put_character_sequence<char, std::__1::char_traits<char> >(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, char const*, unsigned long) in hextest-ea1278.o
  "std::__1::ios_base::clear(unsigned int)", referenced from:
      std::__1::ios_base::setstate(unsigned int) in hextest-ea1278.o
  "std::terminate()", referenced from:
      ___clang_call_terminate in hextest-ea1278.o
  "___cxa_begin_catch", referenced from:
      std::__1::basic_ostream<char, std::__1::char_traits<char> >& std::__1::__put_character_sequence<char, std::__1::char_traits<char> >(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, char const*, unsigned long) in hextest-ea1278.o
      ___clang_call_terminate in hextest-ea1278.o
  "___cxa_call_unexpected", referenced from:
      std::__1::ostreambuf_iterator<char, std::__1::char_traits<char> >::ostreambuf_iterator(std::__1::basic_ostream<char, std::__1::char_traits<char> >&) in hextest-ea1278.o
  "___cxa_end_catch", referenced from:
      std::__1::basic_ostream<char, std::__1::char_traits<char> >& std::__1::__put_character_sequence<char, std::__1::char_traits<char> >(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, char const*, unsigned long) in hextest-ea1278.o
  "___gxx_personality_v0", referenced from:
      std::__1::basic_ostream<char, std::__1::char_traits<char> >& std::__1::__put_character_sequence<char, std::__1::char_traits<char> >(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, char const*, unsigned long) in hextest-ea1278.o
      std::__1::ostreambuf_iterator<char, std::__1::char_traits<char> > std::__1::__pad_and_output<char, std::__1::char_traits<char> >(std::__1::ostreambuf_iterator<char, std::__1::char_traits<char> >, char const*, char const*, char const*, std::__1::ios_base&, char) in hextest-ea1278.o
      std::__1::ostreambuf_iterator<char, std::__1::char_traits<char> >::ostreambuf_iterator(std::__1::basic_ostream<char, std::__1::char_traits<char> >&) in hextest-ea1278.o
      std::__1::basic_ios<char, std::__1::char_traits<char> >::widen(char) const in hextest-ea1278.o
      Dwarf Exception Unwind Info (__eh_frame) in hextest-ea1278.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Template Class Inside Template Class - Different Parameter

Is it possible to create a template class inside a template class like the following

// Container.h
template <typename T>
class Container
{
private:
  using iterator = Iterator<Node<T>>;
  using const_iterator = Iterator<const Node<T>>;

  // Node struct to hold data.
  template <typename T>
  struct Node
  {
    T data_;
  };

public:
  // Templated iterator for const or non-const.
  template <typename NodeType>
  class Iterator
  {
  private:
    NodeType* node_;
  
  public:
    Iterator();
  };
};

#include "Container.tpp"

So here I declare a template for an iterator that takes in a NodeType which is different from the T that the container class template takes.

If this is possible to do, how do I implemenet the Iterator() inside a different file? Something like

// Container.tpp
template <typename T>
LinkedList<T>::LinkedListIterator<NodeType>::Iterator()
{
  // Implementation ...
}

This does not seem right since I do not have access to the NodeType. Any advice would be appreciated.

Partial template specialization of std::atomic for smart pointers

Background

Since C++11, atomic operations on std::shared_ptr can be done via std::atomic_... methods found here, because the partial specialization as shown below is not possible:

std::atomic<std::shared_ptr<T>>

This is due to the fact that std::atomic only accepts TriviallyCopyable types, and std::shared_ptr (or std::weak_ptr) is not trivially copyable.

However, as of C++20, these methods have been deprecated, and got replaced by the partial template specialization of std::atomic for std::shared_ptr as described here.

Question

I am not sure of

  1. Why std::atomic_... got replaced.
  2. Techniques used to enable the partial template specialization of std::atomic for smart pointers.

Is there a way to exclude rows and columns in a C++ array?

Suppose I have an array in C++ such as the following:

1  2  3  4 = arr
5  6  7  8
9  9  8  9
7  6  1  3

Is there a concise way to exclude any row and/or column?

For example, suppose I want to do an operation on the following array:

1  3  4
5  7  8
7  1  3

In other programming languages, I can obtain the above array fairly easy with arr[-3,-2] to exclude the third row and second column. However, I have been unable to find a concise way to exclude rows and columns in C++. How would you go about it?

how to set c++11 thread affinity to NUMA node on Windows?

On Windows, how can I:

  • query how many NUMA nodes the system has
  • set affinity of an std::thread to the CPU cores of a specific NUMA node?

Returning different data types from a function in c++

I am writing some kind of buffer parser that takes vector of unsigned char bytes as an input,for example

Datatype getvalue(vector<unsigned char> buffer) 
{
  // compute value
  If vector contains 2 bytes then unsigned int will be returned
  If vector contains 4 bytes then unsigned long will be returned 
  If 12 bytes then date time will
 be returns 
  return value;
}

QT moc.exe won't compile in VS19 extension

I've been working on a project for months now and it's been fine. I've just came back from holiday and now it won't compile. Original it said this error message, which I have no clue what it's pointing out?enter image description here I restarted Visual studio and now get this:enter image description here With this log output:

1>main.cpp
1>D:\Documents\GitHub\CppTSPAlgorithm3\CppTSPalgorithm\CppTSPalgorithm.cpp(14,59): warning C4311: 
'type cast': pointer truncation from 'int (__cdecl *)(void)' to 'int'
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.27.29110\include\xutility(4607,45): error C2675: unary '++': '_OutIt' does not define this operator or a conversion to a type acceptable to the predefined operator
1>        with
1>        [
1>            _OutIt=std::vector<double,std::allocator<double>>
1>        ] (compiling source file CppTSPalgorithm.cpp)
1>D:\Documents\GitHub\CppTSPAlgorithm3\CppTSPalgorithm\CppTSPalgorithm.cpp(123): message : see reference to function template instantiation '_OutIt std::fill_n<std::vector<double,std::allocator<double>>,int,int>(_OutIt,const _Diff,const _Ty &)' being compiled
1>        with
1>        [
1>            _OutIt=std::vector<double,std::allocator<double>>,
1>            _Diff=int,
1>            _Ty=int
1>        ]
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.27.29110\include\xutility(4608,13): error C2100: illegal indirection (compiling source file CppTSPalgorithm.cpp)
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.27.29110\include\xutility(4607,45): error C2088: '++': illegal for class (compiling source file CppTSPalgorithm.cpp)
1>Done building project "CppTSPalgorithm.vcxproj" -- FAILED.

The moc.exe is in the right folder and hasn't been changed since installing QT. I have all the necessary extensions and have achieved a compilable solution. I'm using QT5 V5.15.0 on VS2019 x86. From what I've read QT creator and VS will have 2 different compilers and I've found no solution for this error on VS. I've also not been able to re-download/troubleshoot the moc.exe file.

Maybe useful links(I have no clue what's causing this and what to google, but this is what I've gotten): https://developercommunity.visualstudio.com/content/problem/580465/qt-moc-starts-over.html https://forum.qt.io/topic/54395/qt-5-4-1-cannot-find-moc-exe/4

TensorFlow C API vs TensorFlow C++ API

I'm using TensorFlow C_API in C++ programs. Building and using C++_API looks difficult. Do I need to replace C_API with C++_API? What do I loose if I don't do that?

Why I am not able to print first element in this Linked List?

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807

    class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            
            vector<int> a1;
            vector<int> a2;
            vector<int> result;
            while(l1->next||l2->next)
            {
                a1.push_back(l1->val);
                a2.push_back(l2->val);
                l1=l1->next;
                l2=l2->next;
            }
            int v1=0;
            int v2=0;
            for(auto d:a1)
            {
                v1=v1*10+d;
                
            }
            for(auto f:a2)
            {
                v2=v2*10+f;
            }
            int v3=v1+v2;
            int r;
            while(v3>0)
            {
                r=v3%10;
                v3=v3/10;
                result.push_back(r);
                
            }
            ListNode* p= new ListNode(result[0]);
            ListNode* start=p;
            ListNode* add=p;
            int i;
            for(i=1;i<result.size();i++)
            {
                ListNode* temp=new ListNode(result[i]);
                
                add->next=temp;
                add=add->next;
            }
            return p;
        }
    };

Output(1st element of the linked list is not printing)

Input: [2,4,3]
       [5,6,4]
               
Your answer:[0,8]              
Expected answer:[7,0,8]
       

I am not able to print the first element of the resultant linked list. I Tried with different test cases and its printing everything right except the first element.

Unique Pointer returns different instances

I have created a Car class.

class Car
{
public:
   std::string NumberPlate;
};

RentCar supposed to keep one instance of Car.

class RentCar
{
public:
   Car& GetCar()
   {
      if (!m_Car) {
         m_Car = std::make_unique<Car>();
      }
      return *m_Car;
   }
private:
   std::unique_ptr<Car> m_Car;
};

In main, while getting the instance of Car, each time, new instances have been given.

int main()
{
   RentCar rentCar;
   auto car1 = rentCar.GetCar();
   car1.NumberPlate = "Temp";
   std::cout << "Case 1 : " << rentCar.GetCar().NumberPlate.c_str() << "\n";
   rentCar.GetCar().NumberPlate = "Temp";
   std::cout << "Case 2 : " << rentCar.GetCar().NumberPlate.c_str() << "\n";
}

Output is

Case 1 :
Case 2 : Temp

Why the function provides different instances?

Also what's wrong in RentCar::GetCar function?

clang-format: How to prevent space before {}?

I'd like to make auto foo = Foo {}; become auto foo = Foo{};.

What would be the correct property?

My style works when applied from CLI, but this is the only thing that Qt Creator ruins when I save my edited file.

Is there some hackish way to change the value of a const variable?

I have a C++ 11 header which has a const value declared as my_const_value. And a function which runs a complex logic using the const value and returns an expected value.

I know this is not advisable but for writing a unit test for GetValue, I wish to test GetValue with different values of my_const_value. Is there some hack-ish way in C++ to change the value of a const even if it a const?

//MyHeader.hpp
namespace myheader {

const int my_const_value = 5;

int GetValue() {
    // In real world, lets say below line of code is a complex logic that needs to be tested by a unit test
    return /my_const_value * 5) / 25;
}

}

#include "MyHeader.hpp"
#include <gtest/gtest.h>

TEST(MyHeaderTest, Testing_Something) {
    EXPECT_EQ(1, myheader::GetValue()); // This is okay

    // I want to test that in future is the value of my_const_value changes to something else then 
    // myheader::GetValue returns the expected result. But of course I cannot change my_const_value because it is a const.
    // Is there a way to hack around this for a unit test? Is there a way that I could still hack and change the value of my_const_value?
    myheader::my_const_value = 25;
    EXPECT_EQ(5, myheader::GetValue());
}

I know that I could const_cast my_const_value to a non_const variable. But that wouldn't help here. If there is some hack to change the value of my_const_value by using a pointer or something, that would answer my question.

C++11: parameter pack to pass in to constructor for templatized memory allocator

Say I have a class Allocator with a method that will allocate space somehow, construct a desired object in that space, and then do something with the constructed object. The objects' classes are heterogeneous: we could be called for multiple classes in one build. In short I need an idea how to write the ??? parts in this example code:

class Foo {
    Foo( int i, double d, string s );
};

class Bar {
    Bar( int i );
};

class Allocator {
    template<typename T> Allocate( ??? );
}

template<typename T> Allocator::Allocate( ??? ) {
    void* pv = /* memory is found somehow, perhaps using sizeof( T ) */;

    T* pobj = new( pv ) T( ??? );

    /* something is done with the new object */
}

/* user of this class would write something like this??? */
allocator.Allocate<Foo>( 1, 2.3, "four" );
allocator.Allocate<Bar>( 1 );

I've looked at initializer_list<> and parameter packs, but I'm not seeing how to combine those with the template method.

Getting the error "CRT detected that the application wrote to memory after end of heap buffer" when deleting the structure pointer variable in C++

I have the below structure

.h file

 typedef struct _HID_DEVICE
    {
        PCHAR                   m_pcInputReportBuffer;
    } HID_DEVICE, *PHID_DEVICE;

PHID_DEVICE             m_pHidDevice;

I am using this structure variable (m_pHidDevice) and the member (m_pcInputReportBuffer) like as shown below in the implementation file

.cpp file

Initialization:

m_pHidDevice->m_pcInputReportBuffer =
        new char[ m_pHidDevice->m_hDeviceCaps.InputReportByteLength];

if( NULL == m_pHidDevice->m_pcInputReportBuffer )
    {
        throw exception("Memory could not be allocated");
    }
    memset(m_pHidDevice->m_pcInputReportBuffer,
           '\0', m_pHidDevice->m_hDeviceCaps.InputReportByteLength);

Destruction:

if (NULL != m_pHidDevice->m_pcInputReportBuffer )
    {
        delete []m_pHidDevice->m_pcInputReportBuffer;
        m_pHidDevice->m_pcInputReportBuffer = NULL;
    }

When it is calling delete in the if condition, I am getting the error "CRT detected that the application wrote to memory after end of heap buffer"

Here m_pHidDevice has some address but m_pcInputReportBuffer is blank (""). But the control is going into the if condition. How to restrict this?

mardi 25 août 2020

How can I pass a int value to my member function operator += to insert int values into a object list in c++?

I'm very new to c++ and have issues doing what seems like a simple task. I was given a main function to test and I have to create a class that correctly corresponds to the int main. Below is the class I've made so far. There's a lot more to it than what I've provided because I'm having issues starting off the basic parts of the class.

The task is to create a class that makes object lists of ints with a default cap of 8 and can be manipulated with other functions that come later. For now, I am trying to set up the lists and inserting int n values.

#include<iostream>
#include<string>
#include<cmath>
#define DEFAULT 8
#define EMPTY -1
using namespace std;
// Your class specification goes here <<<<<<<<<<<<<<
class Alist
{
  private:
   int *a = NULL;
   int end = EMPTY; // requires -std=c++11 to compile 
   int size;
  public:
    Alist(){a = new int [DEFAULT];} //default constructor
    Alist(Alist const &other);//copy constructor
    Alist(Alist &&other);//move constructor
    ~Alist() {delete [] a;} //destructor 
    Alist& operator=(const Alist& other); //copy assignment
    Alist& operator=(Alist&& other); //move assignment
    Alist& operator+=(const Alist &other);
    Alist& operator+(Alist const &other); // overload +
    friend ostream& operator<<(ostream &os, const Alist& other);
};

this in my class so far and below is the definitions.

Alist::Alist(Alist const &other) // copy constructor
{
  end = other.end;
  a = new int [DEFAULT];
  for (int i = 0; i <= end; i++)
   a[i] = other.a[i];
}
Alist::Alist(Alist &&other) //move constructor
{
  for (int i = 0; i <= end; i++)
   a[i] = other.a[i]; 
  *this = move(other); 
}
Alist& Alist::operator=(const Alist& other) //overload =
{
  if (this == &other) // Check for self assignment
   return *this;
  end = other.end;
  delete [] a;
  a = new int [DEFAULT];
  for (int i = 0; i <= end; i++)
   a[i] = other.a[i];
  return *this;    
}
Alist& Alist::operator=(Alist&& other)
{
  if(this != &other)
  {
    delete[] a;
    a = new int [DEFAULT];
    for (int i = 0; i <= end; i++)
    {
      a[i] = other.a[i];
    }
  }
  return *this;
}
Alist& Alist::operator+(Alist const &other) //overload +
{
  Alist answer;
  int index = 0;
  for (int i = 0; i < this->end; i++)
   answer.a[index++] = this->a[i];
  for (int i = 0; i <= other.end; i++)
   answer.a[index++] = other.a[i];
  return answer;  
}
Alist& Alist::operator+=(const Alist &other)
 {
   Alist answer;
  int index = 0;
  for (int i = 0; i < this->end; i++)
   answer.a[index++] = this->a[i];
   return answer;
 }
 //Alist& Alist::operator[](Alist &other)
 //{
 //  return a[];
 //}
ostream& operator<<(ostream &os, const Alist& other)
{
  for (int i = 0; i <= other.end; i++)
   os << other.a[i] << ", ";
  return os;  
}

I need to get my code to work with this first part of the main function

int main()
{// Test basic constructors and += overloading
 Alist a1, /*a2(true), a3(72, false),*/ a4, a6, a7, a8;
 const int nums_count = 100;
 int n;
  for (int i = 0; i < nums_count; i++)
    {
      n = rand() % 1000;
      a1 += n;
      //a2 += n;
      //a3 += n;
    }
return 0;
}

My main issue is getting the += operator to work correctly as I keep getting the error about adding Alist and an int together. My += function does not seem correct either but im not sure how to even correct it. I've commented out a2 and a3 because I'm not sure how to deal with the true or false of these objects either. Please help in any way or send me in a direction of information Id really appreciate it.

the fastest thread pool in c++

I am a beginner with multithreading. I have found that there is no standard library for thread pool. So I would like to know which is the fastest thread pool that I can use for windows and Linux. Thanks a lot

Undefined reference for ~queue with explicit template instantiation with Clang 10

The following code doesn't link Clang 10 but succeed with GCC and Clang 9:

#include <queue>

template <typename T>
class A
{
public:
    void f();

private:
    std::queue<int> q;
};

template <typename T>
void A<T>::f()
{
    q = {};
}

template class A<int>;

int main()
{
    return 0;
}

What I get from the compiler is:

Online example

/opt/compiler-explorer/gcc-9.3.0/lib/gcc/x86_64-linux-gnu/9.3.0/../../../../x86_64-linux-gnu/bin/ld: /tmp/example-f70f65.o: in function `A<int>::f()':

/home/ce/<source>:16: undefined reference to `std::queue<int, std::deque<int, std::allocator<int> > >::~queue()'

clang-10: error: linker command failed with exit code 1 (use -v to see invocation)

Compiler returned: 1

It works if I replace std::queue with std::vector, std::deque or std::set; or if I remove the explicit template instantiation.

It also works if I remplace q = {} with the full constructor call q = std::queue<int>{}.

Is this code not standard or is it a compiler/libc++ bug?

call a callback function in a pthread function

I'm learning about callback functions in C++ and I'm trying to call a callback function in a pthread function wherein I'm passing the function as argument to pthread_create using reinterpret_cast and then cast it back inside pthread function. This is my code

#include <iostream>    
#include <atomic>
#include <algorithm>
#include <unistd.h>
#include <pthread.h>


std::atomic<int32_t> res(0);
using TCallback = std::function<void (int32_t)>;

void put_result(int32_t result) {
    res = result;
}

void time_consuming_func(TCallback Callback) {
    sleep(10);
    int32_t result = 10456456;
    Callback(result);
}

void* thread_func(void* arg) {
    TCallback callback = std::bind(reinterpret_cast<void (*) (int32_t)>(arg), std::placeholders::_1);
    time_consuming_func(callback);

    return nullptr;
}

int32_t main(int32_t argc, char* argv[]) {
    pthread_t p1;
    pthread_create(&p1, nullptr, thread_func, reinterpret_cast<void*>(put_result));
    
    std::cout << "before: " << res << std::endl;
    pthread_join(p1, nullptr);
    std::cout << "after: " << res << std::endl;

    return EXIT_SUCCESS;
}

I'm trying to compile the above program with the command g++ -Wall -pedantic-errors func_callback_demo.cpp -o func_callback_demo -std=c++11 -lpthread and it doesn't work, but if I remove -pedantic-errors and -wall flags it compiles.

Can somebody tell why this difference?

Why is it tough to find a dummy .so file online?

I need a dummy .so file in order to call it's functions in android. The dummy .so file could be anything from doing addition, subtraction, etc. When searched online, All I find is "What is .so file?", "How to integrate .so file in android". Can anyone please share a dummy .so file for doing addition?

How to use a standard algorithm to replace the for loop?

How can I replace the for loop with a standard algorithm? Here I want to assign the value of vals[i] in vector vals to nodeList[i]->val in nodeList. And what if I use vals[i] * 2 to replace it?

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

using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

int main()
{
    TreeNode node1(1);
    TreeNode node2(2);
    TreeNode node3(3);
    node1.left = &node2;
    node1.right = &node3;

    vector<TreeNode*> nodeList = {&node1, &node2, &node3};
    vector<int> vals = {1, 3, 2};
    for (int i = 0; i < vals.size(); i++) {
        nodeList[i]->val = vals[i];
        // nodeList[i]->val = vals[i] * 2;
    }
}