jeudi 31 décembre 2020

VS2015 uses c++11 syntax difference

The program runs normally under the Linux system, and now the following error occurs when using VS2015 on the Windows7 system

note: see declaration of 'ncorr::details::base_region<T_container>::operator ='

note: definition

note: 'std::enable_ifstd::is_same<container_traits<T_container2::nonconst_container,base_region<T_container>::nonconst_container>::value,ncorr::details::base_region<T_container>&>::type ncorr::details::base_region<T_container>::operator =(const ncorr::details::base_region<T_container> &)'

note: existing declarations

note: 'ncorr::details::base_region<T_container> &ncorr::details::base_region<T_container>::operator =(container_traits<T_container>::const_reference)'

note: 'ncorr::details::base_region<T_container> &ncorr::details::base_region<T_container>::operator =(container_traits<T_container>::const_container &)'

etc

I feel that this is usually a problem with VS2015, and certain C++ syntaxes are somewhat different on VS2015. Below is the code part, thanks for telling me the improvement part

// Base Region -----------------------------------------------------------//
    template <typename T_container>
    base_region<T_container>& base_region<T_container>::operator=(const base_region &reg) {
        if (this->region_h != reg.region_h || this->region_w != reg.region_w) {
            throw std::invalid_argument("Attempted to assign region of size: " + reg.region_size_2D_string() + 
                                        " to region of size: " + region_size_2D_string() + ".");
        }
               
        std::copy(reg.begin(), reg.end(), this->begin());
        
        return *this;
    }  
    
    template <typename T_container>
    template <typename T_container2>
    typename std::enable_if<std::is_same<typename container_traits<T_container2>::nonconst_container, typename base_region<T_container>::nonconst_container>::value, base_region<T_container>&>::type base_region<T_container>::operator=(const base_region<T_container2> &reg) {
        if (this->region_h != reg.region_h || this->region_w != reg.region_w) {
            throw std::invalid_argument("Attempted to assign region of size: " + reg.region_size_2D_string() + 
                                        " to region of size: " + region_size_2D_string() + ".");
        }
               
        std::copy(reg.begin(), reg.end(), this->begin());
        
        return *this;
    }  

C++ Casino Game Deck and Card classes questions [closed]

I got some great feedback the other day about how I could improve and implement my Casino game further. I had some follow up questions to this. Questions will be below and code will follow.

Questions - Card Class

  1. When creating Card() is there a reason I am setting the strings to "" and the int to 0? This is something I had to do in my intro class and I really don't get the purpose.
  2. For my setNumber/setSuit/setvalue, are these actually being used? If so, what is the purpose of them exactly?
  3. The same as above for getNumber/getSuit/getValue, I know that these return the value but as of right now it doesn't seem like I need those values returned right?
  4. print() was something I copied from another blackjack game someone else was making on YouTube since I was stuck a bit. However, I was told print() shouldn't be used like this. So how would I cout the card/deck without this?

Questions - Deck Class

  1. Mostly on this one, it's the same question as 4 for the card class. I don't want to use print() but how else do I output the cards in my main class?

Questions - Main Class (May seem like very basic questions but just want to confirm my thinking)

  1. Deck playingDeck is declaring the object playingDeck in my main class. I am then printing that deck. Then I am shuffling that deck. The below questions all revolve around this.
    1. In my line that says "Deck playingDeck", is this creating the deck of cards with the 52 cards?
    2. Since I want to remove printDeck(), how can I achieve the same thing without using printDeck()? I don't know of a way to cout an object so to speak.
    3. This one may be a stupid question, but I just want to confirm. When I do playingDeck.shuffle() that is shuffling my playingDeck object right? That is now permanently changed to a shuffled deck? ​

main.cpp

#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <cctype>
#include "Card.h"
#include "Deck.h"
using namespace std;

void showMenu(int &choice);
int blackjackGame(int betAmount, int userBalance);
int threeCardGame(int betAmount, int userBalance);
int highCardGame(int betAmount, int userBalance);
int getValidBet(int betAmount, int userBalance);


int main()
{
    int userBalance;
    int userChoice;
    int betAmount;
    string userName;
    bool keepGoing = true;


    // Creates playing deck.
    Deck playingDeck;
    playingDeck.printDeck();
    cout << "Shuffled Deck..." << endl;
    playingDeck.shuffle();
    playingDeck.printDeck();

Deck.cpp

#include "Deck.h"
#include "Card.h"
#include <iostream>
#include <iomanip>
#include <string>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>


Deck::Deck()
{
    string cardNumbers[13] = {"TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN", "JACK", "QUEEN", "KING", "ACE"};
    string cardSuits[4] = {"HEARTS", "DIAMONDS", "SPADES", "CLUBS"};
    int cardValues[13] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11};
    deck = new Card[CARDS_PER_DECK];
    int suitCounter = 0;
    for (int i=0; i < 52; i++)
    {
        deck[i] = Card(cardNumbers[i % 13], cardSuits[suitCounter], cardValues[i%13]);
        if ((i+1) % 13 == 0)
        {
            suitCounter = suitCounter + 1;
        }
    }
}
void Deck::printDeck() const
{
    for (int i=0; i < 52; i++)
    {
        cout << deck[i].print() << endl;
    }

}
void Deck::shuffle()
{
    srand(time(NULL));

    for (int original = 0; original < 52; original++)
    {
        int r = rand() % 52;

        Card temp = deck[original];
        deck[original] = deck[r];
        deck[r] = temp;

    }
}

Card.cpp

#include "Card.h"

Card::Card()
{
    cardNumber = "";
    cardSuit = "";
    cardValue = 0;
}

Card::Card(string num, string suit, int value)
{
    cardNumber = num;
    cardSuit = suit;
    cardValue = value;
}
void Card::setNumber(string num)
{
    cardNumber = num;
}
void Card::setSuit(string suit)
{
    cardSuit = suit;
}
void Card::setValue(int value)
{
    cardValue = value;
}
const string Card::getNumber() const
{
    return cardNumber;
}
const string Card::getSuit() const
{
    return cardSuit;
}
const int Card::getValue() const
{
    return cardValue;
}
string Card::print() const
{
    return (cardNumber + " of " + cardSuit);
}

erase map element using an iterator inside a function

I need to erase map elements using an iterator inside a function which takes map iterator as argument, but getting runtime error(free(): double free detected). This is my code:

#include <iostream>
#include <map>

std::map<int32_t, int32_t> mapp;

void erasee(std::map<int32_t, int32_t>::iterator itr) {
    itr = mapp.erase(itr);
}

int main()
{
    mapp.emplace(1, 1000);
    
    std::map<int32_t, int32_t>::iterator itr = mapp.begin();
    while(itr != mapp.end()) {
        std::cout << "before" << std::endl;
        
        erasee(itr);
        
        std::cout << "after" << std::endl;
    }
    
    return 0;
}

std::thread arguments are copied on the new thread?

I have started reading "C++ Concurrency in action, seconds edition" by Anthony Williams. In its 2.2 section he writes that arguments to the thread function are copied on the new thread. I checked this on a couple of compilers, and it is true: if we pass an lvalue - it is copied on the new thread.

Anthony writes that this may represent undefined behaviour - lvalue may go out of scope on the original scope, while new thread starts up.

This is kind of scary. Does this mean that every std::thread constructor invocation has a potential race? Why this copying is not synchronized prior to returning from std::thread constructor? Why it is not copied on the original thread altogether?

mercredi 30 décembre 2020

C++ problem returning the correct pattern from given interleaved pattern

I'm trying to implement a function in C++ that gets two inputs, one input is an array of integers value (binary values just zero or one) , the second input is an integer value one of those values: 1 , 2, 4, 8.

the function returns the correct pre-mapped pattern according to this table: multiple Mapped Value = 0 Mapped Value= 1 1 0 1 2 00 11 4 1100 0011 8 11001100 00110011

I mean by pre-mapped pattern, a pattern that it was before mapping it according to the table !.

to elaborate more, I'm giving examples: (Remap is the name of the function, we always read the given input array from left to right ..)

Ramp(given array, multiply value)

first example: Remap({0,1} , 1 ) => returns an integer array according to the table {0, 1}; (we see that 0 is mapped to value 0 , 1 is mapped to value 0 if the multiply=1)

second example: Remap({1 ,1 , 0 , 0} , 2 ) => returns an integer array according to the table {1 ,0}; (we see that 11 is mapped to value 1 , 00 is mapped to value 0 if the multiply=2, so the output is {1,0})

third example: Remap({1 ,1 , 0 , 0 , 0 , 0 , 1 , 1} , 4 ) => returns an integer array according to the table {0 ,1}; (we see that 1100 is mapped to value 0 , 0011 is mapped to value 1 if the multiply=4 so output is {0,1})

third example: Remap({1 ,1 , 0 , 0 , 1 , 1, 0 , 0} , 8) => returns an integer array according to the table {0}; (we see that 11001100 is mapped to value 0 if the multiply=8 so output is {0} )

the given array is always in its rules according to the table, this means there's no case like the patterns in the given array aren't the same as the patterns on the table, for instance this array {001} with multiply 2 isn't possible .. !

In brief we are returning the pre-mapped pattern according to the attached table of mapping. (the attached table is given by default in the question itself) My implementation code C++ is:

std::vector Remap(int* givenArray , int multiply)
{
     vector<int> ret;                                                      // result's utput
  switch (multiply)
   {   case 1
          int l[2]={0,1};                                               // for first opition in the table
          for (int i=0;i<2;i++)
              ret.puch_back({0,1});
      case 2
          int l[4]={0 ,0 ,1 ,1};                                           // for second opition in the table
          for (int i=0;i<4;i++)
              ret.puch_back({0 ,0 ,1 ,1});
      case 4
          int l[8]={0 ,0,1 ,1 ,1 ,1 ,0 ,0};                                  // for third opition in the table
          for (int i=0;i<8;i++)
              ret.puch_back({0 ,0,1 ,1 ,1 ,1 ,0 ,0});
      case 8
          int l[16]={0 ,0,1,1,1,1,0,0 ,1,1,0,0,0,0,1,1};                // for fourth opition in the table
          for (int i=0;i<16;i++)
              ret.puch_back({0 ,0,1,1,1,1,0,0 ,1,1,0,0,0,0,1,1});
   }
  return ret // returning the pre-mapped array to the function main
}

int main()
{
    int MappedPattern[4]={0,0,1,1};
    vector<int> PremappedPattern=Remap(MappedPattern , 2 ) // it should return {0,1} because 00 -> 0 , 
     //11->1 according to the table over multiply =2
    return 0;
}

What's wrong with my code? any help please in my implementation for the problem? honestly Im stuck on this about one week, so it would be appreciated if there's any assistance to solve my problem or any other algorithms suggestions for my problem!

THANKS ALOT.

"Capture by move" does not prevent capture by reference

When I write [&,x](){ /* making use of x */ }, x is captured by value.

When I write [=,&x](){ /* making use of x */ }, x is captured by reference.

If I try writing [&x, x](){ … } I get an error telling me x can appear only once in a capture list.

However, [&x, y = std::move(x)](){ /* making use of x and y */ }(); compiles fine but I get a segmentation fault.

Why does the code even compile? Why does the standard allow that I capture a variable by reference and I also use it in a "capture by-move" init capture?

What would a default lambda capture mode via init capture be like?

With lambdas, in C++11, we can have a default capture mode set to by-value/by-ref, e.g. [=]/[&], optionally followed by explicit captures, by-ref/by-value, for some variables, e.g. [=,&this_is_by_ref] or [&,this_is_by_value].

In C++14, we can also have explicit captures by-move, e.g. [y = std::move(x)].

In Effective Modern C++, Item 32, 3rd paragraph, I read

The one thing you can't express with an init capture is a default capture mode, […]

What is the author most likely referring to?

We already have a way to capture all variables we need by copy or by reference. Why would we want to express that with the x = y form?

Maybe the author is referring only to the a "capture by move default"? Something which would work like [x = std::move(x), y = std::move(y), …] with all variables used in the body listed?

C++ Parent Class with Abstracted Function that Uses Functions in a Child Class

I am trying to create a C++ parent class that has two functions, f1 and f2, to be implemented in the child class. This parent class has a function, abstractedFunction that abstracts how f1 and f2 should be used together. Both f1 and f2 are implemented in the child class as shown in the code below.

#include <iostream>

class Parent
{
public:
    int f1();        // To be implemented in the derived class
    void f2(int i);  // To be implemented in the derived class
    void abstractedFunction() { // Abstracted in the parant class 
        auto r = f1();
        f2(r);
    }
};

class Child : public Parent
{
public:
    int f1() {
        std::cout << "f1 is implemented in the child class\n";
        return 1;
    }

    void f2(int i) {
        std::cout << "f2 is implemented in the child class\n";
        std::cout << "Return value for f1 = " << i << "\n";
    }
};

int main() {
    Child ch;
    ch.abstractedFunction();
    return 0;
}

Is such a concept implementable in C++?

std::bitset

Seems like std::bitset<N> under the hood is an array of unsigned longs now, this means that there will be an (heavy?) overhead when N is small. sizeof(std::bitset<8>) is 8 bytes!

Is there a reason why the type of underlying array itself is not a template parameter? Why does the implementation not use uint32_t/16_t/8_t when more appropriate? I do not see anything in the implementation that limits this?

I am guessing I am missing a particular reason but unsure how to look for it or maybe there is no reason at all ? Since this is such a simple container I am not able to understand how the zero overhead principle of C++ seems to be avoided here.

GCC Impl: https://gcc.gnu.org/onlinedocs/gcc-4.6.2/libstdc++/api/a00775_source.html

I believe clang is similar (used sizeof to confirm)

Is there a better way to initalize pointers in c++?

Below I have a bit of code for implementing Huffman compression. What I was curious about was if I could initialize the left and right pointers without including cstdlib, or rather, if I could initialize an empty memory location for storing the left and right without using malloc.

Also, in my combine function, I do not want to use "NULL" for the string parent node of my left and right, but would rather have an empty string. Will I have to make a new constructor for this? I get an error (basic_string::_M_construct null not valid) when I replace "NULL" with nullptr.

#include <string>
#include <cstdlib>

#ifndef PRIORITY_NODE
#define PRIORITY_NODE

namespace Huffman
{
  class PriorityNode
  {
    private:
      std::string key; // The character sequence to compress
      long frequency = 0;  // The frequency of the character sequence
      PriorityNode* left = (PriorityNode*)malloc(sizeof(PriorityNode));
      PriorityNode* right = (PriorityNode*)malloc(sizeof(PriorityNode));
    
    public:
      PriorityNode(std::string k, long f): frequency(f), key(k){};
      std::string getKey() const{ return key;}
      long getFrequency() const{ return frequency;}
      void setLeft(const PriorityNode& left){*this->left = left;}
      void setRight(const PriorityNode& right){*this->right = right;}
      PriorityNode& getLeft() const{ return *left;}
      PriorityNode& getRight() const{ return *right;}
      friend PriorityNode combine(const PriorityNode& lhs, const PriorityNode& rhs)
      {
        long ret_freq = lhs.getFrequency() + rhs.getFrequency();
        PriorityNode ret = PriorityNode("NULL", ret_freq);
        ret.setLeft(lhs);
        ret.setRight(rhs);
        return ret;
      };
  };
}

#endif

Rental Service Usaco [closed]

Problem: http://www.usaco.org/index.php?page=viewproblem2&cpid=787

I've been getting only 3 cases right (1,5 and 7) in this problem but I can't find why.

So first of all when looking at this problem I realized that you want to rent the cows that produce less milk and sell first to the ranches that pay more, so after collecting the data I sorted it like this

by money

10 25

15 15

2 10

by money but I assign them the cow that gives the least amount of gallons

250 1

80 2

100 4

40 6

0 7

The commented code prints these

I then traverse the Rent vector from n-1 to 0 and I compare the money we get if a cow is rented vs the one if its milk is sold

In this function, if s which is the variable I assign to the gallons is more than the gallons I'm allowed to sell then I subtract the gallons I am allowed to sell to s I update the total and I go to the next ranch, else I update the total, set the variable Sale2 to the gallons I can sell- s and I set s to 0

if the total is more than what I get from renting I set Sale2 to the gallons the actual ranch buys, update the variable I use to traverse the sale vector, and I return the total, else I return the Rent

And if we are done with the ranches I only return the renting money

Here is my code:

#include<bits/stdc++.h>

using namespace std;

struct trip {
    long long c, m;

    bool operator < (const trip& y) const {
        return m > y.m;
    }

};

long long n, m, r, amount = 0;
vector < long long > v;
vector < pair < long long, long long >> Rent;
vector < long long > p;
vector < trip > Sale;

long long x = 0;
long long RentOrSale(long long act) {
    long long total = 0;
    long long s = Rent[act].second;
    long long i = x;
    long long Sale2 = 0;
    if (i >= m) {
        return Rent[act].first;
    }
    while (s > 0 && i < m) {
        if (s >= Sale[i].c) {
            total += Sale[i].m * Sale[i].c;
            s -= Sale[i].c;
            i++;
        }
        else {
            total += s * Sale[i].m;
            Sale2 = Sale[i].c - s;
            s = 0;
        }
    }
    if (Rent[act].first < total) {

        if (Sale2 != 0) {
            Sale[i].c = Sale2;
        }
        x = i;
        return total;
    }

    return Rent[act].first;
}

int main() {
    ifstream cin("rental.in");
    ofstream cout("rental.out");
    cin >> n >> m >> r;

    for (long long i = 0; i < n; i++) {
        long long a;
        cin >> a;
        v.push_back(a);
        amount += a;
    }

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

    for (long long i = 0; i < m; i++) {
        long long a, b;

        cin >> a >> b;

        Sale.push_back({
          a,
          b
            });
    }

    sort(begin(Sale), end(Sale));

    for (long long i = 0; i < r; i++) {

        long long a;
        cin >> a;
        p.push_back(a);

    }
    sort(Rent.rbegin(), Rent.rend());

    for (long long i = 0; i < n; i++) {
        if (i < r) {
            Rent.push_back(make_pair(p[i], v[i]));
        }
        else {
            Rent.push_back(make_pair(0, v[i]));
        }
    }

    /*
      for (int i = 0; i < m; i++) {
          cout << Sale[i].c << ' ' << Sale[i].m <<endl;
      }
      cout << endl << endl;

      for (int i = 0; i < n; i++) {
          cout << Rent[i].first <<' '<< Rent[i].second<<endl;
      }


  */
    long long act = n - 1;
    long long money = 0;

    for (act = n - 1; act >= 0; act--) {

        money += RentOrSale(act);
        amount -= Rent[act].second;
        if (amount == 0) {
            break;
        }
    }

    cout << money;
    return 0;
}

Is there a version of itoa that returns how many characters were written to the buffer?

I am currently calling _itoa_s and then calling strlen to figure out how many characters were written. Is there a similar method to itoa that either returns the new pointer to the start of the buffer, or returns how many characters were written? I have not been able to find a method in the standard library that provides this functionality.

New to using GDB

can someone guide me a bit. i'm working a program, but it fails every time i use the browser to "talk" to it. Being new to using GDB, i have no idea what i'm reading. Except for the possible error in the sockethandler.cpp. And yes, i did research Segmentation fault. this is what GDB returned.

Program received signal SIGSEGV, Segmentation fault.
e0x00007ffff7eb2da3 in std::_Rb_tree_increment(std::_Rb_tree_node_base*) () from /lib/x86_64-linux-gnu/libstdc++.so.6
#0  0x00007ffff7eb2da3 in std::_Rb_tree_increment(std::_Rb_tree_node_base*) () from /lib/x86_64-linux-gnu/libstdc++.so.6
#1  0x000055555558a30f in std::_Rb_tree_iterator<std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const, Socket*> >::operator++ (this=0x7fffffffe380) at /usr/include/c++/10/bits/stl_tree.h:287
#2  0x000055555558a075 in SocketHandler::runLoop () at SocketHandler.cpp:75
#3  0x000055555557bdbc in run_aureleys_ai () at Main.cpp:281
#4  0x000055555557addc in main (argc=1, argv=0x7fffffffe518) at Main.cpp:92
#0  0x00007ffff7eb2da3 in std::_Rb_tree_increment(std::_Rb_tree_node_base*) () from /lib/x86_64-linux-gnu/libstdc++.so.6
No symbol table info available.
#1  0x000055555558a30f in std::_Rb_tree_iterator<std::pair<std::__cxx11::basic_string<char, 
std::char_traits<char>, std::allocator<char> > const, Socket*> >::operator++ (this=0x7fffffffe380) 
at /usr/include/c++/10/bits/stl_tree.h:287 
No locals
#2  0x000055555558a075 in SocketHandler::runLoop () at SocketHandler.cpp:75
        s = {first = <error: Cannot access memory at address 0x1>, second = 0x0}
        input_sockets = {fds_bits = {16, 0 <repeats 15 times>}}
        timeout = {tv_sec = 2, tv_usec = 424901}
        sock = 0x0
        socket = -1
        result = 1
#3  0x000055555557bdbc in run_aureleys_ai () at Main.cpp:281
# No locals.
#4  0x000055555557addc in main (argc=1, argv=0x7fffffffe518) at Main.cpp:92
# No locals.
Thread 1 (process 2829 "aureleys_ai"):
#0  0x00007ffff7eb2da3 in std::_Rb_tree_increment(std::_Rb_tree_node_base*) () from /lib/x86_64-linux-gnu/libstdc++.so.6
No symbol table info available.
#1  0x000055555558a30f in std::_Rb_tree_iterator<std::pair<std::__cxx11::basic_string<char, 
std::char_traits<char>, std::allocator<char> > const, Socket*> >::operator++ (this=0x7fffffffe380) 
at /usr/include/c++/10/bits/stl_tree.h:287
No locals.
#2  0x000055555558a075 in SocketHandler::runLoop () at SocketHandler.cpp:75
        s = {first = <error: Cannot access memory at address 0x1>, second = 0x0}
        input_sockets = {fds_bits = {16, 0 <repeats 15 times>}}
        timeout = {tv_sec = 2, tv_usec = 424901}
        sock = 0x0
        socket = -1
        result = 1
#3  0x000055555557bdbc in run_aureleys_ai () at Main.cpp:281
No locals.
#4  0x000055555557addc in main (argc=1, argv=0x7fffffffe518) at Main.cpp:92
No locals.

no matching function for call to std::get with const tuple ref as argument

I've been trying to make a generic function in order to build a query in SQL. In order to do that, I went and used tuple with variadic template, in order to make the query more generic. This is the code (This is not a final code so understand some of the code is pseudo-code):

#include <tuple>

template<std::size_t I>
struct Visit_Tup_Impl
{
  template<typename ...T>
  static const std::string& visit_tup (const std::tuple<T...>& values, int comp)
  {
    if (I == comp)
    {
      std::get<I, std::tuple<T...> > (values);
      return EMPTY_STRING;
    }
    else
    {
      return Visit_Tup_Impl<I-1>::visit_tup (values, comp);
    }
  }
};

template<>
template<>
const std::string&
Visit_Tup_Impl<0>::visit_tup (const std::tuple<>& values, int comp)
{
  assert (0 && "Should not happen");
  return EMPTY_STRING;
}

template <typename ...T>
std::string
create_coupled_query (const std::vector<std::string>& keys,
                      const std::vector<std::tuple<T...> >& values)
{
  std::ostringstream local;
  local << "(";

  auto iter = values.begin ();
  auto iter_end = values.end ();
  for (; iter != iter_end; ++iter)
  {
    local << "(";
    int i = 1;
    do
    {
      local << keys [i] << "=" << to_sql_string (Visit_Tup_Impl<(sizeof...(T) - 1)>::visit_tup (*iter, i));
      ++i;
      if (i < keys.size ())
        local << " AND ";
    }
    while (i < keys.size ());

    local << ")";
    if (iter + 1 != iter_end)
      local << " OR ";
  }

  local << ")";

  return local.str ();
}

This is the line that wouldn't compile:

std::get<I, std::tuple<T...> > (values);

I Get This compilation error:

no matching function for call to ‘get(const std::tuple<ACE_Time_Value, ACE_Time_Value, std::basic_string<char, std::char_traits, std::allocator > >&)’

Also, it gives me suggestions for std::get candidates (under utility.h):

template<long unsigned int _Int, class _Tp1, class _Tp2> constexpr typename std::tuple_element<_Int, std::pair<_Tp1, _Tp2> >::type& std::get(std::pair<_Tp1, _Tp2>&)

and some more, which are not relevant for me.

Ur help compiling this please

Hand written move

I have written a vector class to learn move semantics. I use move constructor to move T (commented line).

My question is why not to just copy all the bytes of temp object and set all bytes of temp object to zero?

I know that the destructor will be called for temp object and it may require some initialized members to properly destruct. This can be reason why I must not change internal representation of the object.

But in case I'm 100% sure my ~T() don't have such requirements, is this a good optimization?

 20     void push_back(T&& val)
 21     {
 22         check_cap();
 23         //new (m_data + m_size) T(std::move(val));
 24         for(int i = 0; i < sizeof(T); ++i)
 25         {
 26             reinterpret_cast<char*> (m_data + m_size)[i] = reinterpret_cast<char*> (&val)[i];
 27             reinterpret_cast<char*> (&val)[i] = 0;
 28         }
 29         m_size++;
 30     }

(please don't tell anything about casts and their safety if it's not related to the actual question)

Comparesion between this Two codes ```num1 = value;``` & ```int num1 = value;```

enter image description here

What is the compare num1 = value; & (datatype)num1 = value; although finding (constant datatype) num1 =value [is global variable];

Thanks

How to put different template of std::function in a array? [duplicate]

Can I put different template of std::function in a array?

For example:

std::function<int(int)> funA;
std::function<int()> funB;
Sometype funArray[2] = {funA, FunB};

I tried to cast std::function<int(int)> to void*, it can be compiled successful, but the result was wrong, like this:

int a=0, b=0;
void* pFun = (void*)&funA;
std::function<int(int)> *fun = (std::function<int(int)> *)pFun;
(*fun)(a, b);

The method seems to work. But I must define the function at first. For example:

int Fun(int a)
{
    std::cout << a << std::endl;
    return ++(++a);
}

int main()
{
    std::function<int(int)> originPFun = Fun;
    void *ppFun;
    // ppFun = (void*)&Fun; // This way will cause segmentation fault
    ppFun = (void*)&originPFun; // This way can run seuccessful and get right result
    std::function<int(int)> *pFun = (std::function<int(int)>*)(ppFun);
    std::cout << (*pFun)(5) << std::endl;
    system("pause");
    return 0;
}

Meaning of vector

What does vector<int *>v and vector< int > *v mean ? Any link to reference material will also help.

mardi 29 décembre 2020

How do applications know how return the data an API requested?

Let's say I created Twilio. Below is their alerts API

https://www.twilio.com/docs/usage/monitor-alert:

Download the helper library from https://www.twilio.com/docs/python/install

import os
from twilio.rest import Client

Your Account Sid and Auth Token from twilio.com/console and set the environment variables. See http://twil.io/secure

account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
client = Client(account_sid, auth_token)

alert = client.monitor.alerts('NOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').fetch()

print(alert.alert_text)

Example JSON API response:

{
  "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "alert_text": "alert_text",
  "api_version": "2010-04-01",
  "date_created": "2015-07-30T20:00:00Z",
  "date_generated": "2015-07-30T20:00:00Z",
  "date_updated": "2015-07-30T20:00:00Z",
  "error_code": "error_code",
  "log_level": "log_level",
  "more_info": "more_info",
  "request_method": "GET",
  "request_url": "http://www.example.com",
  "request_variables": "request_variables",
  "resource_sid": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "response_body": "response_body",
  "response_headers": "response_headers",
  "request_headers": "request_headers",
  "sid": "NOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "url": "https://monitor.twilio.com/v1/Alerts/NOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "service_sid": "PNe2cd757cd5257b0217a447933a0290d2"
}

How does the application return the data above? How does it know to return the above data?

DO you have to create an object with the data above to respond to said API call> Does the programmer need to write a special function, they would not normally create if they didn't want to provide API access to the application, to respond to the api call that will return the data?

So for example if I had a website that enabled people to enter in their first and last names into a database. I would then need to write a program that utilized some function that inserted the names. If I then wanted to create an API to give others to retrieve the names from the database I would need to create another function, that I wouldn't create if I didn't have the API, to retrieve the names for the API call. Or I would create an API call that would make a request to some function that would return an object with all the data I said my API call would return; or the function would go searching around for the data create an object and then return the information to the person who made the call.

C++ Casino game - How to create player and dealer hands? [closed]

I am working on a rather simple Casino program in C++. I am somewhat newer to C++ but since my college uses it, I am trying to tackle this project with that language. This was inspired to me by a blackjack program I made with Java, however, classes seem much easier and make way more sense to me in Java compared to C++.

Code will be below and will post my questions below it.

main.cpp

#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <cctype>
#include "Card.h"
#include "Deck.h"
using namespace std;

void showMenu(int &choice);
int blackjackGame(int betAmount, int userBalance);
int threeCardGame(int betAmount, int userBalance);
int highCardGame(int betAmount, int userBalance);
int getValidBet(int betAmount, int userBalance);

enum cardSuits{HEART, SPADES, DIAMONDS, CLUBS};
enum cardValues{TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE};

int main()
{
    int userBalance;
    int userChoice;
    int betAmount;
    string userName;
    bool keepGoing = true;


    // Creates playing deck.
    Deck playingDeck;
    playingDeck.printDeck();
    cout << "Shuffled Deck..." << endl;
    playingDeck.shuffle();
    playingDeck.printDeck();


    cout << "Welcome to the casino program!" << endl;
    cout << "Please enter your name." << endl;
    cin >> userName;
    cout << "Please enter your starting balance." << endl;
    cin >> userBalance;

    while(keepGoing)
    {
        showMenu(userChoice);

        switch(userChoice)
        {
            case 1:
                blackjackGame(betAmount,userBalance);
                break;
            case 2:
                threeCardGame(betAmount,userBalance);
                break;
            case 3:
                highCardGame(betAmount,userBalance);
                break;
            case 4:
                break;
            default:
                break;
        }
    }
    return 0;
}
void showMenu(int &choice)
{
    // User Menu
    cout << "Please select a game" << endl;
    cout << "1) Blackjack" << endl;
    cout << "2) Three Card Poker" << endl;
    cout << "3) High Card Flush" << endl;
    cout << "4) Exit" << endl;
    cin >> choice;

    // Validates input
    while(choice < 1 || choice > 4)
    {
        cout << "You must enter either 1,2,3 or 4" << endl;
        cout << "Select an option (1,2,3,4)" << endl;
        cin >> choice;
    }
}
int getValidBet(int betAmount, int userBalance)
{
    cout << "Please enter the amount you would like to bet" << endl;
    cin >> betAmount;

    while(betAmount > userBalance || betAmount < 1)
    {
        cout << "Invalid entry." << endl;
        cout << "Please enter the amount you would like to bet" << endl;
        cin >> betAmount;
        cout << endl;
    }

    return betAmount;
}
int blackjackGame(int betAmount, int userBalance)
{
    cout << "Your current balance is $" << userBalance << endl;
    betAmount = getValidBet(betAmount, userBalance);
    cout << betAmount;
}
int threeCardGame(int betAmount, int userBalance)
{
    cout << "Your current balance is $" << userBalance << endl;
    betAmount = getValidBet(betAmount, userBalance);
    cout << betAmount;
}
int highCardGame(int betAmount, int userBalance)
{
    cout << "Your current balance is $" << userBalance << endl;
    betAmount = getValidBet(betAmount, userBalance);
    cout << betAmount;
}

Card.cpp

#include "Card.h"

Card::Card()
{
    cardNumber = "";
    cardSuit = "";
    cardValue = 0;
}

Card::Card(string num, string suit, int value)
{
    cardNumber = num;
    cardSuit = suit;
    cardValue = value;
}
void Card::setNumber(string num)
{
    cardNumber = num;
}
void Card::setSuit(string suit)
{
    cardSuit = suit;
}
void Card::setValue(int value)
{
    cardValue = value;
}
const string Card::getNumber() const
{
    return cardNumber;
}
const string Card::getSuit() const
{
    return cardSuit;
}
const int Card::getValue() const
{
    return cardValue;
}
string Card::print() const
{
    return (cardNumber + " of " + cardSuit);
}

Card.h

#ifndef CASINO_CARD_H
#define CASINO_CARD_H
#include <string>
using namespace std;

class Card
{
private:
    string cardNumber;
    string cardSuit;
    int cardValue;
public:
    Card();
    Card(string num, string suit, int value);

    void setNumber(string num);
    void setSuit(string suit);
    void setValue(int value);

    const string getNumber() const;
    const string getSuit() const;
    const int getValue() const;
    string print() const;

};


#endif //CASINO_CARD_H

Deck.cpp

#include "Deck.h"
#include "Card.h"
#include <iostream>
#include <iomanip>
#include <string>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>


Deck::Deck()
{
    string cardNumbers[13] = {"TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN", "JACK", "QUEEN", "KING", "ACE"};
    string cardSuits[4] = {"HEARTS", "DIAMONDS", "SPADES", "CLUBS"};
    int cardValues[13] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11};
    deck = new Card[CARDS_PER_DECK];
    int suitCounter = 0;
    for (int i=0; i < 52; i++)
    {
        deck[i] = Card(cardNumbers[i % 13], cardSuits[suitCounter], cardValues[i%13]);
        if ((i+1) % 13 == 0)
        {
            suitCounter = suitCounter + 1;
        }
    }
}
void Deck::printDeck() const
{
    for (int i=0; i < 52; i++)
    {
        cout << deck[i].print() << endl;
    }

}
void Deck::shuffle()
{
    srand(time(NULL));

    for (int original = 0; original < 52; original++)
    {
        int r = rand() % 52;

        Card temp = deck[original];
        deck[original] = deck[r];
        deck[r] = temp;

    }
}

Deck.h

#ifndef CASINO_DECK_H
#define CASINO_DECK_H
#include "Card.h"
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <algorithm>
#include <stdlib.h>

using namespace std;

const int CARDS_PER_DECK = 52;

class Deck
{
public:
    Deck();
    Card dealCard();
    void shuffle();
    void printDeck() const;
private:
    Card *deck;
    int currentCard;

};


#endif //CASINO_DECK_H

Questions

  1. So what I need to do next is have a way to create a playerHand and a dealerHand. In Java I was able to do this within the Deck class itself. I feel like that would not be possible to do in C++. What would be the best way to handle this?
  2. If another class like Hand.cpp for example is needed, in C++ how do I populate the deck, shuffle it, and then use that shuffled deck within Hand.Cpp where I could create the players hand and dealers hand?

Why I am getting different output in Visual Studio 2019 and on g++11 for the rvalue reference implementation in the following code? [duplicate]

I was trying out an example for rvalue reference in a copy constructor as shown in below code but the output are different on different compilers and able to understand why this difference is coming as this rvalue thing is the concept of c++11 and onwards.

#include<iostream> 
using namespace std;

class Test
{
    /* Class data members */
    int x{10};
public:
    Test(Test&& t) { cout << "copy constructor called" << endl;
    x = 20;
    }
    Test() { cout << "constructor called" << endl; }
    void print() {
        cout << x << endl;
    }
};

Test fun()
{
    cout << "fun() Called\n";
    Test t;
    return t;
}

int main()
{
    Test t1;
    t1.print();
    Test t2 = fun();
    t2.print();
    return 0;
}

Output in Visual Studio 2019:

constructor called
10
fun() Called
constructor called
copy constructor called
20

Output in gcc c++17 compiler:

constructor called                                                                    
10                                                                                    
fun() Called                                                                          
constructor called                                                                    
10 

Why this difference is coming?

Why are std::allocator objects being inserted into my vector? [closed]

I have two vectors of A objects. I want to "Python zip" the vectors together pairwise, go through the pairs, create a B object out of each pair, and insert each new B object into a vector. Then I need to use the vector of B objects to create a C object.

I'm trying to use std::transform to accomplish this like so:

std::vector<B> zipped;
std::transform(first_vector_of_A_objects.begin(),
    first_vector_of_A_objects.end(),
    second_vector_of_A_objects.begin(),
    zipped.begin(),
    [&](const auto& a1, const auto& a2) {
        return B::create({a1, a2});
     });
C c = C::create(zipped);

My compiler throws an error telling me that zipped is of type std::vector<B, std::allocator<B> >&) and that I need a std::vector<B> to create a C object. This doesn't make any sense! I've gone over the C++ documentation and tried several variations on the above code, and I don't see how I'm getting these std::allocator objects. Why can't I use std::transform to populate my vector with B objects?

C++ Override [] operator for an Array class

I have an array class, containing Point objects, stored in an array. A point object is described by coordinates x, y. I'm trying to override the [] operator, but it's not working: array2[0] = point1; // Not working: no operator "=" matches this operand, operand types are Array = point

class Array
{
private:
    Point* m_data;
    int m_size;

public: 
    Array(); //default Constructor
    Array(int size); //argument constructor 
    Array(const Array &array); //copy constructor
    ~Array(); //destructor

    Array& operator = (const Array& source); // Assignment operator
    Point& operator[](int index); //class indexer for writing
    const Point& operator[] (int index) const; //class indexer for reading

    //Getter function
    int Size() const; //returns size 

    //Get element by index
    Point& GetElement(int i);

    void SetElement(const int index, const Point& element); //set element of array to a new point

    void Print(string msg);
};

//class indexer
Point& Array::operator [] (int index)
{
    return (index > m_size - 1) ? m_data[0] : m_data[index];
}


const Point& Array::operator [] (int index) const
{
    return (index > m_size - 1) ? m_data[0] : m_data[index];
}

int main()
{
  //instantiate an array of two elements size
    Array* array1 = new Array(2);
    Point point0(0, 0); //instantiate a point with coordinates x, y
    Point point1(1, 1); 
    array1->SetElement(0, point0); //set the first element of array1 to point0
    array1->SetElement(1, point1);
    Array* array2 = new Array(2);
    Point point2(2, 2); //instantiate a point with coordinates x, y
    Point point3(3, 3);
    array2->SetElement(0, point2); //set the first element of array1 to point2
    array2->SetElement(1, point3);
    array2[0] = point1;  // Not working: no operator "=" matches this operand, operand types are Array = point
  return 0;
}

I'm getting an error in my c++ program in which I have separated a class program into three parts (one .h and two .cpp files)

I have written a program to insert the first name, last name and the status of a user. I am getting no errors in my files but still I'm getting the wrong output. I'm writing my program using Visual Studio Code. Here's my code for my main.cpp file.

#include <iostream>
#include <string>
#include "user.h"

int main()
{
    User user;
    std::cin >> user;
    std::cout << user << std::endl;
}

Here's the code for my user.cpp file.

#include <iostream>
#include <string>
#include "user.h"

        int User::get_user_count()
        {
            return user_count;
        }
        std::string User::get_status()
        {
            return status;
        }
        void User::set_status(std::string status)
        {
            if (status == "Gold" || status == "Silver" || status == "Bronze")
            {
            this->status = status;
            }
            else
            {
                this->status = "No status";
            }     
        }
        User::User()
        {
            user_count++;
        }
        User::User(std::string first_name, std::string last_name, std::string status)
        {
            this->first_name = first_name;
            this->last_name = last_name;
            this->status = status;
            user_count++;
        }
        User::~User()
        {
            user_count--;
        }
        std::ostream& operator << (std::ostream& output, const User user);
        std::istream& operator >> (std::istream &input, User &user);

int User::user_count = 0;

std::ostream& operator << (std::ostream& output, const User user)
{
    output << "First name: " << user.first_name << "\nLast name: " << user.last_name << "\nStatus: " << user.status;
    return output;
}

std::istream& operator >> (std::istream &input, User &user)
{
    input >> user.first_name >> user.last_name;
    return input;
}

And lastly, Here's the code for my user.h file

#ifndef USER_H
#define USER_H

class User
{
        static int user_count;
        std::string status = "Gold";

        public:
        static int get_user_count();
        std::string first_name;
        std::string last_name;
        std::string get_status();
        void set_status(std::string status);
        User();
        User(std::string first_name, std::string last_name, std::string status);
        ~User();
        friend std::ostream& operator << (std::ostream& output, const User user);
        friend std::istream& operator >> (std::istream &input, User &user);
};
#endif

The output is coming "Gold" when I'm telling the program that it is "Silver". The first and the last name are coming correctly in the output of the program so please help me with my question.

Avoid rounding with std::setprecision [duplicate]

the following example

int main(int argc, const char * argv[]) {
    std::stringstream ss;
    ss << std::fixed << std::setprecision(5) << 4567.9000990;
    cout << ss.str() << endl;
}

And when I run it the output is:

4567.90010

I was expecting the output: 4567.90009

Is there any way to avoid rounding in this situation?

Thanks in advance

NO Idea, why the base string get return instead of Derived, is that becasue vector copied only base object from the dervied object? [duplicate]

NO Idea, why the base string get return instead of Derived, is that becasue vector copied only base object from the dervied object?

#include <vector>
#include <iostream>
using namespace std;
class Base
{
protected:
    int m_value{};
 
public:
    Base(int value)
        : m_value{ value }
    {
    }
 
    virtual const char* getName() const { return "Base"; }
    int getValue() const { return m_value; }
};
 
class Derived: public Base
{
public:
    Derived(int value)
        : Base{ value }
    {
    }
 
    virtual const char* getName() const { return "Derived"; }
};

int main()
{
    std::vector<Base> v{};
    v.push_back(Base{ 5 });
    v.push_back(Derived{ 6 });
 
        
    for (const auto& element : v)
        std::cout << "I am a " << element.getName() << " with value " << element.getValue() << '\n';
 
    return 0;
}

why in second output Base is get return from the getName() methods?

Is that because of vector is not a pointer type or reference?

I am a Base with value 5

I am a Base with value 6 ----> why it prints the Base?

How to pair 2D array and integer in the output of the function?

I'm struggling to create multi-variable output from a function: I want to return 2D array sites(16x15) and the integer number N.

I tried:

  1. std::make_tuple here
  2. std:make_pair here

My problem is that I probably do not know how to define a 2D array in the declaration of the function std::pair <int [][],int> correctly.

Piece of code named function.cpp:

#include <iostream>

std::pair <int[16][15],int> sites_diamond()
{
    int sites[16][15]={0};
    int N=0;
    for (int r=0; r<7; r++) {
        N=N+1+2*r;
        for (int c=0; c<(7-r);c++){
            sites[r][c]=0;
            sites[15-r][c]=0;
            sites[r][14-c]=0;
            sites[15-r][14-c]=0;
        }
    }
    N=2*(N+15);
    return std::make_pair(sites, N);
}

using namespace std;

int main(){
    std::pair <int[16][15], int> result = sites_diamond();
    cout << " sites \n"<<result.first<< endl;
    cout << "number \n"<<result.second<< endl;

    return 0;
}

Error I'm getting:

function.cpp: In function ‘std::pair<int [16][15], int> sites_diamond()’:
function.cpp:21:26: error: could not convert ‘std::make_pair<int (&)[16][15], int&>(sites, N)’ from ‘std::pair<int (*)[15], int>’ to ‘std::pair<int [16][15], int>’
     return std::make_pair(sites, N);

Thank you ahead for any suggestions. I work primarily in Python, but I want to rewrite a code to C++.

i have to print the detail of the recent Copter and Plane on the basis of their location from the input data of Aircraft [closed]

I have a problem calling my showDetail() function and print the details as of now? how can I avoid the segmentation fault? So that I can further solve the actual problem i/p:

1,copter,101,22.77

3,copter,103,22.50

2,plane,202,22.86

2,copter,102,22.22

3,plane,203,22.55

1,copter,101,22.89

1,plane,201,22.67

3,copter,103,22.60

3,plane,203,23.01

2,plane,202,22.81

1,plane,201,22.68

2,copter,102,22.11

o/p:

copter 1,copter,101,22.89

2,copter,102,22.11

3,copter,103,22.60

plane: 1,plane,201,22.68

2,plane,202,22.81

3,plane,203,23.01



#include <bits/stdc++.h>
using namespace std;
//defining an Abstract Class Aircraft
class Aircraft{
    //all members are set as protected so that they can be accessed by their child classes
    protected:
    int instanceId;                     //instance id showing which instance is that
    string aircraftType;                //type of aircraft either Copter or Plane
    int refrenceId;                     //refrence id for the Aircraft  
    float curLocation;                  //location will held in this variable of the Aircraft

    //all the functions & Constructor are ublic so that it can access the members of class
    public:
    //virtual keyword to implement the Abstract class (in c++)
    virtual void setAircraftType(string aircraftType)=0;
    //function to update the current Location of Aircraft
    void updateLocation(float loc)
    {
        this->curLocation=loc;
    }
    void showDetails()
    {
        cout<<this->instanceId<<", "<<this->refrenceId<<", "<<this->curLocation<<endl;
    }   
};
//1st Subclass of Base class Aircraft i.e. Copter  
class Copter:public Aircraft
{
    public:
    //overiding of virtual function
    void setAircraftType(string aircraftType){
        this->aircraftType=aircraftType;
    }
    
    Copter(int instanceId, string aircraftType, int refrenceId, float curLocation)
    {
        this->instanceId=instanceId;
        //setAircraftType("copter");
        this->aircraftType=aircraftType;
        this->refrenceId=refrenceId;
        this->curLocation=curLocation;
    }

};
//2nd Subclass of Aircraft i.e. Plane class
class Plane:public Aircraft
{
    public:
    //overiding of virtual function
    void setAircraftType(string aircraftType){
        this->aircraftType=aircraftType;
    }
    
    Plane(int instanceId, string aircraftType, int refrenceId, float curLocation)
    {
        this->instanceId=instanceId;
        //setAircraftType("plane");
        this->aircraftType=aircraftType;
        this->refrenceId=refrenceId;
        this->curLocation=curLocation;
    }

};
int main() {
    int n;
    cout<<"enter the number of record you want to input"<<endl;
    cin>>n;
    vector<Aircraft*> input_data(n);
    for(int i = 0; i < n; i++)
    {
        int instanceId;
        cout<<"Enter the Instance Id"<<endl;
        cin>>instanceId;
        cout<<"Enter the type of Aircraft"<<endl;
        string typeOfAircraft;
        cin>>typeOfAircraft;
        cout<<"Enter the refrence id of Aircraft"<<endl;
        int refId;
        cin>>refId;
        cout<<"Enter the current location of Aircraft";
        float curLocation;
        cin>>curLocation;
        if(typeOfAircraft == "copter")
        {
            input_data.push_back(new Copter(instanceId, typeOfAircraft, refId, curLocation));

        }
        else
        {
            input_data.push_back(new Plane(instanceId, typeOfAircraft, refId, curLocation));
        }
    }
    for(int i = 0; i < n; i++)
    {
        input_data[i]->showDetails();
        
    }
  
}```

Shared a concurrent queue

How should I instantiate my queue to be shared with all my object instances?

This is my concurrentQueue class

template <typename T>
class concurrentQueue
{
    public:
        concurrentQueue():data_cond(), mut(){};

        concurrentQueue(const concurrentQueue& other):data_cond(), mut(){
            std::lock_guard<std::mutex> lock(other.mut);
            data_queue = other.data_queue;
        };
        virtual ~concurrentQueue(){}; 
        concurrentQueue &operator=(const concurrentQueue &other) = delete;
    [...]

};

I was thinking of using the reference passage for my differents objects. For example

class consumer :
{
    public:
    consumer(const concurrentQueue<std::string>& queue) : myQueue(queue){};
    void execute(){ std::string s{""}; bool t = myQueue.try_and_pop(s); if (t) {std::cout << s << std::endl;}  };
    
};

class producer :
{
    public:
    producer(const concurrentQueue<std::string>& queue) : myQueue(queue){};
    void execute(){ std::string s=string_random(10); myQueue.push(s); std::cout << myQueue.size() << std::endl;  };
     [...]
    
};

int main()
{ 
    concurrentQueue<std::string> queue;
    producer A(std::ref(queue));
    producer A1(std::ref(queue));
    consumer B(std::ref(queue));
    A.execute();
    A1.execute();
    while(!queue.isEmpty)
     B.execute();
     
    exit
}

What is the best way?

What would a proper way to go, to get the "Copy & Swap Idiom" to work here?

MY Previous question:


In the code below, I need the variable auto ptr to remain valid and the assertion to pass.

   auto ptr = a.data();

Looks like this:

   +--------------+
   | a.local_data | --\
   +--------------+    \     +-------------+
                        >--> | "Some data" |
   +-----+             /     +-------------+
   | ptr | -----------/
   +-----+

#include <iostream>
#include <cassert>
using namespace std;

class Data 
{
private:
    char* local_data;
    int _size = 0;
    
    inline int length(const char* str)
    {
        int n = 0;
        while(str[++n] != '\0');
        return n;
    }
    
public:
    Data() {
        local_data = new char[_size];
    }
    
    Data(const char* cdata) : _size { length(cdata) }{
        local_data = new char[_size];
        std::copy(cdata, cdata + _size, local_data);
    }
    
    int size() const { return _size; }
    const char* data() const { return local_data; }
    
    void swap(Data& rhs) noexcept
    {
        std::swap(_size, rhs._size);
        std::swap(local_data, rhs.local_data);
    }
    
    Data& operator=(const Data& data)
    {
        Data tmp(data);
        swap(tmp);
        return *this;
    }
};



int main()
{
    Data a("Some data");
    auto ptr = a.data(); // Obtains a pointer to the original location
    a = Data("New data");
    assert(ptr == a.data()); // Fails
    return 0;
}

Why are functions returning references with prefix inc/dec operators are lvalue expressions but not with postfix inc/dec operators

Why functions that return lvalue references, along with prefix increment/decrement operators are lvalue expressions whereas, functions that return lvalue references along with postfix increment/decrement operators are not lvalue expressions ?

C++ Primer, Lippman et al. 5/e mentions :

Functions that return lvalue references, along with the assignment, subscript, dereference, and prefix increment/decrement operators, are all examples of expressions that return lvalues. We can bind an lvalue reference to the result of any of these expressions.

Functions that return a nonreference type, along with the arithmetic, relational, bitwise, and postfix increment/decrement operators, all yield rvalues. We cannot bind an lvalue reference to these expressions, but we can bind either an lvalue reference to const or an rvalue reference to such expressions.*

How's the Copy & Swap idiom really supposed to work, seriously! My code fails

I have been hearing about this, very advertised way of implementing an assign operator=() in C++.

Here's where it seems to fail,

A copy operator=() without Copy & Swap Idiom:

Data& operator=(const Data& rhs)
{
    if(this != &data)
    {
        _size = rhs.size();
        delete[] local_data;
        local_data = new char[_size];
        std::copy(rhs.data(), rhs.data() + rhs.size(), local_data);
    }
    return *this;
}
  1. Main.cpp with above (non-swap idiom) implementation called,

    int main(){
       Data a("Some data");
       auto ptr = a.data(); // Obtains a pointer to the original location
       a = Data("New data"); // When a is modified, this modification should effect the 'ptr'
       assert(ptr == a.data()); // Succeeds
       return 0;
     }
    

Same as above, except with Copy & Swap Idiom:

void swap(Data& rhs) noexcept
{
    std::swap(_size, rhs.size());
    std::swap(local_data, rhs.data());
}

Data& operator=(const Data& rhs)
{
    Data tmp(data);
    swap(data);
    return *this;
}

2: With swap idiom implementation:

int main(){
    Data a("Some data");
    auto ptr = a.data(); // Obtains a pointer to the original location
    a = Data("New data"); // When a is modified, this modification should effect the 'ptr' 
    assert(ptr == a.data()); // Fail
    return 0;
}

I observe, that there's clean up. But, is the clean and easy implementation of Copy & Swap Idiom supposed to fail here. And, I know that some runtime overhead does occur. But, generally, the Copy & Swap idiom seems a lot cleaner and better.

EDIT: I am aware of the self-assignment problem, and that this is supposed to help with that. Self-assignment is exceedingly rare in most programs, so an explicit check adds a small cost to every self-assignment even though the check is almost always false.

Sutter & Alexandrescu shows an assignment operator written in terms of a swap member. This is safe against self-assignment, exception-safe, and re-uses the copy constructor.

Qt/C++: What's the best way to call a method asynchronously in Qt event loop without having to write its name as string?

The normal way is with invokeMethod:

QMetaObject::invokeMethod(this, "methodName", Qt::QueuedConnection);

which works fine, except that I don't want to write methods in strings. Like ever. Why? Because this is a refactoring nightmare. Imagine having to change a method name for some reason. The software will malfunction and I'll have to notice in stderr that the method doesn't exist.

My solution?

I use QTimer. Like this:

QTimer::singleShot(0, this, &ClassName::methodName);

which seems to work fine. What I like about this is that you can replace the &ClassName::methodName part with a lambda/bind and it'll still be bound to the correct object (in case I need to use it with QThread) with the expected variable referencing we understand in standard C++:

QTimer::singleShot(0, threadObject, [this, param1, &param2](){ this->methodName(param1, param2); });

Better solutions exist?

But... I'm hoping there's a better way to do this because someone reading my code will not understand why I'm using a QTimer here... so I gotta comment everything.

Is there a better way to do this that's compatible with versions of Qt down to 5.9 or 5.7? What's the best solution you know?

lundi 28 décembre 2020

Proper way to facilitate MOVE operation when overriding operator on C++

I'm not really familiar with how move works in C++, and I need some help to clarify my understanding. I'm want to overload the operator+, and I'm have a couple of questions about it.


ap_n operator+(const ap_n& n, const ap_n& m) {
    ap_n tmp {n};
    return tmp += m;
}

My first question is how to make temporary objects movable. As shown in my function above, both arguments are not meant to be mutated, therefore I need to create a third object to do the operation upon.

How can I make my return value usable for move operation. Is the return value supposed to be a reference as ap_n&? Should the return object be encapsulated by std::move(tmp)? Or is it alright as is?

How does C++ decide when an object is rvalue, or decide that a move operation is suitable on an object, and how can I tell the program that an object is safe to use for move operation.


ap_n operator+(const ap_n&, const ap_n&); // defined as in first question
ap_n operator+(ap_n&& n, const ap_n& m) { return n += m; }
ap_n operator+(const ap_n& n, ap_n&& m) { return m += n; }
ap_n operator+(ap_n&& n, ap_n&& m) { return n += m; }

My second question is whether it is necessary to create variants of function that accept rvalue arguments. Right now I have 4 functions, as shown, to be able to accept normal objects and rvalue objects.

Is writing all the combinations possible like this necessary? If I remove all but the first function, would the program still be able to perform move operation correctly?

What's the meaning of "typename" in "typename Rigid2

    template <typename FloatType>
        
    class Rigid2 {
        
    using Vector = Eigen::Matrix<FloatType, 2, 1>;
        
     
        
    template <typename FloatType>
        
    Rigid2<FloatType> operator*(const Rigid2<FloatType>& lhs,
        
                                const Rigid2<FloatType>& rhs) {
        
      return Rigid2<FloatType>(
        
          lhs.rotation() * rhs.translation() + lhs.translation(),
        
          lhs.rotation() * rhs.rotation());
        
    }
        
     
        
    template <typename FloatType>
        
    typename Rigid2<FloatType>::Vector operator*( 
        
        const Rigid2<FloatType>& rigid,
        
        const typename Rigid2<FloatType>::Vector& point) {
        
      return rigid.rotation() * point + rigid.translation();
        
    }
}
        

What's the meaning of the typename in the sentence "typename Rigid2::Vector operator*". Does it to declare the operator* is the second time overloading?
If it does.We must use it to declare the function what overloads second time?

Question about std::function when using with static member function

Why both PassFxn(&X::StaticMemberDoIt); and PassFxn(std::bind(&X::StaticMemberDoIt, _1, _2, _3)); are right? Is there is an implicit conversion when invoking PassFxn(&X::StaticMemberDoIt); since the declaration is void PassFxn(std::function<int(float, std::string, std::string)> func) other than void PassFxn(int(*func)(float, std::string, std::string))?

What the differences between PassFxn(&X::StaticMemberDoIt); and PassFxn(X::StaticMemberDoIt);?

Here is the code snippet(https://coliru.stacked-crooked.com/a/f8a0e1bb60550958) for demo:

#include <functional>
#include <string>
#include <iostream>

void PassFxn(std::function<int(float, std::string, std::string)> func)
//           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
{
   int result = func(12, "a", "b"); // call using function object
   std::cout << result << std::endl;
}

struct X
{
    int MemberDoIt(float f, std::string s1, std::string s2)
    {
        std::cout << "Member: " << f << ", " << s1 << ", " << s2 << std::endl;
        return 0;
    }

    static int StaticMemberDoIt(float f, std::string s1, std::string s2)
    {
        std::cout << "Static: " << f << ", " << s1 << ", " << s2 << std::endl;
        return 0;
    }
};

int main()
{
    using namespace std::placeholders;

    X x;
    PassFxn(std::bind(&X::MemberDoIt, x, _1, _2, _3)); // Use a member function!

    // Or, if you have a *static* member function...
    //Why these four expression are all right?
    PassFxn(X::StaticMemberDoIt);
    
    PassFxn(&X::StaticMemberDoIt);
    
    PassFxn(std::bind(X::StaticMemberDoIt, _1, _2, _3));
    
    PassFxn(std::bind(&X::StaticMemberDoIt, _1, _2, _3)); 
    

    // ...and you can basically pass any callable object!
}

How to fix " Program terminated with signal SIGSEGV, Segmentation fault. " [duplicate]

I wrote a code to calculate long factorials which i ran to calculate 6000!, it worked the first time and gave me the result but again when i ran it to calculate 6000!,it gave me an error :

The code is :

#define MAX 9999
int multiply(int res[], int x, int res_size)
{
    int carry = 0;
    for (int i = 0; i < res_size; i++) {
        int prod = res[i] * x + carry;
        res[i] = prod % 10;
        carry = prod / 10;
    }
    while (carry != 0) {
        res[res_size] = carry % 10;
        carry /= 10;
        res_size++;
    }
    return res_size;
}

void extraLongFactorials(int n)
{
    int res[MAX];
    res[0] = 1;
    int res_size = 1;
    for (int i = 2; i <= n; i++) {
        res_size = multiply(res, i, res_size);
    }
    for (int i = res_size - 1; i >= 0; i--) {
        cout << res[i];
    }
}

The error message is :

Reading symbols from Solution...done.
[New LWP 70586]
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Core was generated by `            '.
Program terminated with signal SIGSEGV, Segmentation fault.
#0  0x0000000000401340 in multiply (res_size=10644, x=<optimized out>, 
    res=<optimized out>) at Solution.cpp:15
15          res[res_size] = carry%10;
To enable execution of this file add
    add-auto-load-safe-path /usr/local/lib64/libstdc++.so.6.0.25-gdb.py
line to your configuration file "//.gdbinit".
To completely disable this security protection add
    set auto-load safe-path /
line to your configuration file "//.gdbinit".
For more information about this security protection see the
"Auto-loading safe path" section in the GDB manual.  E.g., run from the shell:
    info "(gdb)Auto-loading safe path"

How to send HTTP header and HTTP body separately using socket?

I can send both header and body this way,

std::string complete_response = "HTTP/1.1 200 OK\r\nContent-Length: 13\r\nConnection: close\r\n\r\nHello, world!";

socket.send(complete_response);

But I'm lost when it comes to sending them at separate stages. I've attempted the following and it doesn't seem working at all,

std::string header = "HTTP/1.1 200 OK\r\nContent-Length: 13\r\nConnection: close\r\n\r\n";
std:string body =  "Hello, world!";

socket.send(header);
socket.send(body);

Using Wireshark, I see that the browser get the header part then browser close the connection and not wait for the body.

why am I getting free(): invalid pointer error after program ends

Can somebody explain why I'm getting this error after program ends?

free(): invalid pointer

This is my code:

#include <iostream>
#include <memory>

int main()
{
    int a = 3;
    std::unique_ptr<int> up(&a);
    
    std::cout << a << std::endl;
    std::cout << *up << std::endl;
    
    std::cout << &a << std::endl;
    std::cout << up.get() << std::endl;
    
    return 0;
}

difference between std::move and std::add_rvalue_reference

Can somebody explain the difference between std::move and std::add_rvalue_reference. Does both serve the same purpose? If yes advantage of one over the other.

queue entries of threadpool in C++

I am trying to implement a thredpool, and I found that there are two implementations. They are all using queue to manage tasks, but the entries of queue are different. I want to konw which is more better and the rational of the implementations. Why the second version need a function_wrapper.

First version use std::queue<std::packaged_task<void()> > tasks;

class ThreadPool {
 public:
  explicit ThreadPool(size_t);
  template <class F, class... Args>
  decltype(auto) enqueue(F&& f, Args&&... args);
  ~ThreadPool();

 private:
  // need to keep track of threads so we can join them
  std::vector<std::thread> workers;
  // the task queue
  std::queue<std::packaged_task<void()> > tasks;

  // synchronization
  std::mutex queue_mutex;
  std::condition_variable condition;
  bool stop;
};

// add new work item to the pool
template <class F, class... Args>
decltype(auto) ThreadPool::enqueue(F&& f, Args&&... args) {
  using return_type = decltype(f(args...));

  std::packaged_task<return_type()> task(
      std::bind(std::forward<F>(f), std::forward<Args>(args)...));

  std::future<return_type> res = task.get_future();
  {
    std::unique_lock<std::mutex> lock(queue_mutex);

    // don't allow enqueueing after stopping the pool
    if (stop) throw std::runtime_error("enqueue on stopped ThreadPool");

    tasks.emplace(std::move(task));
  }
  condition.notify_one();
  return res;
}

Second version use thread_safe_queue<function_wrapper> work_queue;

class function_wrapper {
  struct impl_base {
    virtual void call() = 0;
    virtual ~impl_base() {}
  };
  std::unique_ptr<impl_base> impl;
  template <typename F>
  struct impl_type : impl_base {
    F f;
    impl_type(F&& f_) : f(std::move(f_)) {}
    void call() { f(); }
  };

 public:
  template <typename F>
  function_wrapper(F&& f) : impl(new impl_type<F>(std::move(f))) {}
  void operator()() { impl->call(); }
  function_wrapper() = default;
  function_wrapper(function_wrapper&& other) : impl(std::move(other.impl)) {}
  function_wrapper& operator=(function_wrapper&& other) {
    impl = std::move(other.impl);
    return *this;
  }
  function_wrapper(const function_wrapper&) = delete;
  function_wrapper(function_wrapper&) = delete;
  function_wrapper& operator=(const function_wrapper&) = delete;
};

class thread_pool {
  thread_safe_queue<function_wrapper> work_queue;
  void worker_thread() {
    while (!done) {
      function_wrapper task;
      if (work_queue.try_pop(task)) {
        task();
      } else {
        std::this_thread::yield();
      }
    }
  }

 public:
  template <typename FunctionType>
  std::future<typename std::result_of<FunctionType()>::type> submit(
      FunctionType f) {
    typedef typename std::result_of<FunctionType()>::type result_type;
    std::packaged_task<result_type()> task(std::move(f));
    std::future<result_type> res(task.get_future());
    work_queue.push(std::move(task));
    return res;
  }
}

DP based algo for Stock maximize problem Hackerank

i need some help solving Stock maximize problem on hackerrank the problem is at this link https://www.hackerrank.com/challenges/stockmax/problem I know there's a linear approach to solve this problem but i needed help with Dynamic Programming involving solution of mine.. It gives TLE when i submit it.. As a learner i just want to know is there any further optimization i can do to my DP based solution. I wrote the following function to evaluate answer

long myans(vector<int> prices, unordered_map<int,unordered_map<int, long>> &mp ,int st,long ns,long pr)
{
   //base
   if(st==prices.size())
   return pr;
   //dp
   if( mp[ns][st]!=0)
   return  mp[ns][st];
   //rec
   long dn=0,ss=0,bs=0;
   if(st!=prices.size()-1)
   bs=myans(prices,mp,st+1,ns+1,pr-prices[st]);
   if(ns>0)
   ss=myans(prices,mp,st+1,0,pr+ns*prices[st]);
   dn=myans(prices,mp,st+1,ns,pr);
   mp[ns][st]=max(bs,max(ss,dn));
   // mp[st+1][ns+1]=bs;
   // mp[st+1][ns]=dn;
   // mp[st+1][0]=ss;
    return mp[ns][st];
   //return  mp[make_pair(ns,prices[st])];
}
long stockmax(vector<int> prices) {
unordered_map<int,unordered_map<int, long>> mp;
   return myans(prices,mp,0,0,0);

}

Compiler Error in C++: ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) [duplicate]

I tried to write the code to manage a search binary tree, but why the compiler gives me the following error?

Undefined symbols for architecture x86_64: "ABR::printASCIITree()", referenced from: _main in ABRMain-4a2894.o "Node::Node(int)", referenced from: _main in ABRMain-4a2894.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)

this is the code:

ABRMain.cpp:

#include <iostream>
#include "ABR.hpp"

using namespace std;

int main(){
    ABR<int> *tree = new ABR<int>(new Node<int>(5));

    tree->printASCIITree();
}

Node.hpp:

#include <iostream>

template <typename T>
class Node{
    private:
        T key;
        Node<T> *parent;
        Node<T> *right;
        Node<T> *left;
    public:
        Node();
        Node(T);

        T getKey();
        void setKey(T);

        void setParent(T*);
        T *getParent();

        void setRight(T*);
        T *getRight();

        void setLeft(T*);
        T *getLeft();
};

Node.cpp:

#include "Node.hpp"

using namespace std;

template <typename T>
Node<T>::Node(){
    parent = nullptr;
    right = nullptr;
    left = nullptr;
}

template <typename T>
Node<T>::Node(T k){
    key = k;
    parent = nullptr;
    right = nullptr;
    left = nullptr;
}

template <typename T>
T Node<T>::getKey(){
    return key;
}

template <typename T>
void Node<T>::setKey(T k){
    key = k;
}

template <typename T>
void Node<T>::setParent(T *f){
    parent = f;
}

template <typename T>
T *Node<T>::getParent(){
    return parent;
}

template <typename T>
void Node<T>::setRight(T *r){
    right = r;
}

template <typename T>
T Node<T>::*getRight(){
    return right;
}

template <typename T>
T Node<T>::*setLeft(T *l){
    left = l;
}

template <typename T>
T Node<T>::*getLeft(){
    return left;
}

ABR.hpp:

#include <iostream>
#include "Node.hpp"

using namespace std;

template <typename T>
class ABR{
    private:
        Node<T> *root;
        void transplant(Node<T> *, Node<T> *);
    public:
        ABR():root(nullptr){}
        ABR(Node<T> *r):root(r){}

        Node<T> *search(T);
        Node<T> *search(Node<T> *, T);

        Node<T> *minimum();
        Node<T> *minimum(Node<T> *);

        Node<T> *maximum();
        Node<T> *maximum(Node<T> *);

        void insert(T);

        Node<T> *successor(Node<T> *);
        Node<T> *predecessor(Node<T> *);
        void deleteNode(Node<T> *);

        void printASCIITree();
        void printASCIITree(Node<T> *, int);
};

ABR.cpp:

#include "ABR.hpp"

using namespace std;

template <typename T>
Node<T> *ABR<T>::search(T key){
    return search(root, key);
}

template <typename T>
Node<T> *ABR<T>::search(Node<T> *node, T key){
    if(node == nullptr || node->getKey() == key) return node;

    if(node->getKey() > key) 
        return search(node->getRight(), key);
    else 
        return search(node->getLeft(), key);
}

template <typename T>
Node<T> *ABR<T>::minimum(){
    return minimum(root);
}

template <typename T>
Node<T> *ABR<T>::minimum(Node<T> *node){
    if(node->getLeft() == nullptr) return node;

    minimum(node->getLeft());
}

template <typename T>
Node<T> *ABR<T>::maximum(){
    return maximum(root);
}

template <typename T>
Node<T> *ABR<T>::maximum(Node<T> *node){
    if(node->getRight() == nullptr) return node;

    minimum(node->getRight());
}

template <typename T>
void ABR<T>::insert(T key){
    Node<T> *y = nullptr;
    Node<T> *pt = root;

    while(pt != nullptr){
        y = pt;
        if(pt->getKey() < key)
            pt = pt->getLeft();
        else
            pt = pt->getRight();
    }

    Node<T> *z = new Node<T>(key);
    z->setFather(y);
    if(y == nullptr)
        root = z;
    else if(z->getKey() < y->getKey())
        y->setLeft(z);
    else
        y->setRight(z);
}

template <typename T>
Node<T> ABR<T>::*successor(Node<T> *node){

    if(node->getRight() != nullptr)
        return minimum(node->getRight());

    Node<T> *pt = node->getParent();

    while(pt != nullptr && node == pt->getRight()){
        node = pt;
        pt = pt->getParent();
    }

    return pt;
}

template <typename T>
Node<T> ABR<T>::*predeecessor(Node<T> *node){

    if(node->getLeft() != nullptr)
        return maximum(node->getLeft());

    Node<T> *pt = node->getParent();

    while(pt != nullptr && node == pt->getLeft()){
        node = pt;
        pt = pt->getParent();
    }

    return pt;
}

template <typename T>
void ABR<T>::deleteNode(Node<T> *node){

    if(node->getLeft() == nullptr){
        transplant(node, node->getRight());
    }else if(node->getRight() == nullptr){
        transplant(node, node->getLeft());
    }else{
        Node<T> y = minimum(node->getRight());
        if(y->getParent() != node){
            transplant(y, y->getRight());
            y->setRight(node->getRight());
            node->getRight()->setParent(y);
        }
        transplant(node, y);
        y->setLeft(node->getLeft());
        y->getLeft()->setParent(y);
    }
    
}

template <typename T>
void ABR<T>::transplant(Node<T> *u, Node<T> *v){

    if(u->getParent() == nullptr){
        root = v;
    }

    else if(u == u->getParent()->getLeft()){
        u->getParent()->setLeft(v);
    }

    else if(u == u->getParent()->getRight()){
        u->getParent()->setRight(v);
    }

    if(v != nullptr){
        v->setFather(u->getParent());
    }
}

template <typename T>
void ABR<T>::printASCIITree(){
    printASCIITree(root, 0);
}

template <typename T>
void ABR<T>::printASCIITree(Node<T> *node, int level){
    if(node == nullptr) return;

    for(int j=0; j<level; j++){
        cout << "|";
        if(j == level-1)
            cout << "-";
    }

    cout << node->getKey() << endl;

    printASCIITree(node->getLeft(), level+1);
    printASCIITree(node->getRight(), level+1);
}

Thanks in advance.

Is polymorphism the best way to achieve this? (regarding function calls in derived classes)

I have a program that has four classes:

  • Vehicle (Base)
  • Automobile (Derived from Vehicle)
  • Car (Derived from Automobile)
  • Truck (Derived from Automobile)

At run-time, the user generates a Automobile object which is either a "Car" or "Truck" using a factory function:

Automobile *Automobile::make_automobile(std::string choice) {
    if (choice == "car")
        return new Car;
    else if (choice == "truck")
        return new Truck;
    else
        return nullptr;
}

Now, the "Car" class has three unique setters (and three matching getters):

  • Set_NumDoors()
  • Set_SeatMaterial()
  • Set_Shape()

The "Truck" class has one unique setter (and a matching getter):

  • Set_CargoWeight()

At first, these functions were only implemented in their own classes, but I could not call them at run-time since the object created was an "Automobile" object. I have solved this issue using virtual functions with local overrides. So now, the "Automobile" class all four functions (in virtual form), which by default do nothing. However, when called on an object, the local override performs the correct functionality. Below is an example, and it all works.

Definition in Automobile class

std::string defaultStatement = "Function call is invalid on current object";
    virtual int set_seatMaterial(std::string choice){
        std::cout << defaultStatement << std::endl;
        return -1;
    }

Override in Car class

    int set_seatMaterial(std::string choice) override { // override virtual base
        if (choice == "leather" || choice == "cloth"){
            seatMaterial = choice;
            return 0;
        }
        else
            return -1;
    }

I then use function pointers in main() to point to the required function as appropriate:

if (user_choice == "seat"){
            std::function<int(Automobile*, std::string)> choiceFunction = &Automobile::set_seatMaterial;
            choiceFunction(userVehicle, seatMaterial);
}

The only question I have is - is this the best way of achieving this functionality? It works but now I have declarations of every single function in the "Automobile" class, which already has its own getters/setters. It seems like duplication in a sense, although I understand the concept of polymorphism and its usefulness.

Or is there a better way to call a derived class function from a base class object?

Move operator destroying original pointer

I am trying to have a pointer to a memory location. Then, if I modify the original the assigned variable who points to the same location must be also affected by the change.

But, the thing is, there are two function calls, that happen on line:

a = Data("New data");
  1. Data(const char* cdata) constructor is called.
  2. Data operator=(Data&& data) move operator is called.

My C++ code:

class Data 
{
private:
    char* local_data;
    int _size = 0;
public:
    Data() {
        local_data = new char[_size];
    }
    
    Data(const char* cdata){
        local_data = new char[_size];
        memcpy(local_data, cdata, _size);
    }
    
    int size() { return _size; }
    char* data() { return local_data; }
    const char* data() const { return local_data; }
    
    Data& operator=(const Data& data){}
    Data& operator=(Data&& data){
        
        if(this == &data)
            return *this;
        
        _size = std::move(data.size());
        local_data = std::move(data.data());
        return *this;
    }
};

int main(){
    
    Data a("Some data");
    auto dptr = a.data(); // Gives a pointer to the original location
    a = Data("New data"); // Must modify both a and dptr
    assert(dptr == a.data()); // Should pass successfully, else fail
    return 0;
}

Error C2440 '

I am trying to iterate over an std::tuple and retrieve the true amount of space (bytes) it takes up. To handle std::string I need to use the .length() function but I am unable to compile, and I get the following error:

Error C2440 '': cannot convert from 'char' to 'std::string'

I have also tried using std::is_same (as commented) but without success. The function iterate_tuple_types is called like so:

tuple <char, unsigned int, double, std::string> src;
src = make_tuple('a', 10, 0.333333333333333, std::string("some string"));
iterate_tuple_types(src);

Code

template <typename T, typename S>
struct is_string {
    static const bool value = false;
};

template <class T, class Traits, class Alloc>
struct is_string<T, std::basic_string<T, Traits, Alloc> > {
    static const bool value = true;
};

template<int N, typename... Ts> using NthTypeOf =
    typename std::tuple_element<N, std::tuple<Ts...>>::type;

template <size_t I = 0, typename... Ts>
typename std::enable_if<I == sizeof...(Ts), size_t>::type
    iterate_tuple_types(std::tuple<Ts...> tup) {
    return 0;
}

template <size_t I = 0, typename... Ts>
typename  std::enable_if<(I < sizeof...(Ts)), size_t>::type
    iterate_tuple_types(std::tuple<Ts...> tup) {
    size_t result = 0;
    // std::is_same<std::string, NthTypeOf<I, Ts...> >::value
    if (std::is_integral<NthTypeOf<I, Ts...> >::value) {
        result += sizeof(NthTypeOf<I, Ts...>);
    }
    else if (is_string<std::string, NthTypeOf<I, Ts...> >::value) {
        result += static_cast<size_t>(std::string(std::get<I>(tup)).length());
    }
    return result + iterate_tuple_types<I + 1>(tup);
}

Am I going about this correctly? Why does the error occur?

How and when to use if(!(cin>>x)) mean?

How and when to use if(!(cin>>x)) and what does it mean and in how many ways it can be used in a code

Error to implementation of strategy pattern in C++

I'm trying to implement the design pattern strategy in C++. The goal for me is to do an operation on 2 numbers.

Here is my context class

  operation::operation(std::unique_ptr<calculatorTask> pTask = nullptr)
{
    pCalculatorTask = std::move(pTask);
}

operation::~operation();
{
}

void operation::setTask(std::unique_ptr<calculatorTask> pTask)
{
    this->pCalculatorTask = std::move(pTask);
}

void operation::executeTask(numberMsg& sValues)
{
    pCalculatorTask->calculate(values);
}

This is my implementation :

int main()
{
   std::vector<std::unique_ptr<calculatorTask>> myOperation;
   myOperation.push_back(std::move(std::unique_ptr<additionTask>(new additionTask())));
   myOperation.push_back(std::move(std::unique_ptr<substractionTask>(new substractionTask())));
   for (const auto &Ope : myOperation)
    {
        pOpe->setTask(Ope);
        [...]
    }
}

I have this error :

error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = calculatorTask; _Dp = std::default_delete]’ pOpe->setTask(Ope);

I don't understand error and how to fix it.

The step clause of this for-loop is not of the expected form

for(auto Itr = PropVal.value.int32Values.begin();Itr != PropVal.value.int32Values.end();Itr++)

The step clause of this for-loop is not of the expected form. It must be an expression whose only persistent side effect is to modify the loop counter. The loop counter has been identified as <cs.ast [cc:variable] Itr>.

what is the alternative way?

f(123) = 1! + 2! + 3! .I wrote a code for this type of function to work, have a look at it. My code is not giving desired result

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    int a=123,c,h=0,fact=1,sum=0;

    for(int i=1;a>10;i++)
    {
        a/=pow(10,i);
        h++;
    }
    for(h;h>=0;h--)
    {
        c=a/pow(10,h);
        for(int j=1;j<=c;j++)
        {
            fact*=j;
        }
        sum+=fact;
        a-=(c*pow(10,h));
    }
    cout<<sum;
}

While using debugger I noticed that the line

c=a/pow(10,h);

is not working.

Here I have assigned a=123, but I want take it as input from the user. The variable a can be of any number of digits.

Can anyone suggest some other logic other than the one used in this code.

Understanding "Expression does not compute the number of elements in this array"

Using Apple Clang 12.0.0 to compile this code:

int my_array[10];
int arr_size = sizeof(my_array) / sizeof(decltype(my_array[0]))

And getting this warning/error:

Expression does not compute the number of elements in this array; element type is 'int', not 'decltype(my_array[0])' (aka 'int &')

Note, this is simplified code. In the real code instead of 'int' there's a class type, instead of '10' there's an expression.

Why am I getting this warning, and what is the correct way to calculate the array size without warnings?

Why does this SFINAE not work with enable_if even when the substitution fails?

template <typename Types>
class C {
using A = typename Types::A;
using B = typename Types::B;

template <typename Dummy = void>
inline typename std::enable_if<std::is_same<A, B>::value, Dummy>::type f(vector<int>& ctx, const string& r) { }
};

When I try to compile the above code when A and B are not same, I get the following error:

test.h:153:12: note:   template argument deduction/substitution failed:
test.h:153:12: error: no type named ‘type’ in ‘struct std::enable_if<false, void>’

Note that the code I have presented is not the exact code I use and the variable and function names have been altered to protect secrecy

dimanche 27 décembre 2020

New can give exceptions other than bad_alloc

https://timsong-cpp.github.io/cppwp/n4618/diff.cpp03.language.support 18.6.1.1 Change: operator new may throw exceptions other than std::bad_alloc

Rationale: Consistent application of noexcept.

Effect on original feature: Valid C++ 2003 code that assumes that global operator new only throws std::bad_alloc may execute differently in this International Standard.

Acc. to given clause what there can be other exceptions other than std::bad_alloc, Any idea what are these exceptions?

C++ primer 5th ed. class template specialization. an example case: specializing std::hash

In c++ primer 5th ed. class template specialization I have this example:

Because hash<Sales_data> uses the private members of Sales_data, we must make this class a friend of Sales_data:

template <class T> class std::hash;  // needed for the friend declaration
class Sales_data {
    friend class std::hash<Sales_data>;
    // other members as before
};

The code doesn't compile and complains:

error: invalid use of template-name ‘std::hash’ without an argument list
note: class template argument deduction is only available with ‘-std=c++17’ or ‘std=gnu++17’

I am compiling against C++11 because the book is old so that it doesn't support c++17 and 20.

If I comment out that declaration the code works fine but I am not sure whether doing so is OK and how to fix that problem.

I've tried this and worked but I am not sure whether I am doing the right thing:

   class Sales_data; // forward declaration
   template <>
   class std::hash<Sales_data>; // specialization declaration

What types of compiler optimizations are comonly used in C++? [closed]

I am trying to get high lever overview of optimizations used in C++ language. According to wikipedia article, compilers use these optimizations:

  1. Peephole optimizations
  2. Local optimizations
  3. Global optimizations
  4. Loop optimizations
  5. Prescient store optimizations
  6. Interprocedural, whole-program or link-time optimization
  7. Machine code optimization and object code optimizer

It it completely new topic for me. Till now I was thinking that optimization is only done during compilation. I didn't expect that is also done during linking or even after...

Could you tell me if C++ language supports all of mentioned optimizations?

EDIT: That's right, mentioned wiki article was not language specific, so purpose of that question was to get knowledge if these optimizations are commonly used and supported by C++ compilers.

There is a lot of detailed manuals which describes each compiler flag, but none of them provides general overview similar to mentioned wiki article, which will be C++ specific.

Why is function parameter always an lvalue?

I could not wrap my mind around the following statement from Scott Meyer's Effective Modern C++...

it's especially important to bear in mind that a parameter is always an lvalue, even if its type is an rvalue reference. That is given

void f(Widget&& w);

the paramter w is an lvalue, event it s type is rvalue-reference-to-widget.

How come a parameter w is an lvalue, but its type is rvalue-reference-to-widget? When people say w is an lvalue, doesnt that mean that its type is a lvalue type? I am probably missing something.

EDIT: Mant thanks to those who commented...I am still a bit confusing. I guess I dont fully understand the definition of these concept involved. What are lvalue, rvalue, lvalue reference, rvalue reference? Are these part of the context free grammar of the c++ language? Do these have anything to with code generation? Can I think of type and value category two separate production rules in the c++ context free grammar? What do they mean?

Boost signals2 and std::shared_ptr?

Is it possible to configure (at compile time) boost::signals2 to use std::shared_ptr instead of boost::shared_ptr, for e.g. in calls like boost::signals2::deconstruct?

Why I am able to modify using constant range based loop?

#include <iostream>
#include <map>

using namespace std;

int main()
{
    int number = 10;
    map<int*, int> intmap;
    intmap.insert(pair<int*, int>(&number, 1));
    
    for (auto const &  x : intmap)
    {
        (*x.first)++;
        
    }

    for (auto const &  x : intmap)
    {
        cout << (*x.first) << "::" << x.second; //prints 11::1
    }
    return 0;
}

In this answer its mentioned that

Choose auto const &x when you want to work with original items and will not modify them.

but in the above program, I am able to modify it. Looks like the x in for loop is constant pointer rather than a pointer to constant.

C++ error: invalid suffix '.d' on floating constant

Hello I have the following declared arrays in C++:

int arr[5] = {1,2,3,4,0};
float arr2[10] = {1.2f,0.0f,2.0f,1.4f,0.0f,4.2f,5.3f,0.0f,0.0f,0.0f};
double arr3[6] = {0.0d,0.0d,5.3d,0.0d,0.0d,0.5d};

When I compile this code the compiler returns the following error:

error: invalid suffix '.d' on floating constant

I tried compiling using the flag -std=c++11 to try and see if it worked on C++ 11 but I get the same error. Can someone tell me where the error is? Thank you :)

how to end a loop at a particular time in unordered_multiset

Good morning,

I am trying for a loop when a particular condition is met in an unordered_multiset with the end operation. But it does not work and I get a Segmentation fault in the next iteration of the loop.

Code:

std::unordered_multiset<Element, ElementHash>::iterator itr;
Element elementTemp1("");
for (itr = almacen.begin(); itr != almacen.end(); ++itr) {
    Element tmp(*itr);
    if(tmp.getNombre() == "prueba"){
       itr = almacen.end();
    }
}

How can I solve it? Or maybe my structure is not the right one.

samedi 26 décembre 2020

what is traceable pointer in c++?

Trying to understand clause 20 in ISO Standard c++: Change: Minimal support for garbage-collected regions. Rationale: Required by new feature. Effect on original feature: Valid C++ 2003 code, compiled without traceable pointer support, that interacts with newer C++ code using regions declared reachable may have different runtime behavior.

https://timsong-cpp.github.io/cppwp/n4618/diff.cpp03.utilities

What is traceable pointer(not traceable pointer object). What can be the difference btw traceable pointer and normal pointer?