mardi 31 mars 2020

how str.length() works, calculates string length()?

Suppose i created a string of size n initially, Question1: Can i change it length() by any method? (since it is just an array of characters, So n must be an upper limit of string) so is there any way of reducing str.length() result?

question2: if so, then how str.length() calculates length, if it calculates by finding '\0' , then if i change any in between character to '\0' , can n be reduced?

I know i asked in very confusing way. But an answer from basics will be helpful! Thank you

how to define a class that can convert to any type?

I want to make a class which can convert to any type/class.

struct any{
  template<typename T>
  operator T(){
    return T();
  }
};

struct S{};
void f(const S&){}
f(any());  //ok
//but if no default constructor  will make error
struct S{
  S()=delete;
};
void f(const S&){}
f(any());  //error

How can i solve this problem to make a class which can convert to any type/class?

C++ Precision on stol and stoi for user input

Trying to parse a float out of a String, it returns with a precision of 0 , I'm looking for 0.0 .

Code:

queue<Car> getInputData() {
    string input;
    string line;
    string delin = " ";
    string::size_type sz = 0.0; 
    int counter = 0;
    queue<Car> cars;
    while (getline(std::cin, line) && !line.empty()) 
        {
        if (counter != 0)
            {
            queue<string> parse = getStringList(line, " ");
            _directions dir;
            int cid = std::stoi(parse.front());
            parse.pop();
            long arriv = std::stoi(parse.front()); //This returns 1 rather than 1.1
            parse.pop();
            dir.start = parseToDirection(parse.front(), true);
            parse.pop();
            dir.end = parseToDirection(parse.front(), false);
            parse.pop();
            Car car = Car(dir, cid, arriv);
            cars.push(car);

        }
        counter++;
    }
return cars; 
}

Sample Input:

cid arrival_time dir_original dir_target

0 1.1 ^ ^

1 2.0 ^ ^

2 3.3 ^ <

3 3.5 v v

4 4.2 v >

5 4.4 ^ ^

6 5.7 > ^

7 5.9 < ^

What I've tried: I've tried stol, stoi, stold, stod and none of them work for precision. Is this possible? Or is there a work around that I'm missing?

How do i fix this: "g++ error: C:/mingw64/include,: no file or directory" and also "g++ error: C:/SFML-2.4.0/include: no such file or directory"?

I need help with this. I need to add it to my path but I can't figure out how to include it in my path. I have tried C:/SFML excetra excatera but i can't figure it out.

C++ - begin() returns the end() iterator with a non-empty list

As the question suggest, I'm having a very strange behavior with iterators and lists. So, the (class) problem asks for a function that erase all elements that meet a condition from a list and, when I tried to cover the case where I have a list where all elements are the same I found out that the last element persisted.

Here is the code:

void esborra_tots(list<Estudiant>& t, int x) {
    list<Estudiant>::iterator it;
    list<Estudiant>::iterator itend = t.end();

    for (it = t.begin(); it != t.end(); it++) {
        if ((*it).consultar_DNI() == x) {

            t.erase(it);
            if (t.empty()) return;
            else it = t.begin();
        }
    }
}

I've used itend just to see the value while debugging. Here is the session: See that the list *t* is not empty but t.begin() returns the same as t.end()

How is this possible? PD: I'm not searching for other approaches to the problem.

State Design Pattern GTEST issues

I've been trying to work with a state pattern design where an order switches between Incart, Pending and Complete. The code compiles, but when I test I keep getting segmentation faults and I cannot wrap my head around what exactly I am doing wrong. I could really use some help in fixing my errors. This is my code for the following classes

Order.h

#ifndef ORDER_H
#define ORDER_H
#include "State.h"
#include "ShippingMethod.h"
#include "Paper.h"
#include <string>
#include <vector>

class State;

class Order {
 public:
    Order()
    Order(int weight);
    virtual ~Order();
    void setState(State* state);
    void addProduct(Paper*p);
    void edit(Paper*p, int v);
    void submit();
    void cancel(Paper *p);
    void addToWaitlist();
    std::string orderStatus();
    std::string getShippingMethod() {
        return method;
    }
    int OrderSize();
    int productLocation(Paper *p);

 private:
    State* currentState;
    ShippingMethod * shipMethod;
    std::string method;
    std::vector<Paper*> orders;
};
#endif

Order.cpp

#include "Order.h"
#include "State.h"
#include "Paper.h"
#include "ShippingMethod.h"
#include "Inventory.h"
#include <string>

class State;

Order::Order(int weight) {
  shipMethod = new ShippingMethod();
  shipMethod->setShippingMethod(weight);
  method = shipMethod->getShippingMethod();
  currentState == NULL;
}

Order::~Order() {
    for (unsigned int i = 0; i < orders.size(); i++) {
        delete orders[i];
        orders[i] = NULL;
     }
    delete currentState;
    delete shipMethod;
    shipMethod == NULL;
    currentState == NULL;
}

void Order::setState(State* s) {
        currentState = s;
}

void Order::addProduct(Paper *p) {
    if (currentState->addProduct()) {
       orders.push_back(p);
    } else {
        std::cout << "Cannot add product to a complete order" << std::endl;
    }
}

void Order::edit(Paper *p, int v) {
    int loc;
    if (currentState->cancel()) {
    loc = Order::productLocation(p);
    orders.at(loc)->setQuantity(v);
    std::cout << "Order has been edited" << std::endl;
    } else {
        std::cout << "Cannot order complete order" <<std::endl;
    }
}

void Order::submit() {
    if (currentState->submit()) {
        std::cout<< "Order has been submitted" << std::endl;
    } else {
        std::cout << "Order has already been submitted" << std::endl;
    }
}

void Order::cancel(Paper *p) {
  if (currentState->cancel()) {
    int loc;
    loc = Order::productLocation(p);
    orders.erase(orders.begin() + loc);
    std::cout<< "Order has been cancelled" << std::endl;
  } else {
      std::cout << "Order has been completed.. cannot be cancelled" <<std::endl;
  }
}

void Order::addToWaitlist() {
    if (currentState->addToWaitlist()) {
        std::cout <<"Order has been added to waitlist";
    } else {
        std::cout << "Order has already been added to waitlist ";
    }
}

int Order::productLocation(Paper *p) {
    int index;
    for (unsigned int i = 0; i < orders.size(); i++) {
        if (orders[i]->getProductName() == p->getProductName()) {
            index = i;
        }
    }
    return index;
}

std::string Order::orderStatus() {
      this->currentState->display();
}

int Order::OrderSize() {
    return orders.size();
}

State.h

#ifndef STATE_H
#define STATE_H
#include "Order.h"
#include "Paper.h"
#include <iostream>
#include <vector>
#include <string>

class Order;

class State {
 public:
    virtual bool addProduct() = 0;
    virtual bool edit() = 0;
    virtual bool submit() = 0;
    virtual bool cancel() = 0;
    virtual bool addToWaitlist() = 0;
    virtual std::string display() = 0;
};
#endif

Incart.h

#ifndef INCART_H
#define INCART_H
#include "State.h"
#include "Paper.h"
#include <string>


class Incart : public State {
 public:
    Incart(Order* o);
    virtual ~Incart();
    bool addProduct();
    bool edit();
    bool submit();
    bool cancel();
    bool addToWaitlist();
    std::string display() {
        return "In Cart";
    }

 private:
    Order* currentState;
};
#endif

Incart.cpp

#include "State.h"
#include "Order.h"
#include "Incart.h"
#include "Pending.h"
#include <string>
#include <iostream>

Incart::Incart(Order *o) {
    currentState = o;
}

Incart::~Incart() {
    currentState = NULL;
}

bool Incart::addProduct() {
    return true;
}

bool Incart::edit() {
    return true;
}

bool Incart::submit() {
    this->currentState->setState(new Pending(currentState));
    return true;
}

bool Incart::cancel() {
    return true;
}

bool Incart::addToWaitlist() {
    currentState->setState(new Pending(currentState));
    return true;
}

TestOrder.cpp

#include "Order.h"
#include "Paper.h"
#include "ShippingMethod.h"
#include "State.h"
#include "Pending.h"
#include "Complete.h"
#include "Incart.h"
#include "gtest/gtest.h"

TEST(TestOrder, testConstructor) {
    Paper* p = new Paper("Kleenex", 10, 10);
    Order* o = new Order(100);
    EXPECT_TRUE(o != NULL);
}

TEST(TestOrder, testPendingState) {
    Paper* p = new Paper("Kleenex", 10, 10);
    Order* o = new Order(100);
    o->setState(new Pending(o));
//SEG FAULT HERE    EXPECT_EQ("Pending", o->orderStatus());

}

TEST(TestOrder, testCompleteState) {
}

TEST(TestOrder, testShippingMethod) {
}

TEST(TestOrder, testSubmit) {
}

TEST(TestOrder, TestAddOrder) {
}
TEST(TestOrder, TestCancelOrder) {
}

TEST(TestOrder, TestEditOrder) {
}

TEST(TestOrder, addToWaitlistOrder) {
}

Analyze store instruction consisting inttoptr in LLVM

I am trying to analyze a byte code consisting of a store instruction with inttoptr. I am having trouble to detect whether a store instruction has the inttoptr value as the value operand (3rd instruction in the following code in entry BB). My opcode looks like the following:

define dso_local i32 @test(i32* %p) #0 {
entry:
  %p.addr = alloca i32*, align 8
  store i32* %p, i32** %p.addr, align 8
  store i32* inttoptr (i64 1000 to i32*), i32** %p.addr, align 8
  %0 = load i32*, i32** %p.addr, align 8
  %1 = load i32, i32* %0, align 4
  ret i32 %1
}

I am trying to analyze the store instruction and trying to find whether inttoptr is in a store instruction by using classof method and with dyn_cast like the following code:

  StoreInst *store = dyn_cast<StoreInst>(I);
  Value *vv = store->getValueOperand();
  Value *vp = store->getPointerOperand();
  if(IntToPtrInst::classof(vv)){
    outs() << "Inttoptr found\n";
  }
  if(Instruction *inp = dyn_cast<IntToPtrInst>(vv)){
    outs() << "Inttoptr found\n";
  }

It seems I am not being able to detect inttoptr with any of the methods. I know the byte code is not creating a separate instruction for the inttoptr but it is merging with the store instruction. It would be really nice if anyone points me what I am missing and how I can detect the inttoptr in a store instruction.

C++ none of the 2 overloads can convert all the argument type

when I use a "std::vector" as a parameter of a function, error always exists:C2665,none of the 2 overloads can convert all the argument type. Is there something wrong, when I use the vector as the function parameter?

first.cpp

template<typename Geotype> bool Blocks<GeoType>::update(const GeoType &New){
  std::vector<Geotype>Temp;
  ...
  result = li::ki::UpdateGeo(Temp);// where error exists
  }

first.h

template <typename GeoType>
class Block : public IBlock{

public:

bool update(const GeoType &New);
Geotype result;
}

second.cpp

namespace li{
namespace ki{

interface::Ring UpdateGeo(std::vector<interface::Ring> &Container) {
interface::Ring result=Container.back();
return result;
}}}

Workaround for selecting template function implementation on MSVC++ 10.0

My purpose is to select different function implementation based on the memeber variable of data structure. I use member selection idiom "CREATE_MEMBER_DETECTOR" to detect if a data struct has certain member. In my case is to detect member base inside struct A_t and B_t (both of which has it) and member play_id inside base (A_t does not have play_id).The implementation below works on compiler MSVC++ 14.24. How can I make it work also on the old compiler MSVC++ 10.0, which yields tons of error on visual studio 2010.enter image description here

// templ_derive.h
#include <type_traits>

struct A_base_t {
    int id;
};
struct A_t {
    A_base_t base;

};

struct B_base_t {
    int play_id;
};
struct B_t {
    B_base_t base;
};

#define CREATE_MEMBER_DETECTOR(X)                                                   \
template<typename T> class Detect_##X {                                             \
    struct Fallback { int X; };                                                     \
    struct Derived : T, Fallback { };                                               \
                                                                                    \
    template<typename U, U> struct Check;                                           \
                                                                                    \
    typedef char ArrayOfOne[1];                                                     \
    typedef char ArrayOfTwo[2];                                                     \
                                                                                    \
    template<typename U> static ArrayOfOne & func(Check<int Fallback::*, &U::X> *); \
    template<typename U> static ArrayOfTwo & func(...);                             \
  public:                                                                           \
    typedef Detect_##X type;                                                        \
    enum { value = sizeof(func<Derived>(0)) == 2 };                                 \
};

CREATE_MEMBER_DETECTOR(base);
CREATE_MEMBER_DETECTOR(play_id);

template<typename T, bool>
struct use_base_s {
    static void valid(T data) {
        printf("bast t \n");
    }
};

template<typename T>
struct use_base_s <T, true> {

    static void valid(T data) {
        printf("no base t \n");
    }

    template<typename U = T>
    static void select_play_id(U data,
        typename std::enable_if<Detect_play_id<decltype(U::base)>::value,
        std::nullptr_t>::type = nullptr) {
        printf("has player_id t \n");
        return;
    }
    template<typename U = T>
    static void select_play_id(U data,
        typename std::enable_if<!Detect_play_id<decltype(U::base)>::value,
        std::nullptr_t>::type = nullptr) {
        printf("no player_id t \n");
        return;
    }
};

// main.cpp
#include "templ_derive.h"
int main() {
    A_t a_o = A_t();
    B_t b_o = B_t();
    use_base_s<A_t, Detect_base<A_t>::value>::select_play_id(a_o);
    use_base_s<B_t, Detect_base<B_t>::value>::select_play_id(b_o);
}

really appreciate Any help!

Segmentation Fault accessing qpscale_table in AVFrame

I'm modifying this file slightly: https://gist.github.com/yohhoy/f0444d3fc47f2bb2d0e2 This code decodes a video and makes opencv Mats out of the frame pixels as it goes.

In particular I only want to grab frames that have specific macroblock-related data. I'm attempting to get that data like this:

total_qp = get_total_qp(decframe->qscale_table, mb_width, mb_height, mb_stride);

However, whenever I try to access the data by iterating over that array, I get a segmentation fault:

static float get_total_qp(int8_t *qscale_table, int mb_width, int mb_height, int mb_stride)
{
    int mb_count = mb_height * mb_width;
    int y, x;
    float qp_total = 0.0f;
    for (y = 0; y < mb_height; y++) {
        for (x = 0; x < mb_width; x++) {
            qp_total += qscale_table[x + y * mb_stride]; <-- SEGFAULT here
        }
    }
    return qp_total;
}

I've also tried sending in: frame->qscale_table

and I've tried populating it, but this own't compile because it can't find that function:

int8_t *qscale_table = av_frame_get_qp_table(decframe->qscale_table, &mb_stride, &qscale_type);

So my question is this: Given an AVFrame* how do I ensure that the qscale_table is populated and access it?

exited, segmentation fault

The input for this problem is a first number that indicates how many cases will be input to be analyzed.

Input:

3
8 12
9 27
259 111

The first number means that there will be 3 cases. The next 3 lines are the cases. The program has to output the GCD (Greatest Common Divisor) of the 3 cases.

4
9
37

The code I wrote looks like the following:

#include <iostream>
#include <vector>

int gcd(int a, int b) {
   if (b == 0)
      return a;
   return gcd(b, a % b);

}

int main() {

   int N;

   std::cin >> N;

   int i = 0;

   std::vector<int> cards;

   while (i <= N) {
      i++;
      int F1, F2;
      std::cin >> F1 >> F2;
      cards[i] = gcd(F1, F2);
   }

   for (int j; j <= N; i++) {
      i++;
      std::cout << cards[i] << "\n";
   }
}

It reads the first integer (number of test cases), runs the loop once (reads one test case) and stops running. The terminal outputs exited, segmentation fault. What is the problem?

Variadic Tuples Implementation

I've been trying to use Variadic Tuples on Generic Templates and Structs. The idea is to obtain the max and sum of a variadic tuple. So far I was able to obtain the required results but had to use Global static variables. I've posted the code below of the implementation.

    #include <iomanip>
    #include <complex>
    #include <cmath>
    #include <tuple>
    #include <string>
    #include <iostream>

    using namespace std;
    using namespace std::complex_literals;

    template<typename T>
    static T max;

    template<typename T>
    static T sum;

    template<typename T>
    static T average;

    template <typename T, typename Tuple, std::size_t N>
    struct Calculator
    {
    static void maximum(const Tuple& pack)
    {
    Calculator<T, Tuple, N - 1>::maximum(pack);
    T packValue = get<N - 1>(pack);
    if (packValue > max<T>)
    {
    //T max = get<0>(pack);
    //Try the above instead of the below code to calculate max
    max<T> = get<N - 1>(pack);
    }
    }

    static void summation(const Tuple& pack)
    {
    Calculator<T, Tuple, N - 1>::summation(pack);
    T packValue = get<N - 1>(pack);
    sum<T> += packValue;
    }

    static void averager(const Tuple& pack)
    {
    average<T> = sum<T> / N;
    }


    };

    template<typename T, typename Tuple>
    struct Calculator<T, Tuple, 1>
    {
    static void maximum(const Tuple& pack)
    {
    //T max = get<0>(pack);
    //Try the above instead of the below code to calculate max
    max<T> = get<0>(pack);
    }

    static void summation(const Tuple& pack)
    {
    sum<T> = get<0>(pack);
    }
    };




    int main()
    {
    tuple<double, double, double, double, double, double, double> t1 = make_tuple(16565.256, 45.539,     0.25, 1000.25, 1.25036, 35.66, 210.20);

    Calculator<double, tuple<double, double, double, double, double, double, double>, 7>::maximum(t1);

    cout << "Maximum is: " << max<double> << endl;

    Calculator<double, tuple<double, double, double, double, double, double, double>, 7>::summation(t1);
    cout << "Total Sum is: " << sum<double> << endl;

    Calculator<double, tuple<double, double, double, double, double, double, double>, 7>::averager(t1);
    cout << "Average is: " << average<double> << endl;



    std::complex<int> c2(22, 3);
    std::complex<int> ci(15, 41);
    tuple<std::complex<int>, std::complex<int> > ct1 = make_tuple(ci, c2);

    Calculator< std::complex<int>, tuple<std::complex<int>, std::complex<int> >, 2>::summation(ct1);

    cout << "Summation of complex numbers is: " << sum<std::complex<int>> << endl;

    }

My question, is it possible to implement a version that doesn't use Global static variables to hold the values of sum and max but an alternate implementation using Variadic Templates and Structs if possible?

Example of the dot operator yielding an rvalue

C++ Primer (5th edition) states that "The dot operator yields an lvalue if the object from which the member is fetched is an lvalue; otherwise the result is an rvalue."

I'm trying to see an example where the dot operator yields an rvalue. For this to happen, the member fetched should be from an rvalue. How can an rvalue have a member? Can anyone show me an example of this?

RSA private key included in JWT token

Could someone kindly explain why the private key is included (by default) in the JWT-Token generated by "all" the cpp-based JWT libraries found on github & how to remove it?

lundi 30 mars 2020

Can i change the value of std map without finding it first

This is how currently i am changing the value of std::map

std::map<std::string, int> stdmapMasks;
stdmapMasks.insert(std::make_pair("VALUE", 1));
std::map<char, int>::iterator it = stdmapMasks.find('VALUE'); 
if (it != stdmapMasks.end())
    it->second = 42;

Can i change the value directly without the need to find the map element ?

Met "CUDA_ERROR_MISALIGNED_ADDRESS" error when using NvDecoder decoding video

When I use nvdecoder to decode one video, sometimes met error

"HandlePictureDisplay : cuvidMapVideoFrame(m_hDecoder, pDispInfo->picture_index, &dpSrcFrame, &nSrcPitch, &videoProcessingParameters) returned error 716 at NvCodec/NvDecoder/NvDecoder.cc:450". (CUDA_ERROR_MISALIGNED_ADDRESS)

After this error occur, then every video I want to decode will trigger error

"HandleVideoSequence : cuvidGetDecoderCaps(&decodecaps) returned error 101 at NvCodec/NvDecoder/NvDecoder.cc:155"(CUDA_ERROR_INVALID_DEVICE)

But If I restart the service and decode same video again, the error would not appear again.

Code is cloned from https://github.com/NVIDIA/video-sdk-samples/tree/master/Samples/NvCodec/NvDecoder.

What is this problem and how can I fix it? Thank you in advance.

Undefined behavior [duplicate]

When I try to to call a function returning a bool as follows:

 bool un_retn(double s) {
     s++; 
     cout<<s;
  }

Why is this incorrect? If we consider s=10; then the output will be 11.

How do I connect 64-bit SFML and 64-bit MinGW to my path?

To be more exact: the SFML full name is: SFML-2.5.1-windows-gcc-7.3.0-mingw-64-bit and the MinGw: x86_664-7.33.0-release-posix-seh-rt_v5-rev0

Display names when input text is separated by # in C++?

So, input text of list.txt file is in the form: FirstName LastName#Age My task is to read the list.txt file of four lines of the above form, and output the name with the largest age. I will write my solution below, which works, but only if # is removed and inputs are separated by space. Not sure how to do it with the # being present? I understand i can use getline(), just not sure how? Eg: Alpha Beta#22 Gama Delta#10 and the output should be the name of the oldest person followed by his age. Please orient me towards a an actual correct solution. Thank you in advanceee! :)

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    ifstream ins;   // declare an input file stream object

    ins.open("list.txt");  // open the file
    if (ins.fail()) {     // check if there was an error
        cout << "Error opening file";
        return -1;
    }

    string maxName;   // 
    int maxAge = 0; // 



    for (int i = 0; i < 4; i++) {   // read four lines from the file
        string firstName, lastName;
        int age;
        ins >> age;  // read three variables from the stream line

        if (nr > maxAge) {   // update the current maximum if greater
            maxAge = age;
            maxName = firstName + " " + lastName;
        }
    }

    ins.close();   // close the file

    cout << " The oldest person is: " << maxName
        << " : " << maxAge << endl;

    return 0;
}

CMake + CUDA “invalid device function” even with correct SM version

I have been trying to write a very simple cuda library. I am encountering the error "Invalid Device Function". I have verified that the correct architecture is set as the build flag. And, that the cuda install is good by running deviceQuery and running various other samples.

I cannot share the full source. But I can try to provide a minimal example.

I have a file in which I have the kernel

__global__
void foo( float *ptr_a, uint8_t *ptr_b )
{
 //do stuff
}

And a wrapper function that

void IteratorTestCuda::fooWrapper( uint8_t &aptr )
{
   gpuErrorCheck( cudaMemcpy( ptr_device, ptr_host, sizeof( uint8_t ), cudaMemcpyHostToDevice  ) );

   gpuErrorCheck( cudaGetLastError() );

   //b is a member
   foo << < 1, 1 >> > ( a, b );

   gpuErrorCheck( cudaGetLastError() );

   //do other stuff
}

I am erroring out at the cudaGetLastError call and the error is Invalid Device Function. I have been debugging this for a while and it is because the the requested device function does not exist or is not compiled for the proper device architecture. However, as stated earlier I am providing the correct build flag.

In my cmakelists, I have:

cmake_minimum_required(VERSION 3.5)
project(foo CXX C CUDA )

find_package(CUDA 10.0 REQUIRED)

include_directories(
 include/${PROJECT_NAME}
 ${catkin_INCLUDE_DIRS}
 ${CUDA_INCLUDE_DIRS}
)


if (CUDA_FOUND)
  #Get CUDA compute capability

    set(OUTPUTFILE ${CMAKE_CURRENT_SOURCE_DIR}/src/cuda_info)
    execute_process(COMMAND bash -c <SomeFilePath> OUTPUT_VARIABLE FILEHINT)
    set(CUDAFILE "${FILEHINT}/src/computeCapability.cu"  )
    execute_process(COMMAND bash -c "nvcc -lcuda ${CUDAFILE} -o ${OUTPUTFILE}")
    execute_process(COMMAND bash -c "${OUTPUTFILE}" OUTPUT_VARIABLE ARCH)

    SET(CUDA_NVCC_FLAGS "${ARCH} --relocatable-device-code=true -ldl -lrt -lcufft -lcurand" CACHE STRING "nvcc flags" FORCE)
    SET(CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS} "-std=c++11 -O3")
    SET(CUDA_VERBOSE_BUILD ON CACHE BOOL "nvcc verbose" FORCE)
    SET(LIB_TYPE STATIC)

else()
    message(FATAL_ERROR "CUDA NOT FOUND!")
endif()

SET(LIB_TYPE_TEST SHARED)

CUDA_ADD_LIBRARY( fooCuda ${LIB_TYPE_TEST} srcFoo.cu headerFoo.cuh )

add_dependencies( fooCuda $project_depends} )

CUDA_ADD_LIBRARY( barCuda ${LIB_TYPE_TEST} srcBar.cu headerBar.cuh )

add_dependencies( barCuda $project_depends} )

#src.cpp is another class which calls that function
add_executable( fooCpp src.cpp srcFoo.cu srcBar.cu )

add_dependencies( fooCpp fooCuda barCuda )

target_link_libraries(fooCpp
                   fooCuda
                   barCuda
)

The other alternative would be that it isnt defined under global namespace. But, it is.

I have spent a few hours on this and am about to give up. Any ideas?

-Arunabh

How to improve the syntax

The code I wrote appears to have a couple of syntax mistakes, yet code blocks doesnt show them. Instead of running the program it opens the ios_base.h and shows a few errors there.

C:\Program Files (x86)\CodeBlocks\MinGW\lib\gcc\mingw32\4.9.2\include\c++\bits\ios_base.h|789|error: 'std::ios_base& std::ios_base::operator=(const std::ios_base&)' is private| C:\Program Files (x86)\CodeBlocks\MinGW\lib\gcc\mingw32\4.9.2\include\c++\bits\basic_ios.h|66|error: within this context| C:\Program Files (x86)\CodeBlocks\MinGW\lib\gcc\mingw32\4.9.2\include\c++\streambuf|810|error: 'std::basic_streambuf<_CharT, _Traits>& std::basic_streambuf<_CharT, _Traits>::operator=(const std::basic_streambuf<_CharT, _Traits>&) [with _CharT = char; _Traits = std::char_traits]' is private| C:\Program Files (x86)\CodeBlocks\MinGW\lib\gcc\mingw32\4.9.2\include\c++\fstream|72|error: within this context|

#include <iostream>
#include <stdlib.h>
#include <fstream>
using namespace std;
struct artikl()
{
    int sif;
    int kolic;
    char naz[20];
    float cena;
};
void unos()
{
    fstream myfile("file.bin", ios::out | ios::binary);
    artikl art_val;
    cout << "Unesite sifru: ";
    cin>>art_val.sif;
    cout << "Unesite kolicinu: ";
    cin>>art_val.kolic;
    cout << "Unesite naziv:  ";
    cin>>art_val.naz;
    cout << "Unesite cijenu:  ";
    cin>>art_val.cena;
    myfile.write((char *) &art_val, sizeof(artikl));

    myfile.close();
}
void ispis()
{
    fstream myfile("file.bin", ios::out | ios::binary);
    artikl art_val;
    myfile.read((char *) &art_val, sizeof(artikl));
    cout << "Naziv:  " << art_val.naz << "\n" << "Sifra: " << art_val.sif << "\n" << "Cijena: " << art_val.cena << "\n" << "Kolicina: "<< art_val.kolic << "\n";
}
int main()
{


    cout << "Izbornik: \n" << endl;

    while (true)
    {
        cout<< "1. Unos podataka: \n";
        cout<< "2. Ispis: \n";
        cout<< "9. Izlaz iz programa \n";
        int a;
        cin>>a;
        if (a == 1)
        {
            cout<<"Unesi podatke koje treba upisati u datoteku.\n";
            unos();
        }
        else if (a == 2)
        {
            cout<<"Podaci iz datoteke su: \n";
            ispis();
        }
        else if (a == 9)
        {
            exit(1);
        }
        else
            cout<<"Niste unijeli 1, 2 ili 9.";
    }

    return 0;
}

Minimizing the maximum cost of all adjacent swaps to sort an array

given an array of size N. we're required to sort the array with adjacent swaps only, every swap has a cost |a-b| where a,b are the two adjacent integers. Task is to minimize the maximum costs of all the operations required to sort an array. (Is the task to store the maximum cost of any adjacent swap so far?)

i implemented merge sort but it accounts for any two integers being swapped and bubble sort just causes execution timeout.

#include <iostream>
#include <stdlib.h>
using namespace std;
//nLog(n) time O(n) space
int merging(int arr[],int l,int mid,int h){
    int k = 0, i = l, j = mid+1;
    int temp[h - l + 1];
    int c = 0;
    while(i <= mid && j <= h){
        if(arr[i]<=arr[j]) //no swap required for higher val
        {
            temp[k++] = arr[i++];
        }
        else{
            //swap took place
            c = max(c,arr[i] - arr[j]);
            temp[k++] = arr[j++];
        }
    }

    while(i <= mid){
        temp[k++] = arr[i++];
    }
    while(j <= h){
        temp[k++] = arr[j++];
    }

    //update the initial array with temp array 0th indexing
    for(int i = l; i < h; i++){
        arr[i] = temp[i-l];
    }
    return c;
}

int mergeSort(int arr[],int l,int h){
    int c = 0;
    if(l<h){
        int mid = l + (h-l)/2;
        c = max(mergeSort(arr,l,mid),c);
        c = max(mergeSort(arr,mid+1,h),c);

        c = max(merging(arr,l,mid,h),c);
    }
    return c;
}

int MinSwapCountUtil(int arr[],int n){
    return mergeSort(arr,0,n-1);
}

int main(void){

    int arr [] = {4,2,5,1,3};
    int n = sizeof(arr)/sizeof(arr[0]);

    cout<<MinSwapCountUtil(arr,n);
    return 0;
}

How to use ASIO along with QT4?

I have written a C++ 11 code using asio to send/receive the packets from network. To work with asio, asio::io_service::run() need to be called and the main thread will be waiting in this function. Now, in one of the applications, I need to develop a Gui for which I need to use Qt 4.8. But for a Qt Gui application, the main thread need to wait in QApplication::exec(). Though Qt has its own libraries to send/receive data from Network, I would like to use the code with asio. How can I use asio along with Qt?

What does cin >> x evaluate to, on error?

Consider this snippet:

int a;
while (cin >> a){/* do something */}

On running this code, suppose I enter a string. The loop is exited. But then, since the expression inside while ends in error, and it doesn't evaluate to a bool type (is this incorrect thinking?), how does the compiler know to exit the loop?

std:: add_pointer, what the try_add_pointer for in the possible implementation?

In cppreference add_pointer, it is said we may implement it as:

namespace detail {

template <class T>
struct type_identity { using type = T; }; // or use std::type_identity (since C++20)

template <class T>
auto try_add_pointer(int) -> type_identity<typename std::remove_reference<T>::type*>;
template <class T>
auto try_add_pointer(...) -> type_identity<T>;

} // namespace detail

template <class T>
struct add_pointer : decltype(detail::try_add_pointer<T>(0)) {};

My question is what is the try_add_pointer for? I know it is SFINAE. But why the implementation need it here?

How i solve the problem "Huaauhahhuahau"?

I have tried to solve this problem (using c++) but my answers are not the same those in the tests. Help, please!

Question:

In chats, it is very common among young people and teenagers to use sequences of letters, which often seem random, to reproduce. Some common examples are:

huaauhahhuahau

hehehehe

ahahahaha

jaisjjkasjksjjskjakijs

huehuehue

Cláudia is a young programmer who was intrigued by the sound of “digital laughs”. Some of them she can't even hear! But she realized that some of them seem to convey the feeling of laughter better than others. The first thing she realized is that consonants do not interfere with how much digital laughter influences the transmission of feeling. The second thing she realizes is that the funniest digital letters are those in which the vowel sequences are the same when natural order (left to right) or reverse order (from right to left) orders ignore as consonants. For example, "hahaha" and "huaauhahhuahau" are among the funniest, while "riajkjdhhihhjak" and "huehuehue" are not among the funniest. Cláudia is very busy with a statistical analysis of digital laughs and asked for her help to write a program that determines, for a digital laugh, if she is one of the funniest ones or not.

Input:

The entry consists of a line, contains a sequence of a maximum of 50 characters, formed only by lowercase letters without accents. As vowels are like letters 'a', 'and', 'i', 'o', 'u'. The string contains at least one vowel.

Output:

Your program should produce a line that contains a character, "S", if it appears, either the funniest or "N" otherwise.

Tests

hahaha S

riajkjdhhihhjak N

huaauhahhuahau S

a S

My code

#include <iostream>
using namespace std;

int main(){

  string laugh, vowel;
  int j=0, count = 0;

  cin >> laugh;

  for(int i = 0; i < laugh.size() ; i++ ){
    if(laugh[i]=='a'){
      vowel[j]='a';
      j++;
    }
    if(laugh[i]=='e'){
      vowel[j]='e';
      j++;
    }
    if(laugh[i]=='i'){
      vowel[j]='i';
      j++;
    }
    if(laugh[i]=='o'){
      vowel[j]='o';
      j++;
    }
    if(laugh[i]=='u'){
      vowel[j]='u';
      j++;
    }
  }

  for(int i = 0, j = (vowel.size()-1); i < vowel.size(); i++, j--){
    if(vowel[i] != vowel[j]){
      count++;
    }
  }

  if(count==0){
    cout << "S";
  }
  if(count!=0){
    cout << "N";
  }


  return 0;
}

Pass argument to function as r-value reference vs const l-value reference

Let's consider the following functions:

void processString1(const string & str) { /** **/}
void processString2(string && str) { /** **/}

processString1("Hello");
processString2("Hello");

As I assume, processString1 will invoke copy constructor and processString2 a move constructor of string. What is more efficient?

std::add_const, why the implementation works for reference?

In cppreference add_const it is said we may implement it as:

template< class T> struct add_const { typedef const T type; };

When I try a reference type, like std::add_const<int&>, it is int&.

My question is why it can work without a specific version for reference, since int& const is illegal?

Can you help me get through the errors in the below problem?I'm stuck

Below is the problem question.
https://leetcode.com/problems/four-divisors/

Some test cases failed to pass:
Input: [21,21]
Output : 32
Expected Output: 64


Please tell me where I'm going wrong.
Also it would be helpful if you suggest me more optimised way.


My solution:

class Solution {
public:
    int sumFourDivisors(vector<int>& nums) {
        vector<int> ans;
        int x=0;

        for(int i=0;i<nums.size();i++){
            int j=1;
            while(j!=nums[i]+1){
                if(nums[i]%j==0){
                    ans.push_back(j);

                }
                j++;
            }

                if(ans.size()==4){
                     x=accumulate(ans.begin(),ans.end(),x);


                }
               else
                   ans.clear();

         }
        return x;
    }
};

std::bind with a movable paramter

I am having trouble with std::bind and using a moveable type as a parameter. Is read this and this, but in those cases I actually see the issue since there the OP want's to have a rvalue reference inside the bind. What I want to is have a lvalue, but just to move-construct it when calling std::bind. Here is a minimal sample:

#include <functional>

struct Foo
{
    using Callback = std::function<void(int)>;

    void Do(const Callback &callback)
    {
        callback(5);
    }
};

class Param
{
private:
    Param() {};

public:
    Param(Param&&)
    {
    }

    // commenting out copy ctor triggers the last two invocations in Bar() to fail
#if 1   
    Param(const Param&)
    {
    }
#endif

    Param& operator=(Param&&)
    {
        return *this;
    }

    static Param Create()
    {
        return Param();
    }

    int value_ = 10;
};

struct Bar
{
    Bar()
    {
        Foo f;
        f.Do(std::bind(&Bar::Callback1, this, std::placeholders::_1));
        Param p(Param::Create());
        f.Do(std::bind(&Bar::Callback2, this, std::move(p), std::placeholders::_1)); // does not work w/o copy ctor
        f.Do(std::bind<decltype(&Bar::Callback2), Bar*, Param>(&Bar::Callback2, this, std::move(p), std::placeholders::_1)); // does not work w/o copy ctor
    }

    void Callback1(int a)
    {
        printf("%d\n", a);
    }

    void Callback2(const Param &p, int a)
    {
        printf("%d %d\n", a, p.value_);
    }
};

int main()
{
    Bar b;
}

So I want Param to be move constructible - as shown in the comments adding a copy ctor solves everything (and if everything else fails I will just go that way). The only thing that from my point of view could prohibit this is if the result of std::bind must be copy constructible, but cppreference states:

The return type of std::bind is CopyConstructible if all of its member objects (specified above) are CopyConstructible, and is MoveConstructible otherwise.

I thought that if the type how the variable is stored in the bind is deduced from the call then std::move could cause an attempt to store a rvalue reference, thus the second call where I explicitly state the template parameters (and would expect the bind itself to have a member of type Param which is move constructible and move assignable).

What am I missing here?

How to pass the results of a function to another function in C++

Im currently making a programming that reads a text file, performs calculations, and then returns the results to a new text file. So far the program return the basic details of the text file, however, Im struggling in parsing the results of two functions that perform calculations, to a writetoFile function(that, as the name sugguests, writes all the output to a new text file).

This is the 2 calcualation fuctions, as well as the writetoFile function

//function 1
double robotComplexity(std::vector<std::string>& lines) { //takes in the out.txt file

std::string output = lines[0]; //so far only reads the first line of the output file. 
std::string input = output.substr(18,1);

double complexity = 20 * atoi(input.c_str());


   if(complexity > 100) {
      complexity = 100;
   }

cout << "The Robot Complexity is: " << complexity << endl;
return complexity;
}

//function 2
double robotVariability(std::vector<std::string>& lines) {

std::string output = lines[0]; //so far only reads the first line of the output file. 
std::string input = output.substr(15,2);

double variability;

variability = 5 + atoi(input.c_str());

cout << "The Robot Variability is: " << variability << endl;
return variability;

}

//function to write to file. 
void writeFile(std::string const& outputFile,
               std::vector<std::string> const& lines, double unitComplexity, double unitVariability)
{
   std::ofstream file(outputFile);
   for(std::string const& line: lines)
   {
      file << line << std::endl;
   }

}

I tried using an enchaned for loop of type double but it doesnt accept it, recieving the error, "this range-based 'for' statement requires a suitable "begin" function and none was found"

To reiterate, im trying to add the results of robotComplexity function and the robotValdity function to the output file shown in the writefile function. If any further code is required, please feel free to ask. Thankyou.

dimanche 29 mars 2020

Is there a way to populate C++ initializer_list with a for loop (or any other loop)?

I need to create an interactive session in C++ where user can test a class I created. That includes creating objects of that class with its different constructors. One of them is a collection constructor using initializer_list.

In my code I can run:

MyClass example = {1, 2, 3, 4};

Now I need to find the method to use it during interactive session. Somehow I need to fill the {} with the input provided by the user. User can pass up to 100 argments in that list, so I probably need some kind of a loop solution to my problem. Something working like (Sorry for C++/Python pseudocode mixture):

MyClass example = {a for a in user_input};

Do you know anything I can use to solve this?

Assigning pointers in vector of lists

What am I doing wrong here? Error says member reference type is a pointer here. I am trying to allocate the front element's address to iterator 'it' for each element of vector lists.

class Solution {
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {

     ListNode *it[10];   
        for(int i=0;i<lists.size();i++)
        {
            it[i]=lists[i].begin();
        }

    }
};

C++, no matching function for call to error

Junior CS student here, struggling quite a bit.

This is the error I get:

main.cpp:45:18: error: no matching function for call to ‘yerlesimBirimi::isimAta()’
      obj1.isimAta();
                   ^

Below is my code. Could you help me see what I'm doing wrong?

#include <stdio.h>
#include <iostream>
using namespace std;

class yerlesimBirimi {
public:
    string isim;
    int nufus;
    int dogumSayisi, olumSayisi;

    void isimAta (string _isim){
        cin >> _isim;
        isim = _isim;
    }

    void nufusAta (int _nufus){
        cin >> _nufus;
        nufus = _nufus;
    }

    void dogumAta (int _dogumSayisi){
        cin >> _dogumSayisi;
        dogumSayisi = _dogumSayisi;
    }

    void olumAta (int _olumSayisi){
        cin >> _olumSayisi;
        olumSayisi = _olumSayisi;
    }

    double dogumOrani();
    double olumOrani ();
};

double yerlesimBirimi::dogumOrani(){
    return dogumSayisi/nufus;
}

double yerlesimBirimi::olumOrani(){
    return olumSayisi/nufus;
}

int main (){
    yerlesimBirimi obj1;
    cout << "Yerlesim biriminin ismini giriniz:";
    obj1.isimAta();
    cout << "Nufusunu giriniz:";
    obj1.nufusAta();
    cout << "Dogum sayisini giriniz:";
    obj1.dogumAta();
    cout << "Olum sayisini giriniz:";
    obj1.olumAta();
    cout << obj1.isim << "--- Dogum Orani:" << obj1.dogumOrani << endl;
    cout << obj1.isim << "--- Olum Orani" << obj1.olumOrani << endl;
    yerlesimBirimi obj2;
    cout << "Yerlesim biriminin ismini giriniz:";
    cin >> obj2.isim;
    cout << "Nufusunu giriniz:";
    cin >> obj2.nufus;
    cout << "Dogum sayisini giriniz:";
    cin >> obj2.dogumSayisi;
    cout << "Olum sayisini giriniz:";
    cin >> obj2.olumSayisi;
    cout << "------------- Dogum Orani:" << obj2.dogumOrani<<endl;
    cout << "------------- Olum Orani:" << obj2.olumOrani<<endl;
}

Can someone explain what does the below code snippet do?

Cinema Seat Allocation

where n=no. of rows.

Please explain the for-each loop given below.Its syntax and how it is adding elements to the map.

int maxNumberOfFamilies(int n, vector<vector<int>>& reservedSeats) {
     map<int,vector<int>>mp;
     for(vector<int>a: reservedSeats){
         mp[a[0]].push_back(a[1]-1);

     }

Is there any library which contains differentiation and integration function ? If yes then which one is that library and what is the name of function? [closed]

I want to differentiate and integrate in my program for calculating E.M.F from loop. So, anyone know which function will do this work efficiently and save my time on writing separate code for integration and differentiation .

How to delete a pointer belonging to an object stored in a vector?

I have a Containing class, a Contained class, and a Data class. That Containing class holds a vector of Contained objects. The Contained class holds a pointer to a data object, allocated on the heap in Contained's constructor. However, I can't deallocate it in the destructor, since the vector will create copies of Contained and then destroy them, thus destroying the data pointer even in the copy we're using.

TL;DR Here's some code to explain:

class Data {
    public:
        Data();
};

class Contained {
    private:
        Data* data;
    public:
        Contained();
        // what should I add ? a copy constructor ? an assignement operator ? and how
};

class Container {
    private:
        vector<Contained> rooms;
    public:
        //some member functions
};
Contained::Contained() {
    data = new Data();
}

Where do I delete data ?

C++ template template argument types deduction

I have code that finds and prints out matches of a pattern as going over the container of strings. Printing is performed in the function foo that is templated

The code

#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>
#include <string>
#include <tuple>
#include <utility>

template<typename Iterator, template<typename> class Container>
void foo(Iterator first, Container<std::pair<Iterator, Iterator>> const &findings)
{
    for (auto const &finding : findings)
    {
        std::cout << "pos = " << std::distance(first, finding.first) << " ";
        std::copy(finding.first, finding.second, std::ostream_iterator<char>(std::cout));
        std::cout << '\n';
    }
}

int main()
{
    std::vector<std::string> strs = { "hello, world", "world my world", "world, it is me" };
    std::string const pattern = "world";
    for (auto const &str : strs)
    {
        std::vector<std::pair<std::string::const_iterator, std::string::const_iterator>> findings;
        for (std::string::const_iterator match_start = str.cbegin(), match_end;
             match_start != str.cend();
             match_start = match_end)
        {
            match_start = std::search(match_start, str.cend(), pattern.cbegin(), pattern.cend());
            if (match_start != match_end)
                findings.push_back({match_start, match_start + pattern.size()});
        }
        foo(str.cbegin(), findings);
    }

    return 0;
}

When compiling I've got an error that types deduction has failed due to inconsistency of iterators being provided, their types turn out to be diverse.

GCC compilation error:

prog.cpp:35:9: error: no matching function for call to 'foo'
        foo(str.cbegin(), findings);
        ^~~
prog.cpp:10:6: note: candidate template ignored: substitution failure [with Iterator = __gnu_cxx::__normal_iterator<const char *, std::__cxx11::basic_string<char> >]: template template argument has different template parameters than its corresponding template template parameter
void foo(Iterator first, Container<std::pair<Iterator, Iterator>> const &findings)
     ^
1 error generated.

Clang's output:

main.cpp:34:9: error: no matching function for call to 'foo'
        foo(str.cbegin(), findings);
        ^~~
main.cpp:9:6: note: candidate template ignored: substitution failure [with Iterator = std::__1::__wrap_iter<const char *>]: template template argument has different template parameters than its corresponding template template parameter
void foo(Iterator first, Container<std::pair<Iterator, Iterator>> const &findings)

What am I not catching? Is my utilization of template template types deduction wrong and appears an abuse from the standard's point of view? Neither g++-9.2 with listdc++11 nor clang++ with libc++ are able to compile this

Thank you

Can a c++ program have alternate output results every time you execute with the same input?

I have framed an error into a question.

I keep getting 2 output results alternating randomly(sometimes its '1' and sometimes its '0',even though the input is same .

can someone explain me why is this happening? compiler issue?

i am pretty sure a set of commands with same input cant change it's output every time you run it.

#include <iostream>
using namespace std;
int main() 
{
  int n;
  cin>>n;




  for(int i=0;i<n;i++)
  {



    int N ,M;

    cin>>M>>N;


    int arr[N];
    int turn=-1;
    char win='D';
    for(int i=0;i<N;i++)
    {
      if(M>0)
      { 
        if(turn==-1)
        {
          M=M-arr[i];
          win='D';
        }
        else if(turn==1)
        {
          M=M-arr[i];
          win='K';
        }
      }
      else
        break;

      turn=turn*-1;
    }

    if(win=='K')
    {
      cout<<"Kate"<<endl;
    }
    else if(win=='D')
    {
      cout<<"Little Deepu"<<endl;
    }
  }

    return 0;
}

CodeWars Sum By Factors C++ No idea how to make it work

I try to solve Sum by Factors on CodeWars and I have no idea how to get it working with C++. My code prints just the highest prime factor for every number. Good solution is: I = {12, 15}; // result = "(2 12)(3 27)(5 15)" and mine is Expected: equal to (2 12)(3 27)(5 15) Actual: (3 12)(3 27)(5 15). Can anybody take a look at this code and help me find correct solution?

I don't want to rewrite for instance Python code to Cpp, just trying to improve myself.

#include <string>
#include <vector>
#include <utility>
#include <cmath>
#include <numeric>

class SumOfDivided
{
public:
    static std::string sumOfDivided(std::vector<int> &lst)
    {
      std::vector<std::pair<int, int>> v;
      std::string rtn = "";

      int sum = std::accumulate(lst.begin(), lst.end(), 0);
      v.emplace_back(std::make_pair(primeFactors(std::ref(sum)), std::ref(sum)));

      for(auto& elem : lst)
        v.emplace_back(std::make_pair(primeFactors(std::ref(elem)), std::ref(elem)));

      sort(v.begin(), v.end());

      for(auto& elem : v)
        rtn += "(" + std::to_string(elem.first) + " " + std::to_string(elem.second) + ")";

      return rtn;
    }

    static int primeFactors(int& n)
    { 
      int helper = 2;
      int number = abs(n);

      while(number > helper)
        if(number % helper == 0)
        {
          number /= helper;
          helper = 2;
        }
        else
          helper++;

      return helper;
    }
};

How do I count how many times a letter appears in a string? C programming

I am trying to write a program to tell me how many 'e' letters are in the phrase "Yesterday, all my troubles seemed so far away". I am trying to do this using strcmp function and I want to compare each letter in the phrase to the letter 'e' and then make it so that the count increments.

int main(void)
{
    int i, x, count = 0;
    char words[] ="Yesterday, all my troubles seemed so far away", letter;
    char str1 = "e";
    for (i = 0; i < 45; i++){
        letter = words[i];
        x = strcmp(letter, str1);
        if (x == 0)
        {
            count++;
        }
    }
    printf("The number of times %c appears is %d.\n", str1, count);
}

What is the difference between auto and int in c++?Give some examples

auto vs int

Please tell me the difference between the two in detail.

Forwarding to std::async

This is my (simplified) code where I'm trying to call async forwarding arguments:

template<typename Ret, typename ... Args>
class CallbackAsyncTask {
public:
    CallbackAsyncTask() {
    }
    virtual ~CallbackAsyncTask() = default;

    void execute( Args&& ... args ) {
        execute(&CallbackAsyncTask<Ret, Args...>::onBackground, this, std::forward<Args>(args)...);
    }
protected:
    virtual Ret onBackground( Args& ... args ) = 0;
    template<typename Fn, typename ... Argss>
    void execute( Fn&& fn, Argss&& ... args ) noexcept(false) {
        std::async(std::launch::async, std::forward<Fn>(fn), std::forward<Argss>(args)...);
    }
};

class Child: public CallbackAsyncTask<int, int> {
public:
    virtual int onBackground( int& i ) {
        return i;
    }
};

int main() {
    Child c;
    c.execute(15);
    return 0;
}

I get this error:

../main.cpp: In instantiation of ‘void CallbackAsyncTask<Ret, Args>::execute(Fn&&, Argss&& ...) [with Fn = int (CallbackAsyncTask<int, int>::*)(int&); Argss = {CallbackAsyncTask<int, int>* const, int}; Ret = int; Args = {int}]’:
../main.cpp:27:98:   required from ‘void CallbackAsyncTask<Ret, Args>::execute(Args&& ...) [with Ret = int; Args = {int}]’
../main.cpp:46:17:   required from here
../main.cpp:33:90: error: no matching function for call to ‘async(std::launch, int (CallbackAsyncTask<int, int>::*)(int&), CallbackAsyncTask<int, int>* const, int)’
         std::async(std::launch::async, std::forward<Fn>(fn), std::forward<Argss>(args)...);
                                                                                          ^
../main.cpp:33:90: note: candidates are:
In file included from ../main.cpp:13:0:
/usr/include/c++/4.8.2/future:1532:5: note: template<class _Fn, class ... _Args> std::future<typename std::result_of<_Functor(_ArgTypes ...)>::type> std::async(std::launch, _Fn&&, _Args&& ...)
     async(launch __policy, _Fn&& __fn, _Args&&... __args)
     ^
/usr/include/c++/4.8.2/future:1532:5: note:   template argument deduction/substitution failed:
/usr/include/c++/4.8.2/future: In substitution of ‘template<class _Fn, class ... _Args> std::future<typename std::result_of<_Functor(_ArgTypes ...)>::type> std::async(std::launch, _Fn&&, _Args&& ...) [with _Fn = int (CallbackAsyncTask<int, int>::*)(int&); _Args = {CallbackAsyncTask<int, int>* const, int}]’:
../main.cpp:33:90:   required from ‘void CallbackAsyncTask<Ret, Args>::execute(Fn&&, Argss&& ...) [with Fn = int (CallbackAsyncTask<int, int>::*)(int&); Argss = {CallbackAsyncTask<int, int>* const, int}; Ret = int; Args = {int}]’
../main.cpp:27:98:   required from ‘void CallbackAsyncTask<Ret, Args>::execute(Args&& ...) [with Ret = int; Args = {int}]’
../main.cpp:46:17:   required from here
/usr/include/c++/4.8.2/future:1532:5: error: no type named ‘type’ in ‘class std::result_of<int (CallbackAsyncTask<int, int>::*(CallbackAsyncTask<int, int>*, int))(int&)>’
../main.cpp: In instantiation of ‘void CallbackAsyncTask<Ret, Args>::execute(Fn&&, Argss&& ...) [with Fn = int (CallbackAsyncTask<int, int>::*)(int&); Argss = {CallbackAsyncTask<int, int>* const, int}; Ret = int; Args = {int}]’:
../main.cpp:27:98:   required from ‘void CallbackAsyncTask<Ret, Args>::execute(Args&& ...) [with Ret = int; Args = {int}]’
../main.cpp:46:17:   required from here
/usr/include/c++/4.8.2/future:1552:5: note: template<class _Fn, class ... _Args> std::future<typename std::result_of<_Functor(_ArgTypes ...)>::type> std::async(_Fn&&, _Args&& ...)
     async(_Fn&& __fn, _Args&&... __args)
     ^
/usr/include/c++/4.8.2/future:1552:5: note:   template argument deduction/substitution failed:
/usr/include/c++/4.8.2/future: In substitution of ‘template<class _Fn, class ... _Args> std::future<typename std::result_of<_Functor(_ArgTypes ...)>::type> std::async(_Fn&&, _Args&& ...) [with _Fn = std::launch; _Args = {int (CallbackAsyncTask<int, int>::*)(int&), CallbackAsyncTask<int, int>* const, int}]’:
../main.cpp:33:90:   required from ‘void CallbackAsyncTask<Ret, Args>::execute(Fn&&, Argss&& ...) [with Fn = int (CallbackAsyncTask<int, int>::*)(int&); Argss = {CallbackAsyncTask<int, int>* const, int}; Ret = int; Args = {int}]’
../main.cpp:27:98:   required from ‘void CallbackAsyncTask<Ret, Args>::execute(Args&& ...) [with Ret = int; Args = {int}]’
../main.cpp:46:17:   required from here
/usr/include/c++/4.8.2/future:1552:5: error: no type named ‘type’ in ‘class std::result_of<std::launch(int (CallbackAsyncTask<int, int>::*)(int&), CallbackAsyncTask<int, int>*, int)>’

What I am missing? Compiler Gcc 4.8.3

samedi 28 mars 2020

Why `void` is required while declaring a class template which is to be specialized using `enable_if`

I'm learning C++ template meta-programming and stumbled upon a simple SFINAE related (I believe so) issue. In particular, I'm writing a template class which will give us the type with largest size. I'm aliasing the type to be the right type depending upon their size by comparing types with sizeof operator. I'm selecting correct class specialization using enable_if. What I don't understand is why void needs to be provided as default value for class Enable while declaring a class template which is to be specialized using enable_if.

Following code works just fine

// test.cpp
#include <type_traits>

// void works just fine but if changed to anything else say int, compilation fails!
template < typename L, typename R, class Enable = void > struct MaxTypeT;

template < typename L, typename R >
struct MaxTypeT<L, R, typename std::enable_if< (sizeof(L) >= sizeof(R)) >::type> {
    using type = L;
};

template < typename L, typename R >
struct MaxTypeT<L, R, typename std::enable_if< (sizeof(L) < sizeof(R)) >::type> {
    using type = R;
};

int main(){
    static_assert(std::is_same< MaxTypeT<int, double>::type, double >::value, "MaxTypeT not working");
    return 0;
}

but when I change class Enable = void to any other type say class Enable = int, then I get following error. Why void is necessary here?

test.cpp: In function ‘int main()’:
test.cpp:17:56: error: incomplete type ‘MaxTypeT<int, double>’ used in nested name specifier
     static_assert(std::is_same< MaxTypeT<int, double>::type, double >::value, "MaxTypeT not working");
                                                        ^~~~
test.cpp:17:56: error: incomplete type ‘MaxTypeT<int, double>’ used in nested name specifier
test.cpp:17:69: error: template argument 1 is invalid
     static_assert(std::is_same< MaxTypeT<int, double>::type, double >::value, "MaxTypeT not working");

enum overloading operator | constexpr and runtime

I have a predeclared enum:

enum class TheEnum : std::uint32_t;

Followed by operator overloading:

constexpr TheEnum operator|(TheEnum const a, TheEnum const b)
{
    return TheEnum(std::uint32_t(a) | std::uint32_t(b));
}

With the definition:

enum class TheEnum : std::uint32_t
{
    A = 1 << 0,
    B = 1 << 1,
    C = 1 << 2,
    D = 1 << 3,
    Val0 = TheEnum::A | TheEnum::C,
    Val1 = TheEnum::A | TheEnum::D,
    Val2 = TheEnum::B | TheEnum::D
};

I try to have the operator| constexpr and not constexpr in the same time. Currently if I add the (not constexpr):

inline TheEnum operator|(TheEnum const a, TheEnum const b)
{
    return TheEnum(std::uint32_t(a) | std::uint32_t(b));
}

My compiler said it's already defined. The constexpr allow me to do some typetrait operations, but I need the same operators for runtime evaluation.

C++ Program to Find "Patient Zero" [closed]

I need to write a program to find the "patient zero" of a given input, in addition to a few other details. So for this problem, we know the information that...

1) Exactly 1 person started off with the disease.

2) Once a person is infected, they will pass the disease to any person they interact with. However, after K interactions, they will realize they have the disease and santize themselves so that they will not pass the disease in any future interactions.

3) Once a person is infected, they will stay infected (even through the santization). In the problem, we want to find the person who had the disease before the interactions occurred, in addition to the minimal and maximal values of K.

The input composes of an integer N and T. The integer N describes the length of the string following it. The string following it will be comprised of 1s and 0s, where each 1 describes that the person with the respective position is sick, and each 0 describes that the person with the respective position is not sick. For example, in the string (0011), the people labeled 1 and 2 will not be sick, but the people labeled 3 and 4 will be sick. This string describes the status of the people after the interactions. The T interactions will then be labeled with the first number representing the time it took place (a greater time means it took place later), and then the labels of the two people who interacted with each other. One example of an input would be..

4 3 1100 7 1 2 5 2 3 6 2 4

This input shows that persons 1 and 2 are sick after the interactions, but persons 3 and 4 are not. And it shows that at time 7, persons 1 and 2 interacted; at time 5, persons 2 and 3 interacted; at time 6, persons 2 and 4 interacted.

The output should contain the label of the initial patient ("patient zero"), in addition to the minimal and maximal values of K (the amount of interactions people will go before realizing they have the disease and sanitizing themselves). The output for this example input would be...

1 1 Infinity

since the only candidate for the patient zero would be person 1 who would transfer the disease to person 2 due to their interaction at time 7. And K could range from 1 to infinity since we know that there was only one transfer. Note that K could be 0, meaning the initial patient would have no opportunity to transfer the disease to anyone else, and that K could be infinity if we don't have enough information to conclude a definite maximal K. And remember there is always a patient zero.

i have a code that returns max but i need to print the path in file

this code can find max knapsack value in the dataset. I need to post the path though in a .txt file in a format like 0,1,0,1,1,0...... which means 1rst item=0(not included) 2nd item=1(included in solution) ... any suggestions? table checked[n] is there in order to store the path and later one to store in in the file


#include <bits/stdc++.h> 
using namespace std; 

// Structure for Item which store weight and corresponding 
// value of Item 
struct Item 
{ 
    float weight; 
    int value; 
}; 

// Node structure to store information of decision 
// tree 
struct Node 
{ 
    // level --> Level of node in decision tree (or index 
    //           in arr[] 
    // profit --> Profit of nodes on path from root to this 
    //       node (including this node) 
    // bound ---> Upper bound of maximum profit in subtree 
    //       of this node/ 
    int level, profit, bound; 
    float weight; 
}; 

// Comparison function to sort Item according to 
// val/weight ratio 
bool cmp(Item a, Item b) 
{ 
    double r1 = (double)a.value / a.weight; 
    double r2 = (double)b.value / b.weight; 
    return r1 > r2; 
} 

// Returns bound of profit in subtree rooted with u. 
// This function mainly uses Greedy solution to find 
// an upper bound on maximum profit. 
int bound(Node u, int n, int W, Item arr[]) 
{ 
    // if weight overcomes the knapsack capacity, return 
    // 0 as expected bound 
    if (u.weight >= W) 
        return 0; 

    // initialize bound on profit by current profit 
    int profit_bound = u.profit; 

    // start including items from index 1 more to current 
    // item index 
    int j = u.level + 1; 
    int totweight = u.weight; 

    // checking index condition and knapsack capacity 
    // condition 
    while ((j < n) && (totweight + arr[j].weight <= W)) 
    { 
        totweight += arr[j].weight; 
        profit_bound += arr[j].value; 
        j++; 
    } 

    // If k is not n, include last item partially for 
    // upper bound on profit 
    if (j < n) 
        profit_bound += (W - totweight) * arr[j].value / 
                                        arr[j].weight; 

    return profit_bound; 
} 

// Returns maximum profit we can get with capacity W 
int knapsack(int W, int ** tab, int n) 
{ 
    FILE *bbdfs=fopen("pr1.txt","a");



    int checked[n];//array to store chosen values in 0 & 1
    int i;
    for(i=0;i<n;i++){
        checked[i]=0;
    }
    Item arr[n];
    for(i=0;i<n;i++){
        arr[i].value=tab[i][1];
        arr[i].weight=tab[i][0];

    }



    // sorting Item on basis of value per unit 
    // weight. 
/// sort(arr, arr + n, cmp); 

    // make a queue for traversing the node 
    queue<Node> Q; 
    Node u, v; 

    // dummy node at starting 
    u.level = -1; 
    u.profit = u.weight = 0; 
    Q.push(u); 

    // One by one extract an item from decision tree 
    // compute profit of all children of extracted item 
    // and keep saving maxProfit 
    int maxProfit = 0; 
    while (!Q.empty()) 
    { 
        // Dequeue a node 
        u = Q.front(); 
        Q.pop(); 

        // If it is starting node, assign level 0 
        if (u.level == -1) 
            v.level = 0; 

        // If there is nothing on next level 
        if (u.level == n-1) 
            continue; 

        // Else if not last node, then increment level, 
        // and compute profit of children nodes. 
        v.level = u.level + 1; 

        // Taking current level's item add current 
        // level's weight and value to node u's 
        // weight and value 
        v.weight = u.weight + arr[v.level].weight; 
        v.profit = u.profit + arr[v.level].value; 

        // If cumulated weight is less than W and 
        // profit is greater than previous profit, 
        // update maxprofit 
        if (v.weight <= W && v.profit > maxProfit) 
            maxProfit = v.profit; 



        // Get the upper bound on profit to decide 
        // whether to add v to Q or not. 
        v.bound = bound(v, n, W, arr); 

        // If bound value is greater than profit, 
        // then only push into queue for further 
        // consideration 
        if (v.bound > maxProfit) 
            Q.push(v); 

        // Do the same thing, but Without taking 
        // the item in knapsack 
        v.weight = u.weight; 
        v.profit = u.profit; 
        v.bound = bound(v, n, W, arr); 
        if (v.bound > maxProfit) 
            Q.push(v); 
    } 
    for(i=0;i<n;i++){
            fprintf(bbdfs,"%d ,",checked[i]);
        }
        fprintf(bbdfs,"\n");
    return maxProfit; 
} 


Observer pattern, smart pointers and singleton classes

I want to create an Obserer pattern using smart pointers. This is my class:

class Observable {
public:
    void addObserver(std::shared_ptr<Observer> ptr);
private:
    std::list<std::weak_ptr<Observer>> observers;
};

The use of smart pointers provides strong guarantees about memory leak, however I don't understand how to manage list of observers when I don't have a shared_ptr. Example for singleton classes:

class Singleton {
private:
  Singleton();
public:
  static Singleton& getInstance() {
      static Signleton instance;
      return instance;
  }
}

In this case I don't have a shared ptr but the singleton class can be an observer. Does it mean that I need to return a shared_ptr from a singleton class? Is there any design detail to take into account?

How does Memory allocation in C++

String::String(const String& old_str)    
{ 
size = old_str.size; 
s = new char[size+1]; 

Why we use size+1 here to allocate memory. why not size?

Prime no list -Input 1 should be lesser than Input 2. Both the inputs should be positive. i

package monu; import java.util.Scanner;

public class Test {

    public static void main (String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = Integer.parseInt(sc.nextLine());
        int b = Integer.parseInt(sc.nextLine());
        int c=b-a;
        if((a > b) || c<0||a <0|| b <= 0){
            System.out.println("Provide valid input");
        }
        else{
            int i = 0, num = 0;
            String prime = "";

            for(i = a;i <= b;i++){
                int counter = 0;
                num = i;
                while(num >= 1){
                    if(i % num == 0)
                        counter++;
                    num--;
                }
                if(counter == 2)
                    prime = prime + i + " ";
            }

            System.out.println(prime);
        }
    }
}

This is my code there is hidden test should have got check for zero

Is pointer addition with an int variable different from addition with an int literal?

Consider this snippet of code, trying to check if two arrays are equal:

int arr1[5] = {1,2,3,4,5};
int arr2[5] = {1,2,3,4,5};

int *p1 = arr1;
int *p2 = arr2;

if (end(arr1) - p1 == end(arr2) - p2) // Check if sizes are equal
{
    for (size_t i = 0;
         p1 != end(arr1);
         ++i){
             if (*(p1 + i) != *(p2 + i)){ // Check if each ith element is equal
                 cout << "Arrays not equal!" << endl;
                 return 0;
             }
         }
    cout << "Arrays equal!" << endl;
    return 0;
}
else // Not equal if sizes don't match
{
    cout << "Arrays not equal!" << endl;
    return 0;
}

When I run this code, I end up getting "Arrays not equal!". So, I was looking into the if condition, when I noticed that *(p1 + i) for the first i, i.e., i = 0, seems to give a value of 32766, whereas if I write *(p1 + 0), I'm getting the first element of arr1 as expected. Why does this happen?

(C++11) Is there any way to limit scope of template parameters on a specific class?

■ Problem Definition_________________________

!!You can skip here and directly go to■ Question Summary !!

I designed a flexible but memory-efficient class that suits various situations, having only selective traits within it : link

Plus, I gave ID for each trait, which is used when a user wants to request only specific traits of the class.

I wrote my own class satisfying these properties, using multiple inheritances of unnamed enums with variadic template.

See below :

▼ TriTraits.h

struct TriT
{
    struct Centroid
    {
        Point3D centroid;
        struct ID { enum : utin8_t { CENTROID = 1 }; }; // 0000 0001
    };

    struct Area
    {
        double area;
        struct ID { enum : utin8_t { AREA = 2 }; }; // 0000 0010
    };

    struct Perimeter
    {
        double perimeter;
        struct ID { enum : utin8_t { PERIMETER = 4 }; }; // 0000 0100
    };
    ... // More traits...
};

▼ Triangle.h

#include "TriTraits.h"

enum class TRI_TRAIT_ID : uint8_t {}; // strong type
template<class... Traits>
struct TriangleT : Traits...
{
    struct IDs : Traits::ID...
    {
        enum : uint8_t {
            NONE = 0, // 0000 0000
            ALL = 255 // 1111 1111
        };
    };
    void ComputeTrait(TRI_TRAIT_ID _requestedIDs)
    {
        ... // Implementation will be written somehow, using bitwise & operator.
    }
};

For example, if one defines one's own triangle type, MyTri<TriT::Area, TriT::Perimeter> myTri, what compiler sees may look like this :

struct MyTri
{
    double area;
    double perimeter;

    struct IDs // Since enum can't be inherited, it has 3 individual unnamed enums in it
    {
        enum : uint8_t { AREA = 2 };
        enum : uint8_t { PERIMETER = 4 };
        enum : uint8_t {
            NONE = 0,
            ALL = 255
        };
    };
} myTri;

This custom triangle type will compute some of its traits by calling ComputeTraits(...) with bitwise |operator, like this :

myTri.ComputeTraits(MyTri::IDs::AREA | MyTri::IDs::PERIMETER); // Compute area and perimeter of it

The problem rises here : suppose there are Rectangle.h and Pentagon.h, ... NthPolygon.h, in the same manner..

I want each of my custom polygon types to get a strongly-typed parameter for its ComputeTrait(...)(So I used enum class for it), to prevent silly operations taking mixed types of polygon traits, such as

myTri.ComputeTraits(MyTri::IDs::AREA | MyRect::IDs::PERIMETER); // Mixed traits of a triangle and of  a rectangle.

So I want to overload |operator which takes only unnamed enums in each scope of Polygon::IDs::.

I tried writing the overloaded template operator inside the private scope of NthPolygon::IDs::, but this failed since in-class operator overloading always takes the first parameter as itself : link

Making it friend of global scope also failed, since there will be more than 1 overloaded |operators for every N-th Polygon classes.

enum class N_TH_TRAIT_ID : uint8_t {}; // strong type
struct NthPolygon
{
    ...
    struct IDs
    {
        ...
     private:
        template<typename TRAIT_ID1, typename TRAIT_ID2>
        N_TH_TRAIT_ID operator|(TRAIT_ID1 _id1, TRAIT_ID2 _id2) // Error : too many operators for this operator function
        { return static_cast<N_TH_TRAIT_ID>(static_cast<utin8_t>(_id1) | static_cast<utin8_t>(_id2)); }

        template<typename TRAIT_ID1, typename TRAIT_ID2>
        friend N_TH_TRAIT_ID operator|(TRAIT_ID1 _id1, TRAIT_ID2 _id2) // Error : more than 1 operator "|" matches these operands
        { return static_cast<N_TH_TRAIT_ID>(static_cast<utin8_t>(_id1) | static_cast<utin8_t>(_id2)); }
    };
} myTri;

■ Question Summary_________________________

In the situation below, how can one make the template overloaded operator| take only parameters(unnamed enums) from the specific class?

enum class STRONG_TYPE_TRI_TRAIT_ID : uint8_t {};
struct Triangle
{
    struct IDs {
        enum : utin8_t { A = 1 };
        enum : utin8_t { B = 2 };
        enum : utin8_t { C = 3 };
    };
};
template<typename TRI_TRAIT_ID1, typename TRI_TRAIT_ID2>
STRONG_TYPE_TRI_TRAIT_ID operator|(TRI_TRAIT_ID1 _id1, TRI_TRAIT_ID2 _id2)
{ return static_cast<STRONG_TYPE_TRI_TRAIT_ID>(static_cast<uint8_t>(_id1) | static_cast<uint8_t>(_id2)); }
enum class STRONG_TYPE_RECT_TRAIT_ID : uint8_t {};
struct Rectangle
{
    struct IDs {
        enum : utin8_t { A = 1 };
        enum : utin8_t { B = 2 };
        enum : utin8_t { C = 3 };
    };
};
template<typename RECT_TRAIT_ID1, typename RECT_TRAIT_ID2>
STRONG_TYPE_RECT_TRAIT_ID operator|(RECT_TRAIT_ID1 _id1, RECT_TRAIT_ID2 _id2)
{ return static_cast<STRONG_TYPE_RECT_TRAIT_ID >(static_cast<uint8_t>(_id1) | static_cast<uint8_t>(_id2)); }
int main(void)
{
    Triangle::IDs::A | Triangle::IDs::B;  // OK
    Triangle::IDs::A | Rectangle::IDs::B; // Error
    ...
    return 0;
}

Segmentation fault after returning unique_ptr inside of pair from function

I have a factory that creates class instances from strings. KeyValueType is an abstract class, which will be passed to Map/Reduce functions.

class KeyValueType {
public:
    virtual void parse(const std::string &) = 0;

    virtual std::string to_string() const = 0;
};

Factories in code are getting from the shared library (to be able to config map/reduce functions from a remote computer).

std::unique_ptr<KeyValueType> KeyValueTypeFactory::create() override {
    return std::make_unique<KeyValueType<T>>();
};
std::unique_ptr<KeyValueType> KeyValueTypeFactory::create(const std::string &str) override {
    std::unique_ptr<KeyValueType> ptr = this->create();
    ptr->parse(str);
    return ptr;
};

So, I have the next code, where I'm creating two objects key/value and returning them, as a pair of unique_ptr

std::pair<std::unique_ptr<KeyValueType>, std::unique_ptr<KeyValueType>> 
get_key_value_from_json(const std::string &data, std::unique_ptr<KeyValueTypeFactory> &key_factory, std::unique_ptr<KeyValueTypeFactory> &value_factory) {
    boost::property_tree::ptree pt{};
    boost::property_tree::json_parser::read_json(dynamic_cast<std::stringstream &>(std::stringstream{} << data), pt);
    return { std::move(key_factory->create(pt.get("key", ""))),
             std::move(value_factory->create(pt.get("value", ""))) };
}
std::pair<std::unique_ptr<KeyValueType>, std::unique_ptr<KeyValueType>> blocking_get_result() {
        ... // Get json and config
        auto[key, value] = get_key_value_from_json(json, cfg->key_out_factory, cfg->value_res_factory);
        std::cout << "The result of Map/Reduce is " << value->to_string() << std::endl;
        return { std::move(key), std::move(value) };
}
int main() {
    auto[key, value] = blocking_get_result();
    std::cout << (value.get() == nullptr) << std::endl;
    std::cout << "The result of Map/Reduce is " << value->to_string() << std::endl;
    return 0;
}

The actual problem is, that in blocking_get_result() function key and value are valid and virtual function to_string() is working correctly, but after returning pair from function to main unique_ptr is not null, but to_string throws Segmentation Fault. Also, dynamic_cast to a derived class is causing Segfault.

Why is an array limited by size, when I can initialize values to indices out of its bounds? [duplicate]

I'm trying to understand the concept of a fixed size in an array. Consider the following array:

int arr[1] = {0};

Now, if I subscript arr by any unsigned value greater than 0, I will get undefined values.

But if I do:

arr[1] = 42;

Now index 1 of arr holds 42. I can keep doing this assignment to any index of arr, making arr hold more than one int, which it was originally defined as.

How is arr having a fixed size if I can keep assigning multiple ints to its indices?

How member function with variadic parameters as template parameter

Is it possible to write template function in C++14 like below

Here is the sample https://godbolt.org/z/9gRk-t

// pseudo code

#include <type_traits>

template <typename T, typename R, typename... Args>
decltype(auto) Call(T& obj, R(T::*mf)(Args...), Args&&... args) 
{
  return (obj.*mf)(std::forward<Args>(args)...);
}

So, for a test class

struct Test 
{
  int Func(){return 1;};
  bool Func(bool){return true;};  // overload

  void FuncInt(int){};
};

The template coudl work for the use case below (but it failed)

int main()
{
  Test test;

  // for overload case
  auto a = Call<int()>(test, &Test::Func);
  auto b = Call<bool(bool)>(test, &Test::Func, true);

  // for non-overload case
  Call(test, &Test::FuncInt, 1);

  return 0;
}

Herer the erro info.

#1 with x64 msvc v19.24
example.cpp
<source>(23): error C2672: 'Call': no matching overloaded function found
<source>(23): error C2770: invalid explicit template argument(s) for 'decltype(auto) Call(T &,R (__cdecl T::* )(Args...),Args &&...)'
<source>(5): note: see declaration of 'Call'
<source>(24): error C2672: 'Call': no matching overloaded function found
<source>(24): error C2770: invalid explicit template argument(s) for 'decltype(auto) Call(T &,R (__cdecl T::* )(Args...),Args &&...)'
<source>(5): note: see declaration of 'Call'
Compiler returned: 2

vendredi 27 mars 2020

Copying from one dimensional vector vector

I have multiple 3 one dimensional vectors (vector<int> starts, vector<int> ends, vector<int> points). Each having specific number of elements.

I want to create a two dimensional vector vector<pair<int,int>>matrix in such a sequence :

  1. from beginning of matrix to size of start first element of matrix is elements of vector<int> starts and second element is "-1"
  2. Append now the elements of vector<int> ends to matrix such that first element of matrix is elements of vector<int> ends and second element is "-2"
  3. Append now the elements of vector<int> points to matrix such that first element of matrix is elements of vector<int> points and second element is Index of points.

    Visual Representation :-

    Input:

    starts: {1, 2, 3} ends: {4, 5, 6} points: (7, 8, 9}

    Output:

    matrix: { {1, -1}, {2, -1}, {3, -1}, {4, -2}, {5, -2}, {6, -2}, {7, 0}, {8, 1}, {9, 2} }

Currently I am using a push_back with for-loop function which works perfectly fine but when the input size is big code is very slow.

Code I am using is as follows:

vector<pair<int,int>> fast_count_segments(
    vector<int> starts, 
    vector<int> ends, 
    vector<int> points) 
{
   int i = 0;
   vector<pair<int,int>>matrix;

   for(i; i<starts.size(); i++) {
       matrix.push_back(make_pair(starts[i],-1));
   }
   for(i; i<starts.size()+ends.size(); i++) {
       matrix.push_back(make_pair(ends[i-starts.size()],-2));
   }
   for(i; i<starts.size()+ends.size()+points.size(); i++) {
        matrix.push_back(make_pair(
            points[i-starts.size()-ends.size()],
            i-(starts.size()+ends.size())
        ));
   }
   return matrix;
}

Can you please help on how to fill the 2D vector quickly with these requirements without iterating through each element. I am using C++11. Thanks in Advance !!

How to check the value of an element in c++? [closed]

I'm trying to check for the element of a vector in c++, I have the following:

vector<string> result;

result.push_back('zeroth');
result.push_back('first');
result.push_back('second');

if (result[0] == 'zeroth') {
    //do stuff
}

and it throws the error: no operator "==" matches these operands -- operand types are: std::string == int

any way I can fix this? Thanks...

Deleting a specific element in an array of Vectors C++ [duplicate]

I'm quite stuck on this function for a c++ program.

Instructions Write a function called RemoveGrades that takes the student array and grade vector as parameters, it asks the user for a valid assignment number, loops through each student, and removes the selected assignment from each student's grades vector.

I've searched a lot about deleting specific elements from vectors but can't seem to figure out how to get vector.erase() to work. I think the issue is that I'm working with a vector of arrays of ints.

code

given

// may be declared outside the main function

const int NUM_STUDENTS =3; 

// may only be declared within the main function

string Students[NUM_STUDENTS] = {"Eric","Stacy","Mark"};

vector <int> grades[NUM_STUDENTS] {
    {10,98,88,99,57},
    {62,80,94,100,93},
    {11,82,28,85,38}
};

void RemoveGrades(string Students[],vector<int> grades[],int numstudents){
    cout<<"Remove assignment"<<endl;
    int assignmentNum;
    assignmentNum=getValidAssignmentNumber();
    for (int index=0;index<numstudents;index++) {
           grades[index].erase(assignmentNum);

    }
}

If I put in two arguments in grades[index].erase clion tells me I need one argument, and if I put one it tells me I need two. Any help is appreciated. Thanks

Error messages

No matching member function for call to 'erase' candidate function not viable: requires single argument '__position', but 2 arguments were provided

In function 'void RemoveGrades(std::string*, std::vector*, int)': /cygdrive/c/Users/Ryan Foster/CLionProjects/arrays_and_vectors_second_try/main.cpp:191:56: error: no matching function for call to 'std::vector::erase(int&, int&)' grades[index].erase(assignmentNum,assignmentNum);

How to write a custom file using loops? C++

When i try to type the sentence and press enter it does nothing it keeps running. This part of the code is in a class name createFile, the code runs inside a menu using a do while and a switch, when i use the code in a function it runs perfect, but when i use it in a class it never stops.

myFile.open("myText.txt");

cout << "Entre una oracion." << endl;
while (cin >> oracion) {

    myFile << oracion << " ";

}


myFile.close();

School Management Simple C++ Project [closed]

I have an exercise on structures. Here is the statement:

Write a program in C++ that contains the following operations:

Define a structure type to represent a student with the fields

last name, first name

Date of birthday

the average of grades per semester(for storage, use an 8-element tab of type reels)

course

group.

Question: write a function that displays the name of the student with the highest average of each course.

I need help thanks in advance this fonction is not working: void checkTheHeighMark(student Univ[], int AmOfStu) { double sum1=0, sum2=0, sum3=0, sum4=0, ppt1, ppt2, ppt3, ppt4, moy1, moy2, moy3, moy4; int indice1=0, indice2=0, indice3=0, indice4=0; int a=0,b=0,c=0,d=0; bool k1, k2, k3, k4; sum1 = 0;sum2 = 0;sum3 = 0;sum4 = 0; k1 = 0;k2 = 0;k3 = 0;k4 = 0; for (int i = 0; i < AmOfStu; i++) { for (int j = 0; j < 8; j++) { if (Univ[i].course == 1) { sum1 += Univ[i].GR.grades[j]; k1 = 1; a++; } if (Univ[i].course == 2) { sum2 += Univ[i].GR.grades[j]; k2 = 1; b++; } if (Univ[i].course == 3) { sum3 += Univ[i].GR.grades[j]; k3 = 1; c++; } if (Univ[i].course == 4) { sum4 += Univ[i].GR.grades[j]; k4 = 1; d++; } } if (k1) { moy1 = sum1 / 8; Univ[i].average1 = moy1; } if (k2) { moy2 = sum2 / 8; Univ[i].average2 = moy2; } if (k3) { moy3 = sum3 / 8; Univ[i].average3 = moy3; } if (k4) { moy4 = sum4 / 8; Univ[i].average4 = moy4; } } if (k1) { ppt1 = 1.0; for (int i = 0; i < a; i++) { if (Univ[i].average1 >= ppt1){ ppt1=Univ[i].average1; indice1 = i; } } cout << "student " << Univ[indice1].name << endl; cout << "heigh mark " << Univ[indice1].average1<<endl; } if (k2) { ppt2 = 1.0; for (int i = 0; i < b; i++) { if (Univ[i].average2 >= ppt2){ ppt2=Univ[i].average2; indice2 = i; } } cout << "student " << Univ[indice2].name << endl; cout << "heigh mark " << Univ[indice2].average2<<endl; } if (k3) { ppt3 = 1.0; for (int i = 0; i < c; i++) { if (Univ[i].average3 >= ppt3){ ppt3=Univ[i].average3; indice3 = i; } } cout << "student " << Univ[indice3].name << endl; cout << "heigh mark " << Univ[indice3].average3<<endl; } if (k4) { ppt4 = 1.0; for (int i = 0; i < d; i++) { if (Univ[i].average4 >= ppt4){ ppt4=Univ[i].average4; indice4 = i; } } cout <<"student " << Univ[indice4].name << endl; cout << "heigh mark " << Univ[indice4].average4<<endl; } }

Whether the io buffer will be automatically emptied when the program crashes?

Let's talk about c++ programming, whether the IO buffer will be automatically cleared when the program crashes?if not, then there must be some considerations behind that, what's the reason?

Is the IO buffer shared memory or space allocated by each program individually?

Can Clock with direct QueryPerformanceCounter value be conforming to C++ Standard?

Assuming I want to create Clock with direct QueryPerformanceCounter Windows API result. QueryPerformanceCounter Windows API returns some counter that should be divided by QueryPerformanceFrequency result, thus producing time in seconds.

Usually Clock based on QueryPerformanceCounter would immediately convert result to some units by multiplying by some period and dividing by QueryPerformanceFrequency. This is how steady_clock could be implemented on Windows.

But suppose that for performance reasons I want to avoid division until really needed. So time_point is direct QueryPerformanceCounter value, and duration is the difference of such. And I can perform arithmetic and comparison on those values most of the time, converting to some normal duration or time_point only the final result.

I'm sure it is possible. My question is: will such Clock be fully compatible with standard Clock.

Why return value optimization does not work when return ()

My code is as follows. Why () makes RVO fail?

A fn() {
    A a{};
    return (a); // move constructor of class A works
    return a;   // RVO works
}

int main() {
    A a = fn();
    return 0;
}

std::tr2::sys is not available in latest version of C++

I'm using complete() function of std::tr2::sys namespace but it is not available latest vesion of c++, Please suggest me any alternative. Thanks

Generic implementation to get size of typelist

How to implement generic SizeOfT template for typelists? I'm learning C++ template metaprogramming, decided to implement SizeOfT template to get the number of types a typelist contain. I came up with following code.

template <typename... Ts>
struct TypeList1;

template <typename... Ts>
struct TypeList2;

template <typename H, typename... Ts>
struct SizeOfT;

// Specialized for TypeList1
template <typename H, typename... Ts>
struct SizeOfT <TypeList1<H, Ts...>> {
    constexpr static auto value = 1 + sizeof...(Ts);
};

template <>
struct SizeOfT <TypeList1<>> {
    constexpr static auto value = 0;
};

// Specialized for TypeList2, works fine but
// it would be less code if generic SizeOfT can be implemented which can handle
// both TypeList1 and TypeList2 and maybe any future TypeList3 and so on...
template <typename H, typename... Ts>
struct SizeOfT <TypeList2<H, Ts...>> {
    constexpr static auto value = 1 + sizeof...(Ts);
};

template <>
struct SizeOfT <TypeList2<>> {
    constexpr static auto value = 0;
};

int main() {
    using tl1 = TypeList1<int, char, bool>;
    using tl2 = TypeList2<float, double>;

    static_assert(SizeOfT<tl1>::value == 3, "tl1 size is not 3");
    static_assert(SizeOfT<tl2>::value == 2, "tl2 size is not 2");

    return 0;
}

Everything works fine in the above code. However, I would like to make SizeOfT more generic so that if new typelist TypeList3 is added, I don't need to provide any specialization for that.

I'm using a C++11 conformant compiler.

Having trouble to add "not" in to the string

#include <iostream>
    #include <string>
    using namespace std;
    string isNOT (string str1);
    int main()
    {
        cout << isNOT("This is me") << endl;
        //This is not me
        cout << isNOT("is is") << endl;
        //is not is not
        cout << isNOT("What is yellow?") << endl;
        //What is not yellow?
        return 0;
    }

string isNOT (string str1){
            int lens = str1.size();
            string result;
            string NOT1 = "not ";
            if (str1.find("is")){ //checks if has "is"
                for (int i = 0; i < lens; ++i) { 
                    if (str1 == "is"){
                    result = str1.insert(i + 1, NOT1); //suppose to append not into the string
                    }
                }
            }
         return result;
        }

Deduce type of reference template parameter

If one has a

template <class T>
class A{};

// global namespace, static storage duration
static constexpr A<int> a;

is it possible to deduce the type A<int> by passing a as a reference template param such as:

// This question asks to make the syntax in the following line compile:
static_assert(std::is_same<A<int>, typename GetReferenceType<a>::type>::value, "");
// I am aware the next line works, but it's not what I am looking for in this question, since
// I not only want to deduce `A<int>` but also `int`
static_assert(std::is_same<A<int>, decltype(a)>::value, "");

// This is pseudo code of how this could work in theory
template <const T& RefT, class T> // I know this does not compile, but this shows what I want
struct GetReferenceType{          // which is automatically deduce type `T` without having to 
  using type = T;                 // write it out
};

This should also work, but does not fulfill the above syntax requirement:

template <class T>
constexpr auto GetReferenceTypeFunc(const T& t) -> T;

static_assert(std::is_same<A<int>, decltype(GetReferenceTypeFunc(a))>::value, "");

Why I want to do this

Imagine a does not have a short type A<int> but instead something like A<OmgWhyIsThisTypeNameSoLong>.

Then, if you want to instantiate a type with A<OmgWhyIsThisTypeNameSoLong>, you'd have to write:

Instantiate<A<OmgWhyIsThisTypeNameSoLong>>;

It just so happens that we already have global object a, so it would be nice not to have to write that long type but instead Instantiate<a>.

There is of course the option of creating an alias using AOmg = A<OmgWhyIsThisTypeNameSoLong> but I would really like to get around spamming the namespace with another very similar name to A.

jeudi 26 mars 2020

Behavior difference of lambda function mutable capture from a reference to global variable

I found the results are different across compilers if I use a lambda to capture a reference to global variable with mutable keyword and then modify the value in the lambda function.

#include <stdio.h>
#include <functional>

int n = 100;

std::function<int()> f()
{
    int &m = n;
    return [m] () mutable -> int {
        m += 123;
        return m;
    };
}

int main()
{
    int x = n;
    int y = f()();
    int z = n;

    printf("%d %d %d\n", x, y, z);
    return 0;
}

Result from VS 2015 and GCC (g++ (Ubuntu 5.4.0-6ubuntu1~16.04.12) 5.4.0 20160609):

100 223 100

Result from clang++ (clang version 3.8.0-2ubuntu4 (tags/RELEASE_380/final)):

100 223 223

Why does this happen? Is this allowed by the C++ Standards?