dimanche 31 mai 2020

Returning smart pointer from raw pointer

This is the way i am returning smart pointer from a raw pointer.

std::shared_ptr<Geometry> Clone() const
{
    Circle *sc = new Circle(*this);
    return std::shared_ptr< Geometry >(sc);
}

Is it the correct way to return Smart pointer from raw pointer ?

Why is the output of `typeid(T&).name()` given as `T` instead of `T&`?

As the subject, you could check the related code on https://godbolt.org/z/qtjVP6.

For your convience, the code is posted below:

#include<typeinfo>
#include<iostream>

class Widget{};

Widget someWidget;

int main()
{
    Widget&& var1 = Widget{};      // here, “&&” means rvalue reference
    auto&& var2 = var1;              // here, “&&” does not mean rvalue reference

    std::cout << typeid(var2).name() << std::endl;
}

Output:6Widget

echo 6Widget | c++filt -t says Widget.

I would be grateful to have some help on this question.

How to merge vectors returned from function?

I have a function that returns a vector of strings and inside my main function I would like to combine all the vectors returned from the function. However I keep hitting an error vector iterators incompatible, but I make sure I return a ptr from the function so the vector is not deleted when the function ends.

const unique_ptr<vector<string>> loadTransactions(string filename){
    unique_ptr<vector<string>> transactions = make_unique<vector<T>>();
    //some processing
    return transactions;
}
int main(){
    vector<string> allTransactions;
    for(int i =0; i< 10; ++i){
        unique_ptr<vector<string>> transactions = loadTransactions("filename");
        allTransactions.insert(allTransactions.end(), transactions->begin(), transactions->end());
}

Can't assign empty initializer to vector of unique_ptrs

I have the following code:

std::unordered_map<std::string, std::vector<std::unique_ptr<class EventTrigger>>> triggers;

if (triggers.end() == triggers.find(eventName)) {
   triggers[eventName] = {};
}

That results in an error about using a deleted constructor of unique_ptr. If, on the other hand, I do this, everything compiles fine:

if (triggers.end() == triggers.find(eventName)) {
   triggers[eventName] = std::vector<std::unique_ptr<class EventTrigger>>();
}

Can anyone explain why this is happening? I thought the empty initializer list would have resulted in an empty vector being assigned to triggers[eventName].

Python SWIG wrapper for C++ rvalue std::string &&

I'm trying to build a python wrapper for gnucash c++ parts. In QofBackend I encountered the method const std::string && get_message (). This returns <Swig Object of type 'std::string *' at 0x7f4a20f5c9f0> in my setting but I would like to access the string.

I didn't really find a simple explanation so I rebuilt an example setting and dug into c++ which I barely know. I managed to get the string into python but I'd like to know

  • if this typemap(out) approach is correct (also in respect of memory and error handling).
  • The conversion in set_s_workaround() is also just a workaround. I don't think that for gnucash the python code ever needs to set this value but for completeness sake it would be nice to also have a typemap(in) std::string&& and
  • get rid of get_s_workaround.
/* example.hpp */
#include <string>

using namespace std;

struct struct1{
        string s;
        const std::string&& get_s();
        void set_s(string&&);
        void set_s_workaround(string);
        void init_s();
        void print_s();
};

string conv_rvalue_string(string);
/* example.cpp */
#include<iostream> 
#include"example.hpp"

using namespace std; 

void
struct1::set_s (std::string&& msg)
{
     s = msg;
}

std::string
conv_rvalue_string (std::string msg)
{
        return msg;
}

void
struct1::set_s_workaround(std::string msg)
{
        set_s ( conv_rvalue_string(msg) );
}

void
struct1::init_s ()
{
     set_s("Some content");
}

void
struct1::print_s ()
{
     cout<<get_s()<<endl;
}

const std::string&&
struct1::get_s ()
{
    return std::move(s);
}
/* example.i */
%module example

%include "std_string.i"

%typemap(out) std::string&& {
  std::string s = *$1;
  $result = SWIG_From_std_string(s);
}


%{
#include <string>
#include "example.hpp"
%}

%include "example.hpp"
#!/bin/bash
swig3.0 -c++ -shadow -python example.i
g++ -fpic -c example.hpp example.cpp example_wrap.cxx -I/usr/include/python3.7
g++ -shared example_wrap.o example.o -o _example.so 
# example.py
import example

s1 = example.struct1()
s1.set_s3('TEST')
s1.print_s()
print(s1.get_s())

Thanks for the help!

The difference between the type of a reference and its value category [duplicate]

The difference between the type of a reference and its value category

I would be grateful to have some help with this question.

Widget&& var1 = someWidget;      // here, “&&” means rvalue reference
auto&& var2 = var1;              // here, “&&” does not mean rvalue reference

Is there some situation where must use "reference collapsing"?What are the important applications of it?

As the subject,I know a little about the rules of reference collapsing and std::forward.Is there some situation where are neccessary to use reference collapsing?

I am a novice in C++.I would be grateful to have some help with this question.Could somebody make it clear by giving some simple examples?

C++ - How to bind a callback to a class method without being static?

I have my class:

class Foo
{
public:
  (...)    
private:        
    void mycallback(void* buff, wifi_promiscuous_pkt_type_t type);
    void registerMyCallback();
};

The mycallback is the callback.

I want to use a method esp_wifi_set_promiscuous_rx_cb to register the mycallback so that when a WiFi packet is detected, this callback method will be executed.

The esp_wifi_set_promiscuous_rx_cb signature is:

esp_err_t esp_wifi_set_promiscuous_rx_cb(wifi_promiscuous_cb_t cb);

Where the wifi_promiscuous_cb_t definition is:

typedef void (* wifi_promiscuous_cb_t)(void *buf, wifi_promiscuous_pkt_type_t type);

I want to use the mycallback method inside my class, therefore I simply can't use like this:

  void Foo::registerMyCallback()
  {
    esp_wifi_set_promiscuous_rx_cb(&mycallback);
  }

I know that I could use something similar if I would just make my method as static. Is there anyway that I bind mycallback to esp_wifi_set_promiscuous_rx_cb without making the callback static?

I have tried the following:

esp_wifi_set_promiscuous_rx_cb(std::bind(&Foo::mycallback, this, std::placeholders::_1, std::placeholders::_2));

But I am still having the following error:

cannot convert 'std::_Bind_helper<false, void (Foo::Foo::*)(void*, wifi_promiscuous_pkt_type_t), 
Foo::Foo*, const std::_Placeholder<1>&, const std::_Placeholder<2>&>::type 
to 
'wifi_promiscuous_cb_t {aka void (*)(void*, wifi_promiscuous_pkt_type_t)}' for argument '1'

googletest gives either multiple main defination when libgtest_main.a is used or gives undefined reference to testing when libgtest_main.a is not used [duplicate]

I built googletest following the steps given in this link ->

https://www.eriksmistad.no/getting-started-with-google-test-on-ubuntu/

Here is my code

  1 #include <iostream>
  2 #include <vector>
  3 #include "gtest.h"
  4 //#include <gtest.h>
  5
  6 using namespace std;
  7
  8 void expectEqual(int n1, int n2){
  9         if(n1 != n2){
 10          cerr << "Actual value is " << n1 << ", expected " << n2 <<endl;
 11         }
 12 }
 13
 14 int binarySearch(vector <int> &arr, int key){
 15
 16 int low = 0;
 17 int high = arr.size() -1 ;
 18 while(low <= high){
 19         int mid = (low + high) / 2;
 20         if(arr[mid] == key){
 21                 return mid;
 22         } else if (arr[mid] < key){
 23                 low = mid + 1;
 24         }
 25         else {
 26                 high = mid - 1;
 27         }
 28
 29         }
 58
 59 TEST(BinarySearchTest, EmptyVectorTest) {
 60         vector<int> arr;
 61         arr.push_back(5);
 62         expectEqual(binarySearch(arr, 10), -1);
 63 }
 64
 65
 66 /*int main() {
 67
 68         basicTest();
 69         smallVectorTest();
 70         emptyVectorTest();
 71         return 0;
 72 }*/
 73
 74 int main(int argc, char **argv){
 75         ::testing::InitGoogleTest(&argc, argv);
 76         return RUN_ALL_TESTS();
 77 }
 78

This is how I compile it using a bash script ->

  1 #!/bin/bash
  2
  3 INC_DIR=/usr/include/gtest/
  4 LIB_DIR=/usr/lib/
  5
  6 #g++ -std=c++11 -isystem $INC_DIR -pthread -L$LIB_DIR -lgtest -lgtest_main binarySearch.cpp 
    #gives multiple definition of `main'; error

  7 #g++ -std=c++11 -isystem $INC_DIR -pthread $LIB_DIR/libgtest.a binarySearch.cpp
   #gives undefined reference to `testing::InitGoogleTest(int*, char**)'

  8 g++ -std=c++11 -isystem $INC_DIR -pthread $LIB_DIR/libgtest_main.a binarySearch.cpp
   #gives multiple definition of `main'; error

For reference, I am also pasting how LIB and Include path looks -->

storm@storm:~/cpp_ut$ ls /usr/lib/
X11                gnupg
accountsservice    gnupg2
apparmor           gold-ld
apt                groff
bfd-plugins        hdparm
binfmt.d           init
bolt               initcpio
byobu              initramfs-tools
cloud-init         kernel
cnf-update-db      klibc
command-not-found  klibc-xcgdUApi-P9SoPhW_fi5gXfvWpw.so
compat-ld          language-selector
console-setup      libDeployPkg.so.0
cpp                libDeployPkg.so.0.0.0
cryptsetup         libdmmp.so
dbus-1.0           libdmmp.so.0.2.0
dpkg               libgtest.a
dracut             libgtest_main.a
storm@storm:~/cpp_ut$ ls /usr/include/gtest/
gtest-death-test.h  gtest-message.h     gtest-printers.h  gtest-test-part.h   gtest.h            gtest_prod.h
gtest-matchers.h    gtest-param-test.h  gtest-spi.h       gtest-typed-test.h  gtest_pred_impl.h  internal

Every answer that I found on StackOverflow for a similar issue suggests I use either libgtest.a or libgtest_main.a. Both does not resolve my issue.

I apologize for the long question, but I wanted to include all the possible information.

stringstream/libc++ specific optimization, has any sense?

I saw such code in some cross platform C++ project:

#if defined(_LIBCPP_VERSION)
    #define CONCAT(EXPR)   (std::stringstream() << EXPR).str()    
#else
    #define CONCAT(EXPR)   (static_cast<std::stringstream&>(std::stringstream() << EXPR)).str()
#endif

As I understand there is feature/extension in libc++ and operator<< return std::stringstream, instead of std::basic_ostream<char>, but why not use portable variant instead of this extension? What is benefit for libc++?

How to write a platform independent wrapper function in C++

I am using snprintf to send the output to the buffer.

As of now I am doing it only for windows. But from now onwards it has to support for different platforms (Windows, Linux and Mac)

To support for multiple platforms, I am planning to write a wrapper function with #if tags.

but here the challenge I am facing is, when invoking WrapperSprintf from different places of the project the number of parameters are different.

How to write a common wrapper that can be used from different places with different no of parameters passed to WrapperSprintf function?

I tried the wrapper function like as shown below. Please help me how to proceed with this:

void WrapperSprintf( char buffer, MAX_PATH, const char *format, ... )
{
#if defined(_WIN32)
    _snprintf(buffer,MAX_PATH, sizeof(buffer), format,...);
#else
    snprintf(buffer,MAX_PATH, format, ...);
#endif
}

Calling WrapperSprintf function1:

char m_systemTime[20];

char* CUPSManager ::getSystemTime()
{
    time_t rawtime;
    struct tm * timeinfo;
    time ( &rawtime );
    timeinfo = localtime ( &rawtime );

    WrapperSprintf(m_systemTime, MAX_PATH,"%d-%d-%d :%d:%d:%d" , timeinfo ->tm_year +1900,
             timeinfo ->tm_mon +1,
             timeinfo->tm_mday,
             timeinfo->tm_hour,
             timeinfo->tm_min,
             timeinfo->tm_sec);
    return m_systemTime;
}

Calling WrapperSprintf function2:

void getDevicePath()
{
    wstring strDevPath;
    strDevPath = (LPCWSTR)cDevicePath;
    char cDevPath[2048];
    WrapperSprintf(cDevPath, MAX_PATH, "%ls",strDevPath.c_str());
    int nPathLength = strlen(cDevPath);
...
}

samedi 30 mai 2020

Why deadlock on std::this_thread::sleep_for on Visual Studio 2013

The code below can never print m4 (and of course no t2 and t3) on VS 2013. It behaves like a deadlock and I don't know the reason. Is there anything I missed?

#include <mutex>
#include <thread>
#include <chrono>

#include <stdio.h>

std::mutex m;

void work()
{
    printf("t1\n");

    m.lock();
    printf("t2\n");

    m.unlock();
    printf("t3\n");

    return;
}

int _tmain(int argc, _TCHAR* argv[])
{
    printf("m1\n");

    m.lock();
    printf("m2\n");

    std::thread *th = new std::thread(work);
    printf("m3\n");

    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    printf("m4\n");

    m.unlock();
    printf("m5\n");

    while (true);
    return 0;
}

Send string literal as argument in C++ template - Parameter pack

My function declaration and implementation. It accepts variable number of arguments

template <typename... ParamType,
            typename = typename std::void_t<std::enable_if_t<std::is_same_v<ParamType, std::string> ||
                                                            std::is_floating_point_v<ParamType> ||
                                                            std::is_integral_v<ParamType>>...>>
static inline void Log(const ParamType &... args)
{
   //Implementation
}

I need to add support for cstrings(char *, const char *) and string literals.

Console::Log("Non std::string literal"); //ERROR (const char [24])
Console::Log("hola %s %s %d %s"s,"helloWorld"s,"Joma"s,1, 1990); //OK
Console::Log<String, String, String,int, int>("hola %s %s %d %s"s,"helloWorld"s,"Joma"s,1, 1990); //OK

Passing an lvalue to a function accepting a rvalue reference should fail, but doesn't [duplicate]

The following program

#include <iostream>

class C {};

void f(C&& c) {}

int main() {
    C c;
    f(c);

    return 0;
}

outputs the following compilation error on g++:

cannot bind rvalue reference of type 'C&&' to lvalue of type 'C'

That makes sense to me - f() requests an rvalue reference, but we have passed in an lvalue.

However, I encountered an answer on SO where the writer seems to do exactly this - only to have it work. Code from the answer (comments mine):

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

void overloaded_function(std::string& param) {
  std::cout << "std::string& version" << std::endl;
}
void overloaded_function(std::string&& param) {
  std::cout << "std::string&& version" << std::endl;
}

template<typename T>
void pass_through(T&& param) {
  overloaded_function(std::forward<T>(param));
}

int main() {
  std::string pes;
  pass_through(pes); // Calling pass_through(T&&) with an lvalue
  pass_through(std::move(pes));
}

It does compile also on my machine.

So what's happening here - why does the first piece of code fail to compile, while the second one doesn't?

Is it related to the fact that the function in the second instance is templated? And if so, what it the logic behind what's happening?

Template operator overload is not picked up by linker

I have this minimal working example (I deliberately use cstdio here to keep nm output readable):

// main.cpp
#include "cstdio"
#include "foo.hpp"

int main() {
    Foo<int> foo{42};
    Foo<int> bar{42};

    bool b = foo == bar;
    printf("%d\n", b);

    return 0;
}
// foo.hpp
#pragma once

template<typename T>
struct Foo {
    Foo(T foo_) : foo{foo_} {}

    T foo;

    friend bool operator==(const Foo<T> &lhs, const Foo<T> &rhs);
};
// foo.cpp
#include "foo.hpp"

template<typename T>
bool operator==(const Foo<T> &lhs, const Foo<T> &rhs) {
    return false;
}

template struct Foo<int>;
template bool operator==(const Foo<int> &lhs, const Foo<int> &rhs);

And I build it like this:

clang --std=c++2a -lstdc++ main.cpp foo.cpp

It fails with

Undefined symbols for architecture x86_64:
  "operator==(Foo<int> const&, Foo<int> const&)", referenced from:
      _main in main-3d7fff.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

despite I explicitly instantiated operator== template.

I have rebuilt each file separately:

clang --std=c++2a -c main.cpp
clang --std=c++2a -c foo.cpp

And explored both with nm:

main.o: 0000000000000060 T Foo<int>::Foo(int)
main.o: 0000000000000090 T Foo<int>::Foo(int)
main.o:                  U operator==(Foo<int> const&, Foo<int> const&)
main.o: 0000000000000000 T _main
main.o:                  U _printf
foo.o: 0000000000000020 T Foo<int>::Foo(int)
foo.o: 0000000000000000 T Foo<int>::Foo(int)
foo.o: 0000000000000050 T bool operator==<int>(Foo<int> const&, Foo<int> const&)

And despite that two signatures look compatible to me, when I try to link this, it fails:

$ ld -lc foo.o main.o 2>&1 | c++filt
Undefined symbols for architecture x86_64:
  "operator==(Foo<int> const&, Foo<int> const&)", referenced from:
      _main in main.o
ld: symbol(short) not found for architecture x86_64

Why? How can I fix this?

C++ Regex for getting all the header files used in a c program

So far I have found that using grep I can find the header names in a C program.

Regular expression to extract header name from c file

But in the above case the accepted answer uses grep command with some flags. But I want to use this regex in regex_search() of C++ programmatically. But I am unable to convert the regex in the above answer to fit in C++. I want to know how can I convert the above regex to be used in C++.

regex expr(".*#include.*(<|\")\\K.*(?=>|\")");

I have written above regex but it doesn't give the expected output. Basically I read the C file as string and use C++ regex search to extract header names data. Below code explains what I am trying to do...


#include<bits/stdc++.h>

using namespace std;

void searchContent(string content) {
     smatch match;
     regex expr(".*#include.*(<|\")\\K.*(?=>|\")");

     while (regex_search(content, match, expr)) {
          for (auto x : match)
               cout << x << " ";

           cout << std::endl;
           content = match.suffix().str();
     }
}


int main(int argc, char** argv)
{

  std::ifstream ifs("/home/ultraproton/PlacementPrep/C++/regex/testfile.c");
  std::string content( (std::istreambuf_iterator<char>(ifs) ),
                       (std::istreambuf_iterator<char>()    ) );


  searchContent(content);

  return 0;
}

c++ function to find the sum fo four minimum and four maximum elements in an array not working

I am completing a question in which i have to write a function which finds the maximum and minimum sum of four integers in the array and then displays it.

I have written the following code:

void miniMaxSum(vector<int> arr) {

        int minsum=0;
        int maxsum=0;
        int l1,l2,l3,l4;
        int s1,s2,s3,s4;
        l1=arr[0];
        s1=arr[0];
        for(int i=1;i<arr.size();++i)
        {
            if(l1<arr[i])
            l1=arr[i];
            if(s1>arr[i])
            s1=arr[i];
        }
        l2=arr[0];
        s2=arr[0];
        for(int i=1;i<arr.size();++i)
        {
            if(l2<arr[i]&&arr[i]!=l1)
            l2=arr[i];
            if(s2>arr[i]&&arr[i]!=s1)
            s2=arr[i];
        }
        l3=arr[0];
        s3=arr[0];
        for(int i=1;i<arr.size();++i)
        {
            if(l3<arr[i]&&arr[i]!=l2&&arr[i]!=l1)
            l3=arr[i];
            if(s3>arr[i]&&arr[i]!=s2&&arr[i]!=s1)
            s3=arr[i];
        }
        l4=arr[0];
        s4=arr[0];
        for(int i=1;i<arr.size();++i)
        {
            if(l4<arr[i]&&arr[i]!=l2&&arr[i]!=l1&&arr[i]!=l3)
            l4=arr[i];
            if(s4>arr[i]&&arr[i]!=s3&&arr[i]!=s2&&arr[i]!=s1)
            s4=arr[i];
        }
        minsum=s1+s2+s3+s4;
        maxsum=l1+l2+l3+l4;
        cout<<minsum<<" "<<maxsum;
}

this code gives the correct output for maxsum but the minsum is wrong in all the testcases. Can you please help me find the error in the code i have made... Thanks in advance.

need help in c++ matrix division [closed]

i write a code for multiplying matrix and division for 2 3x3 matrices the out put is a 3x3 matrix . the multiplication works well but division doesn't . i tried the inverse code it works alone . but when i put it in function to multiply it by mat1 result is wrong . any help please.i tried to do some more things on the code but it looks like i made a fatal error preventing it to get trure results

#include <iostream>

using namespace std;

int main()
{
    int mat1[3][3], mat2[3][3], x, j, k, sum, sumdiv;
    double mat3[3][3], mat4[3][3], mat5[3][3];
    cout << "Enter values for first 3 x 3 matrix:\n";
    for (x = 0; x <= 2; x++) {
        for (j = 0; j <= 2; j++) {
            cout << "Enter Value For item" << x << ',' << j << "\n";
            cin >> mat1[x][j];
        }
    }
    cout << "\n Enter values for second 3 x 3 matrix:\n";
    for (x = 0; x <= 2; x++) {
        for (j = 0; j <= 2; j++) {
            cout << "Enter Value For item" << x << ',' << j << "\n";
            cin >> mat2[x][j];
        }
    }
    cout << "\n The first 3 x 3 matrix entered by you is:\n";
    for (x = 0; x <= 2; x++) {
        for (j = 0; j <= 2; j++)
            cout << "\t" << mat1[x][j];
        cout << "\n";
    }
    cout << "\n the second 3 x 3 matrix entered :\n";
    for (x = 0; x <= 2; x++) {
        for (j = 0; j <= 2; j++)
            cout << "\t" << mat2[x][j];
        cout << "\n";
    }
    for (x = 0; x <= 2; x++) {
        for (j = 0; j <= 2; j++) {
            sum = 0;
            for (k = 0; k <= 2; k++)
                sum += mat1[x][k] * mat2[k][j];
            mat3[x][j] = sum;
        }
    }
    cout << "\nThe product of the above two matrices is:\n";
    for (x = 0; x <= 2; x++) {
        for (j = 0; j <= 2; j++)
            cout << "\t" << mat3[x][j];
        cout << "\n";
    }

    mat2[0][0] = mat1[1][1] * mat1[2][2] - mat1[1][2] * mat1[2][1];
    mat2[0][1] = -1 * (mat1[1][0] * mat1[2][2] - mat1[1][2] * mat1[2][0]);
    mat2[0][2] = mat1[1][0] * mat1[2][1] - mat1[1][1] * mat1[2][0];
    mat2[1][0] = -1 * (mat1[0][1] * mat1[2][2] - mat1[2][1] * mat1[0][2]);
    mat2[1][1] = mat1[0][0] * mat1[2][2] - mat1[0][2] * mat1[2][0];
    mat2[1][2] = -1 * (mat1[0][0] * mat1[2][1] - mat1[0][1] * mat1[2][0]);
    mat2[2][0] = mat1[0][1] * mat1[1][2] - mat1[0][2] * mat1[1][1];
    mat2[2][1] = -1 * (mat1[0][0] * mat1[1][2] - mat1[0][2] * mat1[1][0]);
    mat2[2][2] = mat1[0][0] * mat1[1][1] - mat1[0][1] * mat1[1][0];

    long int det = mat1[0][0] * mat2[0][0] + mat1[0][1] * mat2[0][1] + mat1[0][2] * mat2[0][2];

    for (int i = 0; i < 3; i++) {
        for (j = 0; j < 3; j++)
            mat4[i][j] = mat2[j][i];
    }

    for (int i = 0; i < 3; i++) {
        for (j = 0; j < 3; j++)
            mat4[i][j] = mat4[i][j] / det;
    }

    for (x = 0; x <= 2; x++) {
        for (j = 0; j <= 2; j++) {
            sumdiv = 0;
            for (k = 0; k <= 2; k++)
                sumdiv += mat1[x][k] * mat4[k][j];
            mat5[x][j] = sumdiv;
        }
    }

    cout << "\nThe division of the above two matrices is:\n";
    for (x = 0; x <= 2; x++) {
        for (j = 0; j <= 2; j++)
            cout << "\t" << mat5[x][j];
        cout << "\n";
    }

    return 0;
}

Using a template with lambda function pointer [duplicate]

I'm playing around with some C++11 features, and I encountered the following:

#include <iostream>
#include <vector>

template <class T>
void map(std::vector<T>& values, T(*func)(T)) { 
    for (int &value : values) {
        value = func(value);
    }
}

int mul2(int x) {
    return 2*x;
}

auto mul3 = [](int value) {
    return value * 3;
};

int main() {
    std::vector<int> v = { 1,2,3,4,5 };
    map(v, mul3);
    for (auto value : v) {
        std::cout << value << std::endl;
    }
}

using map with mul2 works as expected, but when I use the mul3 function it gives a compilation error. I expected that auto in this case would give me a int function pointer, but it seems that is not the case here. Anybody could explain this behaviour?

Among `dctor,copy ctor and copy assignment operator`, why deletes one and leaves the other to be implicitly-defined will most likely result in errors

As per the documentation(https://en.cppreference.com/w/cpp/language/rule_of_three), which says:

Classes that manage non-copyable resources through copyable handles may have to declare copy assignment and copy constructor private and not provide their definitions or define them as deleted. This is another application of the rule of three: deleting one and leaving the other to be implicitly-defined will most likely result in errors.

As the subject, i wonder why it occurs.Could sombody explain it in more detail? Could somebody make it clear by giving some simple example?

Why does copy constructor not need to check whether the input object pointers to itself or not?

As the code below, the copy assignment operator has to check whether the input object pointers to itself or not. I wonder why copy constructor does not need to do the same check.

I am novice in C++.I would be grateful to have some help on this question.

  class rule_of_three
    {
        char* cstring; // raw pointer used as a handle to a dynamically-allocated memory block

        void init(const char* s)
        {
            std::size_t n = std::strlen(s) + 1;
            cstring = new char[n];
            std::memcpy(cstring, s, n); // populate
        }
     public:
        rule_of_three(const char* s = "") { init(s); }

        ~rule_of_three()
        {
            delete[] cstring;  // deallocate
        }

        rule_of_three(const rule_of_three& other) // copy constructor
        { 
            init(other.cstring);
        }

        rule_of_three& operator=(const rule_of_three& other) // copy assignment
        {
            if(this != &other) {
                delete[] cstring;  // deallocate
                init(other.cstring);
            }
            return *this;
        }
    };

Why can't an inherited protected ctor be made public?

class A
{
protected:
    A(int) {}
    void f(int) {}

public:
    A() {}
};

class B : public A
{
public:
    using A::A;
    using A::f;
};

int main()
{
    B().f(1); // ok
    B(1); // error: 'A::A(int)' is protected within this context
}

Why can't an inherited protected ctor be made public, while an inherited protected member function can?

vendredi 29 mai 2020

Why does the compiler complains when `none const copy constructor` is used?

As the subject, the code below is right.

#include<iostream>

class ABC     
{  public:  
    ABC() 
    {
        std::cout<< "default construction" << std::endl;
    }

    ABC(ABC& a) 
    {
        std::cout << "copy construction" << std::endl;
    } 

};                         

int main()   
{  
   ABC c1 = ABC(); 
}

It could not compile successfully:

<source>: In function 'int main()': 
<source>:25:13: error: cannot bind non-const lvalue reference of type 'ABC&' to an rvalue of type 'ABC'
   25 |    ABC c1 = ABC();
      |             ^~~~~
<source>:10:14: note:   initializing argument 1 of 'ABC::ABC(ABC&)'
   10 |     ABC(ABC& a)
      |         ~~~~~^

However, it could compile if replace the ABC(ABC& a) by ABC(const ABC&).I know it has some relation with the keyword const.But i could not figure out why.

You could check it on https://godbolt.org/z/jNL5Bd. I am a novice in C++.I would be grateful to have some help with this question.

C++ return value and move rule exceptions

When we return a value from a C++ function copy-initialisation happens. Eg:

std::string hello() {
    std::string x = "Hello world";
    return x; // copy-init
}

Assume that RVO is disabled.

As per copy-init rule if x is a non-POD class type, then the copy constructor should be called. However for C++11 onward, I see move-constrtuctor being called. I could not find or understand the rules regarding this https://en.cppreference.com/w/cpp/language/copy_initialization. So my first question is -

  1. What does the C++ standard say about move happening for copy-init when value is returned from function?

  2. As an extension to the above question, I would also like to know in what cases move does not happen. I came up with the following case where copy-constructor is called instead of move:

std::string hello2(std::string& param) {
    return param;
}

Finally, in some library code I saw that std::move was being explicitly used when returning (even if RVO or move should happen). Eg:

std::string hello3() {
    std::string x = "Hello world";
    return std::move(x);
}
  1. What is the advantage and disadvantage of explicitly using std::move when returning?

Segmentation fault in dynamic programming

I read that Segmentation fault is a specific kind of error caused by accessing memory that “does not belong to you". I can't figure out which part of this code is causing that error to come up.

What is the error in my dynamic programming implementation? I am writing a program to check if an array can be divided into two subsets with equal sum. If the input is {1, 5, 11, 5} the output is YES, because it can be divide like {1, 5, 5} and {11}.

#include<bits/stdc++.h>
#define ll long long
using namespace std;
bool subsetsum(ll int arr[], ll int sum, ll int n)
{

     int t[n+1][sum+1];
     for(int i = 0; i < n+1; i++)      //INITIALIZATION
     {   for(int j = 0; j < sum+1; j++)
        {
            if(i == 0)
                t[i][j] = false;
            if(j == 0)
                t[i][j] = true;
        }
     }


       for(int i = 1; i < n+1; i++)
    {
        for(int j = 1; j < sum+1; j++)
        {
            if(arr[i-1] <= j)
            {
                t[i][j] = (t[i-1][j-arr[i-1]]) || (t[i-1][j]);
            }
            else
                t[i][j] = t[i-1][j];
        }
    }

    if(t[n][sum])
        return true;
    else
        return false;
 }

 int main()
 {
     ios_base::sync_with_stdio(0);
     cin.tie(0);
     int T;
     cin>>T;
     while(T--)
     {
         ll int n,sum = 0;
         cin>>n;
         ll int arr[n];
         for(int i = 0; i < n; i++)
            cin>>arr[i], sum = sum + arr[i];

         if(sum % 2 != 0)
         {
             cout<<"NO\n";
             continue;
         }

         bool sol = subsetsum(arr,sum/2, n);

         if(sol)
            cout<<"YES\n";
         else
            cout<<"NO\n";
     }

 }


Why `copy constructor` is used while `move constructor` has been removed?

As the subject,the related code is:

#include <iostream>     

class ABC     
{  public:  
    ABC() 
    {
        std::cout<< "default construction" << std::endl;
    }

    ABC(const ABC& a) 
    {
        std::cout << "copy construction" << std::endl;
    } 

    ABC(const ABC&& a) 
    {
        std::cout << "move construction" << std::endl;
    }
};                         

int main()   
{  
   ABC c1 = ABC();  

   return 0;  
}

Output with -fno-elide-constructors -std=c++11

default construction
move construction

If i remove the move constructor above, then the output is:

default construction
copy construction

Why copy constructor is used while move constructor has been removed? As per some documentation,compiler provides a default move constructor.So why don't the compiler use the default move constructor?

I am a novice in C++.I would be grateful to have some help with this question.

Differences between `copy constructor` and `move constructor`.Could anybody make it clear by giving some simple examples [duplicate]

As the subject, I understand copy constructor and I am confused after studying move constructor.

As the code below, i think copy constructor is used to copy the temporary object returned from fun123() to obj1, but it uses move constructor indeed.

I am a novice in C++.I had been confused for a long time.I would be grateful to have some help with this question.

#include <iostream>  
using namespace std;

class ABC  
{  
public:   
    const char *a;  
    ABC()  
     { cout<<"Constructor"<<endl; }  
    ABC(const char *ptr)  
     { cout<<"Constructor"<<endl; }  
    ABC(ABC  &obj)  
     { cout<<"copy constructor"<<endl;}  
    //ABC(ABC&& obj)  
    //{ cout<<"Move constructor"<<endl; }  
    ~ABC()  
    { cout<<"Destructor"<<endl; }  
};

ABC fun123()  
{ ABC obj; return obj; }  


int main()  
{   
    ABC obj1=fun123();//NRVO   
    return 0;  
}

Changes made to member of object, inside object, inside a vector, do not survive end of method. C++

Sorry for the title. I cannot made something more descriptive or clear than that..

I'm trying to do something that resembles a very basic auction.

To simplify things, I'm going to put here the essentials of every class. I'm also translated everything from spanish to english, so if there is a typo, it's only here. The actual code compile fine.

There are four classes involved here:

class Person
{
private:
    std::string name;
}

class Offer
{
private:
    int amount;
    Person *bidder;
}

class Item
{
private:
    int itemNumber;
    std::string itemName;
    Offer *biggestBidder;

public:
    Item(int, std::string)
    void setbiggestBidder(Offer* const &); // I did this '* const &' thing while trying solutions
    Oferta *getBiggestBidder();
}

class Auction
{
private:
    std::vector<Item> itemCollection;
    int amountOfItems; // in above's collection 
}

I didn't put the getters, setters, and constructors/destructors here so it's not too long. Inside Item.cpp I have:

Item::Item(int number, std::string name)
:itemNumber(number), 
itemName(name), 
biggestBidder(NULL)
{
    // this->itemNumber= number;
    // this->itemName= name;
    // this->biggestBidder= NULL;
}

void Item::setbiggestBidder(Offer* const &offer)
{
    if (biggestBidder== NULL || biggestBidder->getAmount() < offer->getAmount())
    {
        std::cout << "Address of offer in setbiggestBidder: " << offer << std::endl;
        std::cout << "Address of biggestBidder in setbiggestBidder: " << (biggestBidder) << std::endl;
        biggestBidder = offer;
        std::cout << "Address of biggestBidder in setbiggestBidder: " << (biggestBidder) << std::endl;
    }
    else
    {
    }
}

Oferta *Lote::getBiggestBidder()
{

    std::cout << "Address of biggestBidder in getBiggestBidder(): " << this->biggestBidder << std::endl;
    if (this->biggestBidder == nullptr)
    {
        std::cout << "biggestBidder IS NULL" << std::endl;
    }
    else
    {
        std::cout << "biggestBidder is NOT NULL" << std::endl;
    }

    return biggestBidder;
}

Now, the main and the problem:

Item l1(111, "BANANA");
Item l2(222, "MESA"); // this number 222 is just an ID for the item. It does nothing
Person p1("TheDude");
Offer of1(100, &p1);

// now put the item inside a vector and create an auction instance
std::vector<Item> item1;
collect.push_back(banana);
Auction coleccion1(collect, collect.size());


/*
Now we are ready. If I do this..
*/

std::cout << "Test with item outside vector" << std::endl;

std::cout << "Bidding $" << of1.getAmount() << " for item number " 
            << l2.getNumber() << ", " << l2.getItemName() << std::endl;

l2.setBiggestBidder(&of1); // amount 100
/*
If here I do 

l2.setBiggestBidder(&of2); // amount 200
l2.setBiggestBidder(&of1); // amount 100

At the bottom of the output, we get 200. It's all good.
*/
std::cout << l2.getBiggestBidder()->getAmount() << std::endl;

/* 
We get this output:
Test with item outside vector
Bidding $100 for item number 222, MESA
Address of offer in setbiggestBidder: 0x66fb20
Address of biggestBidder in setbiggestBidder: 0
Address of biggestBidder in setbiggestBidder: 0x66fb20
Address of biggestBidder in getBiggestBidder(): 0x66fb20
biggestBidder is NOT NULL
200 <-- l2.getBiggestBidder()->getAmount()
*/

// But if we try with the item inside the vector:

std::cout << "Bidding $" << of1.getAmount() << " for item number " 
                << coleccion1.getItemCollection().at(0).getNumber() << ", " 
                    << coleccion1.getItemCollection().at(0).getItemName() << std::endl;

/*
We get:
Test with item in vector
Bidding $100 for item number 111, BANANA
Address of offer in setbiggestBidder: 0x66fb10
Address of biggestBidder in setbiggestBidder: 0
Address of biggestBidder in setbiggestBidder: 0x66fb10
Address of biggestBidder in getBiggestBidder(): 0
biggestBidder IS NULL
0

and here is the issue.
*/

I really do not like having to do a post so large for a problem that I'm sure is about something extremely basic, but I have looked everywhere and cannot find any solution to this problem. It have been weeks since I stumbled upon this.

Why is that everything works fine if I put an item on the method setBiggestBidder, but the change does not survive the end of the method when I put an item that is inside of a vector? And how can I fix it?

pcl::CropBox does not erase points outside of the box

I am trying to filter out a specific area using pcl::CropBox and only show the points within an established box, but something is not totally correct. The point clouds are coming from a lidar sensor. The lidar is in a fixed position as shown below and all points in the box that I would like to keep are in the yellow box (coordinates are also shown). All points outside of the box should not be visible or erased. The sensor is in a (0,0,0) position and represents the origin for XYZ in red below.

Below and in the box the area I am trying to keep:

cropbox

Below the code I am using to do the filtering and the steps are:

1) Acquiring point clouds - it works

2) Filtering and downsampling: I filter only the point on 180 degree facing upward and filtering in all XYZ direction establishing limits - it works

3) Establishing a fixed box using pcl::CropBox and keep only the points inside the box above - it does not work as I still see all the points outside the box

processlidar.h

class SubscribeProcessPublish
{

public:
    SubscribeProcessPublish();
    pcl::PointCloud<pcl::PointXYZ> filterPointCloudData(const pcl::PCLPointCloud2ConstPtr& cloud);
    void processLidarMeasurementCallBack(const pcl::PCLPointCloud2ConstPtr& cloud);
    void removePointsOutsideBox();
}

processlidar.cpp

void SubscribeProcessPublish::removePointsOutsideBox()
{
    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_xyz_toRemove (new pcl::PointCloud<pcl::PointXYZ>);
    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_xyz_removed (new pcl::PointCloud<pcl::PointXYZ>);
    pcl::fromPCLPointCloud2(*cloud_xyz_toRemove, *cloud_xyz_removed);

    pcl::CropBox<pcl::PointXYZ> boxFilter;
    // Establishing the size of the CropBox
    float x_min = 0.0,  y_min = -25.0, z_min = -1.5;
    float x_max = 50.0, y_max = +25.0, z_max = +1.5;
    boxFilter.setMin(Eigen::Vector4f(x_min, y_min, z_min, 1.0));
    boxFilter.setMax(Eigen::Vector4f(x_max, y_max, z_max, 1.0));
    boxFilter.setInputCloud(cloud_xyz_toRemove);
    boxFilter.filter(*cloud_xyz_removed);
    std::cout<<"Box established"<<std::endl;
    std::cout<<"Constantly Keeping only points inside the box"<<std::endl;
}


pcl::PointCloud<pcl::PointXYZ> SubscribeProcessPublish::filterPointCloudData(const pcl::PCLPointCloud2ConstPtr& cloud)
{

    // Before establishing the XYZ limits we already have the box defined above
    removePointsOutsideBox()

    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_xyz_filtered (new pcl::PointCloud<pcl::PointXYZ>);
    pcl::fromPCLPointCloud2(*cloud, *cloud_xyz_filtered);

    // define a PassThrough
    pcl::PassThrough<pcl::PointXYZ> pass;
    // set input to cloudVoxel
    pass.setInputCloud(cloud_xyz_filtered);
    // filter along z-axis
    pass.setFilterFieldName("z");
    pass.setFilterLimits(z_min, z_max);
    pass.filter(*cloud_xyz_filtered);

    // filter along y-axis
    pass.setFilterFieldName("y");
    pass.setFilterLimits(y_min, y_max);
    pass.filter(*cloud_xyz_filtered);

    // filter along x-axis
    pass.setFilterFieldName("x");
    pass.setFilterLimits(x_min, x_max);
    pass.filter(*cloud_xyz_filtered);

    // cascade the floor removal filter and define a container for floorRemoved
    pcl::PCLPointCloud2::Ptr filtered_cloud (new pcl::PCLPointCloud2 ());
    // copy the contents of the cloud_xyz_filtered to filtered_cloud
    pcl::toPCLPointCloud2(*cloud_xyz_filtered, *filtered_cloud);

    // define a voxelgrid
    pcl::VoxelGrid<pcl::PCLPointCloud2> voxelGrid;
    // set input to cloud
    voxelGrid.setInputCloud(filtered_cloud);
    // set the leaf size (x, y, z)
    voxelGrid.setLeafSize(0.1, 0.1, 0.1);
    // apply the filter to dereferenced cloudVoxel
    voxelGrid.filter(*filtered_cloud);

    pcl::PointCloud<pcl::PointXYZ> pclXYZ;
    pcl::fromPCLPointCloud2(*filtered_cloud, pclXYZ);

    this->publisher.publish (*filtered_cloud);

    return pclXYZ;
}

What I have done so far:

Before arriving to the code I posted above I had to do a lot of research on how to use the filtering functions of pcl. At first I did the tutorial related to the filtering part and creating the voxels and extablishing the XYZ limits I wanted. Very useful posts were this one, also this one.

I went through the official documentation of pcl and consulted CropBox API but also went ahead and consulted this.

The following source was also useful but could still not figure out why it is not working.

However there is something missing that is preventing me from seeing only the points in the box. Please point to the right direction for solving this problem.

Overload of a nested template function

I was thinking a lot what title to put on my question and failed anyway, so if you find a good one, please edit it.

I am trying to write a print function for a vector or other container<T> and have another print function for container<container<T>>, so here what I came up with:

template<typename T>
void print(T const& cont){
    for (const auto& i : cont) {
        cout << i << " ";
    }
    cout << endl;
}

template<typename T, template<typename> typename Cont>
void print(Cont<T> const& cont) {
    for (const auto& i : cont) {
        print(i);
    }
}

and I have my 2 target containers here:

vector<vector<int>> subsets;
vector<int> subset;

When I invoke print(subset); the program works as expected, but when i invoke print(subsets), compiler starts complaining:

error C2679: binary '<<': no operator found which takes a right-hand operand of type 'const std::vector<int,std::allocator<int>>' (or there is no acceptable conversion)

My conclusion is that its still trying to call the non-nested template print function and failing on cout as I am trying to cout a vector.

Can anyone explain why the overload resolution is not working as I expect and what I did wrong here? Even when I rename the nested-template function to printn, its started to complain for a different reason:

error C2784: 'void prints(const Cont<T> &)': could not deduce template argument for 'const Cont<T> &' from 'std::vector<std::vector<int,std::allocator<int>>,std::allocator<std::vector<int,std::allocator<int>>>>'

How can you bind exceptions with custom fields and constructors in pybind11 and still have them function as python exception?

This appears to be a known limitation in pybind11. I read through all the docs, whatever bug reports seemed applicable, and everything I could find in the pybind11 gitter. I have a custom exception class in c++ that contains custom constructors and fields. A very basic example of such a class, trimmed for space is here:

class BadData : public std::exception
{
  public:
    // Constructors
    BadData()
      : msg(),
        stack(),
        _name("BadData")
    {}

    BadData(std::string _msg, std::string _stack)
      : msg(_msg),
        stack(_stack),
        _name("BadData")
    {}

    const std::string&
    getMsg() const
    {
      return msg;
    }

    void
    setMsg(const std::string& arg)
    {
      msg = arg;
    }

    // Member stack
    const std::string&
    getStack() const
    {
      return stack;
    }

    void
    setStack(const std::string& arg)
    {
      stack = arg;
    }
  private:
    std::string msg;
    std::string stack;
    std::string _name;

I currently have python binding code that binds this into python, but it is custom generated and we'd much rather use pybind11 due to its simplicity and compile speed.

The default mechanism for binding an exception into pybind11 would look like

py::register_exception<BadData>(module, "BadData");

That will create an automatic translation between the C++ exception and the python exception, with the what() value of the c++ exception translating into the message of the python exception. However, all the extra data from the c++ exception is lost and if you're trying to throw the exception in python and catch it in c++, you cannot throw it with any of the extra data.

You can bind extra data onto the python object using the attr and I even went somewhat down the path of trying to extend the pybind11:exception class to make it easier to add custom fields to exceptions.

  template <typename type>
  class exception11 : public ::py::exception<type>
  {
   public:
    exception11(::py::handle scope, const char *name, PyObject *base = PyExc_Exception)
      : ::py::exception<type>(scope, name, base)
    {}

    template <typename Func, typename... Extra>
    exception11 &def(const char *name_, Func&& f, const Extra&... extra) {
      ::py::cpp_function cf(::py::method_adaptor<type>(std::forward<Func>(f)),
                            ::py::name(name_),
                            ::py::is_method(*this),
                            ::py::sibling(getattr(*this, name_, ::py::none())),
                            extra...);
      this->attr(cf.name()) = cf;
      return *this;
    }
  };

This adds a def function to exceptions similar to what is done with class_. The naive approach to using this doesn't work

    exception11< ::example::data::BadData>(module, "BadData")
      .def("getStack", &::example::data::BadData::getStack);

Because there is no automatic translation between BadData in c++ and in python. You can try to work around this by binding in a lambda:

    .def("getStack", [](py::object& obj) {
      ::example::data::BadData *cls = obj.cast< ::example::data::BadData* >();
      return cls->getStack();
    });

The obj.cast there also fails because there is no automatic conversion. Basically, with no place to store the c++ instance, there isn't really a workable solution for this approach that I could find. In addition I couldn't find a way to bind in custom constructors at all, which made usability on python very weak.

The next attempt was based on a suggestion in the pybind11 that you could use the python exception type as a metaclass a normal class_ and have python recognize it as a valid exception. I tried a plethora of variations on this approach.

py::class_< ::example::data::BadData >(module, "BadData", py::dynamic_attr(), py::reinterpret_borrow<py::object>(PyExc_Exception))
py::class_< ::example::data::BadData >(module, "BadData", py::dynamic_attr(), py::cast(PyExc_Exception))
py::class_< ::example::data::BadData >(module, "BadData", py::dynamic_attr(), py::cast(PyExc_Exception->ob_type))
py::class_< ::example::data::BadData>(module, "BadData", py::metaclass((PyObject *) &PyExc_Exception->ob_type))

There were more that I don't have saved. But the overall results was either 1) It was ignored completely or 2) it failed to compile or 3) It compiled and then immediately segfaulted or ImportError'd when trying to make an instance. There might have been one that segfaulted on module import too. It all blurs together. Maybe there is some magic formula that would make such a thing work, but I was unable to find it. From my reading of the pybind11 internals, I do not believe that such a thing is actually possible. Inheriting from a raw python type does not seem to be something it is setup to let you do.

The last thing I tried seemed really clever. I made a python exception type

  static py::exception<::example::data::BadData> exc_BadData(module, "BadDataBase");

and then had my pybind11 class_ inherit from that.

  py::class_< ::example::data::BadData >(module, "BadData", py::dynamic_attr(), exc_BadData)

But that also segfaulted on import too. So I'm basically back to square one with this.

Error in comparing two std::chrono::time_point instances

I have two std::chrono::time_point instances in variables exp and time. exp has a time in the future and time is the current time. But when I compare them as in this snippet:

std::time_t t_exp = std::chrono::system_clock::to_time_t(exp);
std::time_t t_time = std::chrono::system_clock::to_time_t(time);
std::cout << std::ctime(&t_exp) << std::ctime(&t_time) << (time > exp) << std::endl;

I get output:

Sat Apr 26 01:39:43 4758
Fri May 29 18:11:59 2020
1

Which is wrong because exp is in the year 4758 and time is in the year 2020.

Where am I going wrong?

How to find tha't circular list's begin?

I'm trying to implement about list and iterator of list like C++ STL.

The node in list is defined like this:

struct Node{
  Node *prev,*next;
  value_type data;
};

And I want to overloading operator > and < :

bool list_iterator::operator>(const iterator_impl_base &rhs) const
bool list_iterator::operator<(const iterator_impl_base &rhs) const

which means if I need to call next to reach rhs.node , it will return 0 in > and return 1 in <.

if I need to call prev to reach rhs.node , it return 1 in > and return 0 in <.

And I implement list using circular list. Below is one part of list class :

class List : public ordered_container {
 protected:
  Node* begin_;
  Node* end_;
  size_type size_;
 public:
    List::List() : end_(new Node){
        begin_ = end_->prev = end_->next = end_;
        size_=0;
    }
}

So , I don't know how to distinguish whether I just pass the begin_ of list. Can someone help me about that? Thankyou.

jeudi 28 mai 2020

there is no cout appear

istringstream stm(data) ;
while( stm >> hadis )// read white-space delimited tokens one by one
{
  cout << hadis <<endl;
  string query1 = "SELECT kata FROM totalkata_malik2 WHERE kata='"+hadis+"'";
  mysql_query(conn, query1.c_str()); //mysql_query(conn,"SELECT kata FROM totalkata_malik2 WHERE kata='"+hadis1+"'");
  ress = mysql_store_result(conn);
  while ((roww = mysql_fetch_row(ress)))
  {
     if (roww[0] == NULL)
       cout << "ok" ;
     else
       cout << "not";
  }
}

this is my code and i dont know why my cout can not be read by system, therefore there is no nothing appear as the result. i run this program to check whether succeed or not.

UVa Problem- 673 - Parentheses Balance. I have no idea about what I did wrong

I have been solving some UVa problems. 673 - Parentheses Balance is one of them. But I got WA. I have no idea about what I did wrong. I checked my code several times, but I have no clue where did I messed up. I also checked on uDebug. For all test cases, I have got the correct output. But when I submit my code, I got WA. Please help me. I am new in Programing.

Here is the problem link

Here is my code. Thank You.

#include <bits/stdc++.h>

using namespace std;

bool checkBalance(char *line)
{
    int arr[129], pointer = 0;

    for (int i = 0; line[i] != '\n'; i++)
    {
        if (line[i] == '(')
            arr[pointer++] = 1;
        else if (line[i] == ')' && arr[pointer - 1] == 1 && i)
            arr[--pointer] = 0;
        else if (line[i] == '{')
            arr[pointer++] = 2;
        else if (line[i] == '}' && arr[pointer - 1] == 2 && i)
            arr[--pointer] = 0;
        else if (line[i] == '[')
            arr[pointer++] = 3;
        else if (line[i] == ']' && arr[pointer - 1] == 3 && i)
            arr[--pointer] = 0;
        else if (line[i] != '(' && line[i] != ')' && line[i] != '[' && line[i] != ']')
            continue;
        else
            return false;
    }
    if (!pointer)
        return true;
    else
        return false;
}

int main()
{
    //freopen("input.txt", "r", stdin);

    int test;
    scanf("%d", &test);
    getchar();

    while (test--)
    {
        char ch[129];
        fgets(ch, sizeof(ch), stdin);

        if (checkBalance(ch))
            printf("Yes\n");
        else
            printf("No\n");
    }
    return 0;
}

Differences between return value optimization and `std::move`?

What are the differences between return value optimization and std::move? Do they depend on same internal implementation?

I understand that there are many places where must use std::move.

std::move and RVO both could achieve copy elision.For example, T Func() {return T();} T t=Func();.I think i could not figure out which method the compiler really uses.

I am a novice in C++.I would be grateful for any hint on this question.

Reducing the time complexity of the program

I am doing this practice problem where given a string s of lowercase letters, and a position p, I have to print all the occurrences of the letter at position p which occur before the position p.

Eg: If the string is "abaac" and p=3(1 based index) then output is 1 because 'a' occurs one time before the position p.

There are q queries each giving me a position p. Is there any way to make this code more efficient?
I'm using hashing which is pretty efficient I think? Is there any algorithm that I am not aware of?

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    cin>>n;
    string s;
    cin>>s;
    int q;
    cin>>q;
    while(q--)
    {
        int p;
        cin>>p;
        int freq[26] = {0};
        for(int i = 0; i<(p-1); i++)
            freq[s[i]-'a']++;
        cout<<freq[s[p-1]-'a']<<"\n";
    }

}

Loosing references to objects inside containers

I am struggling fixing a piece of code, even though I believe I know the cause. I did search a lot on Stack Overflow and many people had similar issues (and good answers were provided), but still, I am not sure I understand the problem with my code. I tried giving a smaller example, but the structure I have is not simple by itself. I hope the following is simple enough.

My objective on the excerpt:

  • Have a vector of points.

  • Have a vector of segments. (Whose endpoints are reference to points in the vector above)

  • Have a vector of events. (That keep a reference to the exhisting segments and points)

segment::segment (point &pt1, point&pt2, int i) {
   s = &pt1; e = &pt2; ind = i; // point *s, point *e, int ind
}
event::event (segment &s, point &pt, int tp) {
   seg = &s; type = tp; p = &pt; //segment *seg, int type, point *p
}
void pre_process (int size, std::vector<point>& pts, std::vector<event>& evts,
        std::vector<segment>& segs) {
    float x, y;
    for (int i = 0; i < size; ++ i) {
        std::cin >> x >> y;
        pts.push_back({x,y});
    }
    for (int i = 0; i < size; ++i) {
        int j = (i+1)%size;
        if (cmpXY(pts[i], pts[j]))
            segs.push_back({pts[i], pts[j], i});
        else
            segs.push_back({pts[j], pts[i], i});
        evts.push_back({segs[i], *segs[i].s, 0});
        evts.push_back({segs[i], *segs[i].e, 1});
        std::cout << 2*i << "\n";
        std::cout << segs[i].s << "\n";       //ALWAYS EQUAl
        std::cout << evts[2*i].seg->s << "\n";
    } // LINE X
    for (int i = 0; i < size; ++i) { //LINE Y
        std::cout << 2*i << "\n";
        std::cout << segs[i].s << "\n";        //DIFFERENT SOMETIMES
        std::cout << evts[2*i].seg->s << "\n";
    }

So, the problem is that some of addressess my objects are pointing to change from LINE X to LINE Y. In particular, pts and segs remain the same.

From what I know and from what I understood here or here I cannot get the refeerence to an object on the stack of any function (my for loop, for example). However, I believe the lifetime of the object on the container is the same as the container itself. It makes me believe that all objects I push_back() should persist through the funtion pre_proccess and the function that is calling it.

Given a periphery of island mark its interior in matrix (Algorithm)

We are given a matrix of size N which is completely filled with 0's and we are also given a list of coordinates which contains the coordinates of the periphery of an island. Now we have to mark the island (periphery + area that is part of the island) as 1's.

I am having trouble coming up with a solution to this problem, I thought of bfs/dfs but can't think of a way to implement this. (Please assume that there is 1 island only and the input is correct i.e. all input coordinates form a closed shape and are valid

N = 5
coordinates = 
0,2
1,1
1,3
2,0
2,4
3,1
3,3
4,2

So this is what output should look like ---

    0 1 2 3 4
  0 0 0 1 0 0
  1 0 1 1 1 0 
  2 1 1 1 1 1 
  3 0 1 1 1 0 
  4 0 0 1 0 0 

All the coordinates marked and the square boxes inside them marked which are a part of the island.

Unicode problem when using cppimport/pybind11

I am trying to use cppimport, an lib based on pybind11, to import some *.cpp files directly into python, according to the author's example.

I am using Pycharm and python 3.7, installed both cppimport and pybind11, win10.
The import code is quite easy using cppimport.

import cppimport.import_hook
import DemoTrade

Then I got an error

mako.exceptions.CompileException: Unicode decode operation of encoding 'ascii' failed in file 'C:\Users\...\DemoTrade.cpp' at line: 0 char: 0

The files address is right, otherwise it will give another error

The problem seems in the coding of files, I changed other encoding, but nothing improved.
I don't know how to deal with this. Thank you for your help.

C2280 std::unique_ptr

I'm trying to make Ticket Reservation System. However, I have an error about C2280.

On TicketReservation, I'm adding TicketManagers with std::vector.

It works fine without TicketResetvation, but with it, error uccred.

I found when error occured, but I don't know how to fix it.

void TicketReservation::addManager(TicketManager tm)
{
    std::cout << tm.getName() << std::endl;   // works.
    managers.push_back(tm);   // error occured.
}

And the error:

C2280 std::unique_ptr<Ticket,std::default_delete<Ticket>>::unique_ptr(const std::unique_ptr<Ticket, std::default_delete<Ticket>> &)'

1>        with
1>        [
1>            _Alloc=std::allocator<std::unique_ptr<Ticket,std::default_delete<Ticket>>>,
1>            _Ty=std::unique_ptr<Ticket,std::default_delete<Ticket>>,
1>            _Objty=std::unique_ptr<Ticket,std::default_delete<Ticket>>
1>        ]

1>        with
1>        [
1>            _Alloc=std::allocator<std::unique_ptr<Ticket,std::default_delete<Ticket>>>,
1>            _Ty=std::unique_ptr<Ticket,std::default_delete<Ticket>>,
1>            _Objty=std::unique_ptr<Ticket,std::default_delete<Ticket>>
1>        ]

1>        with
1>        [
1>            _Ty=std::unique_ptr<Ticket,std::default_delete<Ticket>>
1>        ]


I tried with managers.emplace_back(tm.getName(), tm.getNumber()); but same error.

Also I tried create every default constructor, but same error.

I don't know what is wrong..

Thank you for your help.

Here's my code :

#include <iostream>
#include "TicketReservation.h"
#include "TicketManager.h"
int main()
{
    TicketReservation tickets;
    tickets.addManager(TicketManager("Test A", 10));
    tickets.addManager(TicketManager("Test B", 5));
    tickets.addManager(TicketManager("Test C", 10));
...
}
#pragma once
class Ticket
{
protected:
    int number;     
    static int fNumber; 
    double price;       
public:

    Ticket() = delete;
    Ticket(const double& price);

    virtual ~Ticket();

...
};

#pragma once
#include "Ticket.h"
#include <vector>
#include <string>
#include <memory>
class TicketManager
{
private:
    std::string m_name;         
    int totalNumber;            
    std::vector<std::unique_ptr<Ticket>> ticket;
public:
    TicketManager() = delete;
    ~TicketManager();
    TicketManager(const std::string& name, const int& number);
    TicketManager(const TicketManager& tm);
    TicketManager(TicketManager&& tm) noexcept;

...
};
std::ostream& operator<<(std::ostream& out, const TicketManager& manager);

#include "TicketManager.h"
#include <iostream>
#include "AdvancedTicket.h"
#include "GeneralTicket.h"

TicketManager::~TicketManager()
{
}

TicketManager::TicketManager(const std::string& name, const int& number)
    : m_name(name), totalNumber(number)
{
}

TicketManager::TicketManager(const TicketManager& tm)
    : TicketManager(tm.getName(), tm.getNumber())
{
    for (auto it = tm.ticket.begin(); it < tm.ticket.end(); it++) {
        this->ticket.push_back(*it);
    }
}

TicketManager::TicketManager(TicketManager&& tm) noexcept
    : m_name(tm.m_name), totalNumber(tm.totalNumber)
{
}
...

Returning value from lambda in the same line with declaration

Sometimes it is easier to represent a value by function, and lambdas are good for this. But is there any way to return value from lambda declaration?

for example:

int i = []{return 2;};

generates an error. How to make that lambda declaration return 2 without any new lines of code?

QML/QT Best Practices, for desktop application?

I am designing a desktop application to do many things! One involves an initial setup that you have to do once, while the rest is loaded in through AWS, once that one time configuration is done. Coming from a web developer background, I am very used to creating new states throughout an application.

I feel though I would be doing wrong and not following a standard that seems to have been set in QT/QML. Right now I am scaffolding my app to use multiple QML files with .ui.qml files in each one + passing the engine (QQmlApplicationEngine) as a raw pointer throughout my application. My application plans to have multiple different views and states based on data. What would be the right approach in this situation? one single QML with multiple windows to load? or am I on the right track?

mercredi 27 mai 2020

C++: undefined reference to the functor's overloaded invocation operator

template <typename T>
class Predicate {
   public:
    bool operator()(const T& x) const;
};

template <typename T>
class LessThan : public Predicate<T> {
   public:
    explicit LessThan(const T& v) : val(v) {}
    bool operator()(const T& x) const { return x < val; }

   private:
    const T val;
};

template <typename C, typename T>
class Producer {
   public:
    T operator()(const C& c) const;
};

template <typename C, typename V>
class HowMuch : public Producer<C, int> {
   public:
    explicit HowMuch(Predicate<V> p) : predicate{p} {}
    int operator()(const C& c) const {
        int count = 0;
        for (const auto& x : c)
            if (predicate(x)) ++count;
        return count;
    }

   private:
    Predicate<V> predicate;
};

int main() {
    const LessThan<int> lf(5);
    const HowMuch<list<int>, int> hm(lf);
    list<int> li {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    cout << "How much numbers less than 5 is in {1, 2, 3, 4, 5, 6, 7, 8, 9, "
            "10}? Answer: "
         << hm(li)
         << endl;
}

When compiling the aforementioned code g++ prints this to the console:

/tmp/ccblK6El.o: In function HowMuch<std::__cxx11::list<int, std::allocator<int> >, int>::operator()(std::__cxx11::list<int, std::allocator<int> > const&) const: templates.cpp:(.text._ZNK7HowMuchINSt7__cxx114listIiSaIiEEEiEclERKS3_[_ZNK7HowMuchINSt7__cxx114listIiSaIiEEEiEclERKS3_]+0x84): undefined reference to Predicate<int>::operator()(int const&) const collect2: error: ld returned 1 exit status The terminal process terminated with exit code: 1

I can't quite get what is the problem with Prediate<V> definition inside HowMuch, because for me (a newbie in C++) it really looks LGTM. From my understanding the compiler creates a definition of Predicate<int> as a separate type, and the logs say exactly that, but for some reason it can't find the typed definition of the overloaded invocation operator. May be the problem is with the type deduction? Template of a container template type itself has to be somehow explicitly defined?

EDIT:

virtual modifier was added to both Predicate's and Producer's function operator overloads, but the problem, as it seems, persists. The error "description" (if it can be called as helpful description) is changed a bit, however (but still it points to the same problem):

/tmp/ccn1Swqa.o: In function HowMuch >, int>::operator()(std::__cxx11::list > const&) const: templates.cpp:(.text._ZNK7HowMuchINSt7__cxx114listIiSaIiEEEiEclERKS3_[_ZNK7HowMuchINSt7__cxx114listIiSaIiEEEiEclERKS3_]+0x76): undefined reference to Predicate::operator()(int const&) const /tmp/ccn1Swqa.o:(.rodata._ZTV8ProducerINSt7__cxx114listIiSaIiEEEiE[_ZTV8ProducerINSt7__cxx114listIiSaIiEEEiE]+0x10): undefined reference to Producer >, int>::operator()(std::__cxx11::list > const&) const /tmp/ccn1Swqa.o:(.rodata._ZTV9PredicateIiE[_ZTV9PredicateIiE]+0x10): undefined reference to Predicate::operator()(int const&) const collect2: error: ld returned 1 exit status The terminal process terminated with exit code: 1

Differences between `typename std::remove_reference

As per the documentation(https://en.cppreference.com/w/cpp/utility/move), there are two kinds of constructors for std::move<T>, which are posted below.

What are the differences between these constructors? What confused me most is that why there needs the keyword(typename) in the second constructor.

I am a novice in C++.I would be thankful for any hint on this question.

template< class T >
typename std::remove_reference<T>::type&& move( T&& t ) noexcept;    (since C++11)     (until C++14)
template< class T >
constexpr typename std::remove_reference<T>::type&& move( T&& t ) noexcept;    (since C++14)

Is declaring a reference and passing it in the same as just passing by reference?

Say you have a function like this:

void func(int & arg) {
    std::cout << arg << std::endl;
}

Is doing something like:

int x = 10;
int & y = x;

func(y);

the same as:

int x = 10;

func(x)

Does arg become a int && arg or does it stay a int & arg when you pass in a pre-declared reference like the first case?

Knapstack implementation in c++ using memoization

What is the difference between doing int t[102][1002] = {-1}; vs running a for loop and doing

for(int i = 0; i < 102; i++)
        for(int j = 0; j < 1002; j++)
            t[i][j] = -1;

The code below does not work when the former method is used. It works only when we I loop through and initialize. Why is that?

#include<bits/stdc++.h>
using namespace std;
int t[102][1002] = {-1};
int knapstack(int wt[], int val[], int w, int n)
{
    if(n == 0 || w == 0)
        return 0;

    if (t[n][w] != -1)
        return t[n][w];

    if(wt[n-1] <= w ){
        t[n][w] = max(val[n-1] + knapstack(wt,val, w - wt[n-1],n-1) , knapstack(wt, val, w, n-1));
        return t[n][w];
    }

    if(wt[n-1] > w){
       t[n][w] = knapstack(wt,val,w,n-1); 
       return t[n][w];
    }
}

int main()
{
    int wt[] = {10, 20, 30};
    int val[] = { 60, 100, 120};
    int w = 50, n = sizeof(val)/sizeof(val[0]);
    cout<< knapstack(wt, val, w, n);
}

How to assign values to the data elements of a structure

I have a structure

struct MyStruct
{
    int intValue1;
    float floatValue2;
    std::string stringValue3;
} Structure;

Now based on the value input of two strings, I want to assign values to the data elements of the structure:

std::string varName = "intValue1";
std::string varValue = "5";

So based on the two strings the "intValue1" should get a value of 5

Structure.intValue1 = (int)varValue;

Is it possible to write a function which would automatically assign values to the structure based on the input strings, e.g.:

 void SetData( std::string varName , std::string varValue );

Insert in unordered map when expanding a macro in global scope

I have a macro that creates functions which are then called from an executable via the function name in command line arguments. A minimal example is:

#include <iostream>

#define MAKE_FUNCTION(func_name, custom_message) \
void func_name(){std::cout << #custom_message << std::endl;}

MAKE_FUNCTION(func_foo, "foo called")
MAKE_FUNCTION(func_bar, "bar called")

std::function<void()> get_function_from_string(std::string func_string){
    if(func_string == "func_foo")
        return func_foo;
    else if(func_string == "func_bar")
        return func_bar;
}

int main(int argc, char* argv[]) {
    get_function_from_string(argv[1])();
}

This is now run with

$./a.out func_foo
"foo called"

I want to do this without the help of the get_function_from_string function. For this I tried creating a static unordered map:

#include <iostream>
#include <unordered_map>

static std::unordered_map<std::string, std::function<void()> > global_map;

#define MAKE_FUNCTION(func_name, custom_message) \
void func_name(){std::cout << #custom_message << std::endl;} \
global_map[func_name] = func_name;

MAKE_FUNCTION(func_foo, "foo called")
MAKE_FUNCTION(func_bar, "bar called")

int main(int argc, char* argv[]) {
    global_map[argv[1]]();
}

But this does not compile saying:

$./a.out func_foo
error: C++ requires a type specifier for all declarations
MAKE_FUNCTION(func_bar, "bar called")

Is there a convenient way to do this?

How are lambda captures initialised in case of nested lambdas?

Okay, so this is right off the bat from [expr.prim.lambda]p16 in n3337.pdf. Below code is given as an example:

int a = 1, b = 1, c = 1;
auto m1 = [a, &b, &c]() mutable
{
    auto m2 = [a, b, &c]() mutable
    {
        std::cout << a << b << c;     // Shouldn't this print 113 or 133?
        a = 4; b = 4; c = 4;
    };
    a = 3; b = 3; c = 3;
    m2();
};
a = 2; b = 2; c = 2;
m1();
std::cout << a << b << c;             // Okay, this prints 234

and that it shall generate below output:

123234

However, the way I have understood the text in [expr.prim.lambda] (which is somehow obviously flawed), I feel the output should be 113234, specifically the value of b printed in m2. Below is my understanding/explanation:

When std::cout << a << b << c; is executed inside m2, as per [expr.prim.lambda]p16 (emphasis mine):

If a lambda-expression m2 captures an entity and that entity is captured by an immediately enclosing lambda expression m1, then m2’s capture is transformed as follows:

if m1 captures the entity by copy, m2 captures the corresponding non-static data member of m1’s closure type;

Therefore, the a inside m2 shall capture the member generated to the corresponding a captured in the closure type m1. Since, a in m1 captures by copy, therefore a's value in m2 should be 1.

The standard goes on to say (again, emphasis mine):

if m1 captures the entity by reference, m2 captures the same entity captured by m1.

I believe "same entity" here refers to the entity captured by m1 via reference and that m2 shall also be a reference to the same entity if it's a capture by reference, or a copy of it if it's a capture by copy.

Therefore for b in m2 shall refer to the b defined outside both lambdas. The value of b in m2 then should be 1 as this should be equivalent to capture by copy.

Where am I going wrong? More specifically, when is b inside m2 initialised?

How to fix complexity exception thrown by std::regex?

I am playing around with std::regex,

regex e("([a-z]|[0-9]|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|[0-9]|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*");
bool matched = regex_match("!#$%&'*+-/=\?^_`{|}~]", e);

However, I am getting exception:

C++ exception with description "The complexity of an attempted match against a regular expression exceeded a pre-set level.

Is there a way to raise the complexity level? How do I fix this?

Update: the regex in the example above is only part of the whole regex:

^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$

This regex is meant to validate against an email address... It is a standard enforced by my employer...

CMakeFiles: undefined reference to 'include header file' on running make [duplicate]

My CMakeLists.txt

cmake_minimum_required(VERSION 3.10)

# set the project name and version 
project(test1 VERSION 1.0)

# specify the C++ standard 
set(CMAKE_CXX_STANDARD 11) 
set(CMAKE_CXX_STANDARD_REQUIRED True) 
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D_UNIX_ -D_LINUX_")


include_directories("/opt/workswell/wic_sdk/include/"
                  "/opt/pleora/ebus_sdk/Ubuntu-x86_64/include/"
                          ) 
link_directories("/opt/workswell/wic_sdk/lib/"
                  "/opt/pleora/ebus_sdk/Ubuntu-x86_64/lib/")

add_executable( test1 test_cam.cpp)

where the header files and libraries are pointing to the WIC sdk

my Source file : test_cam.cpp

#include <pthread.h>
#include <iostream>
#include <string>
#include <jpeglib.h>
#include "CameraCenter.h"

int main() {
    uint16_t *buffer;

    cout << "WIC_SDK_Sample" << endl;

    //creates a list of connected camera objects
    CameraCenter *cameras = new CameraCenter("/opt/workswell/wic_sdk/sample/src/"); // Path to folder containing license file

    cout << "Number of detected cameras: " << cameras->getCameras().size() << endl;

    if (cameras->getCameras().size() == 0) {
        cout << "No camera found!" << endl;
        return -1;
    }
}

where CameraCenter header file is from the sdk

on running cmake.. it configures and generates properly but on doing make it gives error:

[ 50%] Linking CXX executable test1
CMakeFiles/test1.dir/test_cam.cpp.o: In function `main':
test_cam.cpp:(.text+0x7d): undefined reference to `CameraCenter::CameraCenter(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
collect2: error: ld returned 1 exit status
CMakeFiles/test1.dir/build.make:94: recipe for target 'test1' failed
make[2]: *** [test1] Error 1
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/test1.dir/all' failed
make[1]: *** [CMakeFiles/test1.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2

Solution tried:

added target_link_libraries

target_link_libraries(test1 "/opt/workswell/wic_sdk/lib/libWIC_sdk.so"
                      "/opt/pleora/ebus_sdk/Ubuntu-x86_64/lib/"  )

New Error in make :

make[2]: *** No rule to make target '/opt/workswell/wic_sdk/lib/libWIC_sdk.so', needed by 'test1'.  Stop.
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/test1.dir/all' failed
make[1]: *** [CMakeFiles/test1.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2

P.S. the header file is pointing to the sdk

Please suggest what could be the problem here,and how can I resolve it, as it is not able to connect to the header files

How to comprephend these ways could eliminate most need for explicit std::move? Could anybody make it clear by some simple examples?

How to comprephend these ways(including not making variables’ scopes needlessly large, writing short functions that return values, returning local variables) could eliminate most need for explicit std::move?

Could anybody make it clear by some simple examples?I am a novice in C++.I would be grateful for any hint on this question. For your convenience, I post all the quotes below.

Moving is done implicitly when the source is an rvalue (e.g., value in a return treatment or a function result), so don’t pointlessly complicate code in those cases by writing move explicitly. Instead, write short functions that return values, and both the function’s return and the caller’s accepting of the return will be optimized naturally. In general, following the guidelines in this document (including not making variables’ scopes needlessly large, writing short functions that return values, returning local variables) help eliminate most need for explicit std::move.

function pointer to overloaded static member - to use as custom deleter in unique_ptr

I have a class with static and overloaded member function. I want to use one them as a custom deleter in a unique_ptr there are lots of questions on this topic, none of them worked for me.

#include <iostream>
#include <memory>
#include <functional>

class A {
    public:
    static void release() {
        std::cout << "void released\n";
    }
    static void release(int*i) {
        std::cout << *i << " released\n";
    }
};

int main()
{
    int i = 10;
    std::unique_ptr<int, decltype(&A::release(int*))> ptr(&i, &A::release); // compiler error
    std::unique_ptr<int, std::function<void(int*)>> ptr(&i, &A::release); // compiler error
    return 0;
}

try it out here: https://onlinegdb.com/H14txk3sL

Passing in enum parameter value to function C++

I have an enum defined as

enum daysOfTheWeek
{
 MONDAY,
 TUESDAY,
 WEDNESDAY,
 THURSDAY,
 FRIDAY,
}

and a function that gets the price of an item based on the day of the week

void GetPriceOfTheItem(daysOfTheWeek currentDay)
{

}

Somewhere in the code, I am running a for loop like this :

for (long day = MONDAY; day < FRIDAY ; day ++)
{
 if (day == Tuesday || day == Friday)
 { 
   GetPriceOfTheItem(day);
 }

My problem is that I can not pass day to the function, as it is incomaptible with parameter of type daysOfTheWeek, which makes sense, but I was wondering how could I do what I'm trying, without specifically passing in both Tuesday and Friday

Retrieving object back without serialization and copy

I am working on a software stack where it is composed of three different entities:

  1. abc_data - holding the data as "plain" data structure
  2. abc_instance - acting as an API
  3. abc_repo - for internal conversions from abc_data to abc_instance. It includes methods using logic for an easy access and queries of the data (e.g., get_a() or get_b())

When creating a new abc_instance from abc_data, the abc_repo converts the abc_data to a different internal representation for fast access (e.g., vectors, maps) without holding the original abc_data representation anymore. However, this way it is not possible to go back to abc_data from a abc_instance.

What would be the best and elegant way to retrieve the abc_data back from a formerly created abc_instance, ideally without any further conversion.

NOTE: Please understand that I don't want to use de/serialization here. Also keeping a copy of the abc_data is not an option.

Any pointers and help would be appreciated. Thanks in advance!

C++11 Cereal Serialization - versioning

I have successfully serialized two members of my class.

    archive(
        cereal::make_nvp("width", m_width),
        cereal::make_nvp("height", m_height),
    );

Now, in a later version my code contains more members and I would like to archive them as well:

    archive(
        cereal::make_nvp("width", m_width),
        cereal::make_nvp("height", m_height),
        cereal::make_nvp("lambda0", m_lambda0),
        cereal::make_nvp("phi1", m_phi1)
    );

However, this crashes as the new members are not present in old archives. As far as I know there is no way of having default values defined for these variables in make_nvp.

But there for sure has to be some kind of versioning so that this default circumstance can be solved? Could someone point me to the documentation of this or even better to some sample code? I can't find anything on there official website. ( But most likely I am just blind .. )

How to estimate worst case memory usage?

My project includes around 50 files and are written with C++11 standards. Now its being migrated to use C++17 and one major change is to use polymorphic memory resource with a custom allocator. However, I need to first know the worst case heap memory usage in the current implementation to allocate memory size for the new pmr resource. I need to know all the heap allocations including:

  1. Default new allocator
  2. std::vector and other std containers that use default allocator which again use new
  3. Smart pointers (make_shared and similar)
  4. Any other

Is there an open source tool or library or technique to know the heap allocations in cycle?

mardi 26 mai 2020

Differences among `unique_ptr

What are the differences among unique_ptr<Sample> sp1(new Sample); unique_ptr<Sample> sp1(new Sample()); and , unique_ptr<Sample> sp2(new Sample{});? I found that they are both legal indeed.You could check it on http://cpp.sh/3icui.

I am a novice in C++.I thought over and over but still could get the idea.I would be thankful for any hint on this question.

#include <iostream>
#include <vector>
#include <memory>
#include <cstdio>
#include <fstream>
#include <cassert>
#include <functional>

using namespace std;

class Sample {
public:
    Sample() { cout << "Sample Constuctor" << endl; }
    ~Sample() { cout << "Sample Destructor" << endl; }
    void publicFn() { cout << "This is public function of class" << endl; }
};
int main() {
    unique_ptr<Sample> sp1(new Sample{});
    unique_ptr<Sample> sp2(new Sample());
    unique_ptr<Sample> sp3(new Sample);
    sp1->publicFn();
    sp2->publicFn();
    return 0;
}

C++, problems with structures in classes

everyone if someone can help me I'll be very grateful. I've been trying to fill in the structure called m_Center by a function of the same class, I'm using eclipse to work and it gave the next errors messages:

-'m_Center' was not declared in this scope
-Field 'radius' could not be resolved
-Symbol 'm_Center' could not be resolved

My header file is Obstacles.h:

#ifndef SRC_OBSTACLES_H_
#define SRC_OBSTACLES_H_

#include <eigen3/Eigen/Dense>
#include <iostream>
#include <random>
#include <list>
#include <stdlib.h>
#include <time.h>

class CObstacles
{
protected:
    struct Center
    {
        float m_vXdCenterX;
        float m_vXdCenterY;
        float m_vXdCenterZ;
        double distance;
        Eigen::VectorXf v_XfAxisCyl;
        Eigen::VectorXf vXfP1;
        double radius;
    };
    Center m_Center;

public:
    CObstacles(double dradius, Eigen::VectorXf &m_vXdMaxBound, Eigen::VectorXf &m_vXdMinBound, int num_obstacles);
    ~CObstacles();

    void generate_obstacles(double dradius, Eigen::VectorXf &m_vXdMaxBound, Eigen::VectorXf &m_vXdMinBound, int num_obstacles);
};


#endif

while the Obstacles.cpp is:

#include "Obstacles.h"

CObstacles::CObstacles(double dradius, Eigen::VectorXf &m_vXdMaxBound, Eigen::VectorXf &m_vXdMinBound, int num_obstacles)
{
    double m_dradius = dradius;
    Eigen::VectorXf m_dvXdMaxBound = m_vXdMaxBound;
    Eigen::VectorXf m_dvXdMinBound = m_vXdMinBound;
    int dnum_obstacles = num_obstacles;
}

CObstacles::~CObstacles()
{
}

void generate_obstacles(double dradius, Eigen::VectorXf &m_vXdMaxBound, Eigen::VectorXf &m_vXdMinBound, int num_obstacles)
{
    srand(time(NULL));
    float aux_centerx, aux_centery;
    Eigen::Vector3f vXfP1;
    Eigen::Vector3f vXfP2;
    Eigen::Vector3f distance;
    for(int num_obs = 0; num_obs < num_obstacles; num_obs++)
    {
        aux_centerx = rand() % 20 + 1;
        aux_centery = rand() % 20 + 1;
        vXfP2 << aux_centerx, aux_centery, 0;
        vXfP1 << aux_centerx, aux_centery, 0;
        distance = vXfP2 - vXfP1;
        m_Center[num_obs].radius = dradius;
    }
}

Crash when using std::map clear [closed]

The following is the bt I've got from gdb, but I don't know how to check with real reason behind the problem, anyone please help me to solve it?

BTW, std::map<unsigned char,unsigned char> m_cDataFrame is my map data, and I use std::pair<unsigned char,unsigned char> to update map data.

    at /opt/fsl-imx-xwayland/4.14-sumo/sysroots/aarch64-poky-linux/usr/include/c++/7.3.0/bits/stl_tree.h:1856
#1  0x0000ffffbd2ea688 in std::_Rb_tree<unsigned char, std::pair<unsigned char const, unsigned char>, std::_Select1st<std::pair<unsigned char const, unsigned char> >, std::less<unsigned char>, std::allocator<std::pair<unsigned char const, unsigned char> > >::_M_erase (this=this@entry=0x44b940, __x=0x41f3c00)
    at /opt/fsl-imx-xwayland/4.14-sumo/sysroots/aarch64-poky-linux/usr/include/c++/7.3.0/bits/stl_tree.h:1856
#2  0x0000ffffbd2ea5fc in std::_Rb_tree<unsigned char, std::pair<unsigned char const, unsigned char>, std::_Select1st<std::pair<unsigned char const, unsigned char> >, std::less<unsigned char>, std::allocator<std::pair<unsigned char const, unsigned char> > >::clear (this=0x44b940)
    at /opt/fsl-imx-xwayland/4.14-sumo/sysroots/aarch64-poky-linux/usr/include/c++/7.3.0/bits/stl_tree.h:1171
#3  std::map<unsigned char, unsigned char, std::less<unsigned char>, std::allocator<std::pair<unsigned char const, unsigned char> > >::clear (this=0x44b940)
    at /opt/fsl-imx-xwayland/4.14-sumo/sysroots/aarch64-poky-linux/usr/include/c++/7.3.0/bits/stl_map.h:1128
#4  UcomDataProcess::SetDataFrame (this=this@entry=0x44b930, sDataFrame=...) at UcomDataProcess.cpp:182
#5  0x0000ffffbd2eadfc in DataReceiveThread::DataUnpack::UnpackDataCore (this=0x41fda40, sDataFrame=...)
    at DataReceiveThread.cpp:184
#6  0x0000ffffbeb3bfd4 in ?? () from /usr/lib/libQt5Core.so.5
#7  0x0000ffffbeb37288 in ?? () from /usr/lib/libQt5Core.so.5
#8  0x0000ffffbe258f78 in start_thread (arg=0xffffbcacb706)
    at /usr/src/debug/glibc/2.27-r0/git/nptl/pthread_create.c:463
#9  0x0000ffffbe835e2c in thread_start () at ../sysdeps/unix/sysv/linux/aarch64/clone.S:78```

How to set default parameters In case a user does not type in the other one

#include <iostream>

class Person {
    friend std::ostream &operator<<(std::ostream &os, const Person &person);
    std::string name;
    int age;
public:
    std::string get_name () {return name;}
    int get_age() {return age;}
    Person() : name{"Unknown"}, age{0} {}
    Person(std::string name, int age) : name{name}, age{age} {}
};

std::ostream &operator<<(std::ostream &os, const Person &person) {
    os << person.name << ": " << person.age;
    return os;
}

int main () {
    Person Austin{"Austin", 12}; 
}

I am trying to have it where for my name I type in "Austin", but If I don't type in age it will automatically make it a 0 because I did not enter a age.

C++11: properly expand template parameter pack in trailing return type

I am trying to translate run-time constant to compile-time constant in my C++11 program using switch statement. I have enum SomeEnum {A, B, C};, and depending on its value I want to call the template function f<A>(), f<B>() or f<C>(). I have lots of template functions in my code that depend on SomeEnum (as well as other template parameters), so I decided to make dedicated dispatch function. Here is the code I am trying to compile:

#include <utility>

enum SomeEnum {
      A, B, C
};

template<template<SomeEnum, typename...> class FUNCTOR, typename ...OTHERS, typename ...ARGS> inline auto dispatch (
    SomeEnum const type,
    ARGS&&... args
) -> decltype( FUNCTOR<A, OTHERS...>::function(std::forward<ARGS>(args)...) ) { //Problem here
    switch(type) {
        case A:
            return FUNCTOR<A, OTHERS...>::function(std::forward<ARGS>(args)...);
        case B:
            return FUNCTOR<B, OTHERS...>::function(std::forward<ARGS>(args)...);
        case C:
            return FUNCTOR<C, OTHERS...>::function(std::forward<ARGS>(args)...);
        default:
            //Do not call any function if enum value is wrong, just return something:
            return decltype( FUNCTOR<A, OTHERS...>::function(std::forward<ARGS>(args)...) )();
    }
}

template<SomeEnum T> struct TemplateFunctor1 {
    static inline int function(int) { return 0; }
};

template<SomeEnum T, class OTHER> struct TemplateFunctor2 {
    static inline int function(int) { return 0; }
};

int main(void) {
    dispatch<TemplateFunctor1>(B, 0); //Problem here!

    dispatch<TemplateFunctor2, int>(B, 0);

    return 0;
}

(I do not need to handle the case when function return type depends on template parameter)

I am getting an error while compiling the line dispatch<TemplateFunctor1>(B, 0);, where is only one template parameter required by TemplateFunctor1. The error messages are following:

error: no matching function for call to 'dispatch(SomeEnum, int)'

note: candidate: template<template<SomeEnum <anonymous>, class ...> class FUNCTOR, class ... OTHERS, class ... ARGS> decltype (FUNCTOR<(SomeEnum)0u, OTHERS ...>::function((forward<ARGS>)(dispatch::args)...)) dispatch(SomeEnum, ARGS&& ...)

note: template argument deduction/substitution failed

error: wrong number of template arguments (2, should be 1) in this part of code: FUNCTOR<A, OTHERS...> of trailing return type.

So I tried to change FUNCTOR<A, OTHERS...> in trailing return type to FUNCTOR<A>, then the line dispatch<TemplateFunctor2, int>(B, 0); cannot be compiled. It says that I provided wrong number of template parameters (1, should be 2), which is quite an expected error.

What I do not understand here is why the same decltype() construction works in default switch branch, but does not work in the trailing return type?

I can fix my code by changing the standard to C++14 and by removing trailing return type completely, but then I will not understand what is going on here.

I also tried different compilers (ICC, GCC, Clang), and all of them giving similar error messages, so it cannot be a compiler error here.