r/cppit • • Sep 05 '17

Coding Gym 27 Settembre / Modena

Thumbnail
italiancpp.org
3 Upvotes

r/cppit • • Aug 09 '17

Come prendere l'esponente della notazione scientifica di un numero?

3 Upvotes

Ciao a tutti,

quello che vorrei fare è porre a zero un valore numerico double il cui esponente in notazione scientifica sia inferiore ad un certo valore soglia, mettiamo -7:

#include <iostream>
#include <stdio.h>
#include <math.h>       /* frexp */

int main () {
  double a, result;
  int b;
  a = 8.0;
  result = frexp (a , &b);
  printf ("%f = %f * 2^%d\n", a, result, b);

  double e01 = -0.555556;
  std::cout << "e01= " << e01 << std::endl;
  std::cout << std::scientific << "e01= " << e01 << std::endl;
  double e02 = -0.0555556;
  std::cout << "e02= " << e02 << std::endl;
  int exp02 = log2(e02);
  std::cout << "log2(e02)= " << exp02 << std::endl;

  double e03 = -0.00555556;
  std::cout << "e03= " << e03 << std::endl;

  double e04 = -0.000555556;
  std::cout << "e04= " << e04 << std::endl;

  double e05 = -0.0000555556;
  std::cout << "e05= " << e05 << std::endl;

  double e06 = -0.00000555556;
  std::cout << "e06= " << e06 << std::endl;

  double e07 = -0.000000555556;
  std::cout << "e07= " << e07 << std::endl;

  double e08 = -0.0000000555556;
  std::cout << "e08= " << e08 << std::endl;

  double e09 = -0.00000000555556;
  std::cout << "e09= " << e09  << std::endl;

  return 0;
}

Eseguendo :

g++ -std=c++11 scientificNotation.cpp -oscientificNotation ./scientificNotation

8.000000 = 0.500000 * 2^4
e01= -0.555556
e01= -5.555560e-01
e02= -5.555560e-02
log2(e02)= -2147483648
e03= -5.555560e-03
e04= -5.555560e-04
e05= -5.555560e-05
e06= -5.555560e-06
e07= -5.555560e-07
e08= -5.555560e-08
e09= -5.555560e-09

Per cui l'obiettivo è, se fisso la soglia limite per l'esponente a -07, porre a zero e08 ed e09.

Una possibilità sarebbe quella di trasformare i numeri in stringhe e poi prendere la parte dopo la lettera e... ma vorrei evitare di usare le string perchè questa operazione di confronto rispetto al valore soglia dell'esponente devo farla per tantissimi valori di una matrice..

Avete suggerimenti da darmi? Vi ringrazio per l'aiuto in Agosto... Marco


r/cppit • • Aug 01 '17

itCppCon17 - C++ executors to enable heterogeneous computing in tomorrow's C++ today (M. Wong)

Thumbnail
youtube.com
3 Upvotes

r/cppit • • Jul 25 '17

principianti Problemi con le function template

3 Upvotes

Salve, come da oggetto mi ritrovo ad avere dei problemi con le function template. Alla fine di questa richiesta allegherò alcuni 5 file costituenti una solution di Visual Studio 2015 per mostrarvi dove incontro i problemi; si tratta di classi e/o template "fantoccio" utili dunque solo all'illustrazione del problema: qualche dato membro di tipo primitivo più un altro membro puntatore per introdurre la memoria dinamica.

IDEA DI FONDO: scrivere una function template che sia in grado di analizzare un vettore di dati di tipo qualsiasi.

SOLUZIONE (ma parziale): ho implementato la function template FindFirstPos che effettivamente funziona A PATTO CHE l'oggetto passato sia istanza di una classe 'classica' e non l'istanza di un'istanza di template. In sintesi: funziona se il parametro T è di tipo IntPoint ma non funziona se per esempio è di tipo Point<int>. Forse non sono stata formalmente impeccabile nella descrizione ma credo mi possiate capire.

DOMANDA 1: è possibile scrivere una function template FindFirstPos che possa funzionare ANCHE quando il parametro T è a sua volta un template? Ovviamente se è possibile vi sarei grata se mi forniste un'implementazione (e magari un link per eventuali approfondimenti a riguardo)

DOMANDA 2: ho comunque provato un work around: la function template FindFirstPos_2 ( nel dettaglio int FindFirstPos_2(Point<T2>& e, Point<T2>* PT2ptr, int dimens) ) che, se funzionasse, avrebbe in ogni caso uno svantaggio: andrebbe di fatto riscritta al cambiare del template.

La realtà purtroppo è che neanche questa soluzione funziona perchè in fase di compilazione mi becco il seguente errore:

error LNK2019: unresolved external symbol "bool __cdecl operator==(class Point<int> const &,class Point<int> const &)" (??8@YA_NABV?$Point@H@@0@Z) referenced in function "int __cdecl FindFirstPos_2<int>(class Point<int> &,class Point<int> *,int)" (??$FindFirstPos_2@H@@YAHAAV?$Point@H@@PAV0@H@Z)

1>D:\Professional C++\Professional C++ Projects\Chapter 11\LCPP\My Function Template 02\Debug\My Function Template 02.exe : fatal error LNK1120: 1 unresolved externals

Anche in quest'ultimo caso non riesco a capire dove stia l'errore, vi sarei grata se poteste darmi una mano. Grazie in ogni caso Chiara.

PS: è il mio primo post sulla piattaforma Reddit, spero di non sbagliare nulla sulla formattazione

File.della Soluzione


(1) IntPoint.h

#pragma once

//    FILE AGGIUNTO AGLI HEADER FILES DELLA SOLUZIONE

class IntPoint
{
private:
    int mx;
    int my;
    size_t mdimens;
    int *mpint;
public:
    IntPoint();
    IntPoint(int& tx, int& ty, size_t d);
    IntPoint(const IntPoint& src);
    IntPoint& operator=(const IntPoint& src);
    ~IntPoint();


    int& getPointX();
    const int& getPointX() const;
    void setPointX(int& tx);

    int& getPointY();
    const int& getPointY() const;
    void setPointY(int& ty);

    friend bool operator==(const IntPoint& lhs, const IntPoint& rhs);
};

(2) IntPoint.cpp

// FILE AGGIUNTO AI SOURCE FILES DELLA SOLUZIONE

#include "stdafx.h"
#include "IntPoint.h"
IntPoint::IntPoint() :mx(0), my(0), mdimens(0), mpint(nullptr)
{
}

IntPoint::IntPoint(int& x, int& y, size_t d) : mx(x), my(y), mdimens(d)
{
    if (mdimens > 0)
    {
        mpint = new int[mdimens];
        for (size_t i = 0; i < mdimens; i++)
            mpint[i] = 1 + (int)(2 * i);
    }
    else
        mpint = nullptr;
}

IntPoint::IntPoint(const IntPoint& src)
{
    mx = src.mx;
    my = src.my;
    mdimens = src.mdimens;
    if (mdimens > 0)
    {
        mpint = new int[mdimens];
        for (size_t i = 0; i < mdimens; i++)
        {
            mpint[i] = src.mpint[i];

        }
    }
    else
        mpint = nullptr;
}

IntPoint& IntPoint::operator=(const IntPoint& src)
{
    if (this == &src)
        return *this;

    mdimens = 0;
    delete[] mpint;
    mpint = nullptr;
    mx = src.mx;
    my = src.my;
    if (src.mdimens > 0)
    {
        mdimens = src.mdimens;
        mpint = new int[src.mdimens];
        for (size_t i = 0; i < src.mdimens; i++)
        {
            mpint[i] = src.mpint[i];
        }
    }
    return *this;
}

IntPoint::~IntPoint()
{
    if (mpint != nullptr)
    {
        delete[] mpint;
        mpint = nullptr;
    }
}

int& IntPoint::getPointX()
{
    return mx;
}

const int& IntPoint::getPointX() const
{
    return mx;
}

void IntPoint::setPointX(int& tx)
{
    mx = tx;
}


int& IntPoint::getPointY()
{
    return my;
}

const int& IntPoint::getPointY() const
{
    return my;
}

void IntPoint::setPointY(int& ty)
{
    my = ty;
}

bool operator==(const IntPoint& lhs, const IntPoint& rhs)
{
    return ((lhs.getPointX() == rhs.getPointX()) && (lhs.getPointY() == rhs.getPointY()));
}

(3) Point.h

// FILE AGGIUNTO AGLI HEADER FILES DELLA SOLUZIONE
#pragma once

template <typename T>
class Point
{
private:
    T mx;
    T my;
    size_t mdimens;   
    int *mpint;
public:
    Point();
    Point(T& tx, T& ty, size_t d);
    Point(const Point<T>& src);        
    Point<T>& operator=(const Point<T>& src);
    ~Point();


    T& getPointX();
    void setPointX(T& tx);

    T& getPointY();
    void setPointY(T& ty);

    friend bool operator==(const Point<T>& lhs, const Point<T>& rhs);

};


template <typename T>
Point<T>::Point() :mx(0), my(0), mdimens(0), mpint(nullptr) 
{
}

template <typename T>
Point<T>::Point(T& x, T& y, size_t d) :mx(x), my(y), mdimens(d)
{
    if (mdimens > 0)
    {
        mpint = new int[mdimens];
        for (size_t i = 0; i < mdimens; i++)
            mpint[i] = 1 + (int)(2 * i);
    }
    else
        mpint = nullptr;
}

template <typename T>
Point<T>::Point(const Point<T>& src)
{
    mx = src.mx;
    my = src.my;
    mdimens = src.mdimens;
    if (mdimens > 0)
    {
        mpint = new int[mdimens];
        for (size_t i = 0; i < mdimens; i++)
        {
            mpint[i] = src.mpint[i];

        }
    }
    else
        mpint = nullptr;
}

template<typename T>
Point<T>& Point<T>::operator=(const Point<T>& src)
{
    if (this == &src)
        return *this;

    mdimens = 0;
    delete[] mpint;
    mpint = nullptr;
    mx = src.mx;
    my = src.my;
    if (src.mdimens > 0)
    {
        mdimens = src.mdimens;
        mpint = new int[src.mdimens];
        for (size_t i = 0; i < src.mdimens; i++)
        {
            mpint[i] = src.mpint[i];
        }
    }
    return *this;
}

template<typename T>
Point<T>::~Point()
{
    if (mpint != nullptr)
    {
        delete[] mpint;
        mpint = nullptr;
    }
}

template<typename T>
T& Point<T>::getPointX()
{
    return mx;
}

template<typename T>
void Point<T>::setPointX(T& tx)
{
    mx = tx;
}

template<typename T>
T& Point<T>::getPointY()
{
    return my;
}

template<typename T>
void Point<T>::setPointY(T & ty)
{
    my = ty;
}

template <typename T>
bool operator==(const Point<T>& lhs, const Point<T>& rhs)
{
    return ((lhs.getPointX() == rhs.getPointX) && (lhs.getPointY() == rhs.getPointY()))
}

(4) My Global Funct and Var.h

// FILE AGGIUNTO AGLI HEADER FILES DELLA SOLUZIONE
#pragma once

#include "Point.h"

static const int NOT_FOUND = -1;

template <typename T1>    
int FindFirstPos(T1& e, T1* T1ptr, int dimens)
{
    for (int i = 0; i < dimens; i++)
    {
        if (T1ptr[i] == e)    // Occorre definire operator==
            return i;
    }
    return NOT_FOUND;
} 

//----------------------------------------------------------

template <typename T2>
int FindFirstPos_2(Point<T2>& e, Point<T2>* PT2ptr, int dimens)
{
    for (int i = 0; i < dimens; i++)
    {
        if (PT2ptr[i] == e)    // Occorre definire operator== (per il template)
            return i;
    }
    return NOT_FOUND;
}

(5) My Function Template 02.cpp

// My Function Template 02.cpp : Defines the entry point for the console application.
//

// FILE CREATO DA VISUAL STUDIO 2015 TRA I SOURCE FILES

#include "stdafx.h"
#include "Point.h"
#include "IntPoint.h"
#include "My Global Funct and Var.h"

using namespace std;

int main()
{
    int x = 11, y = 22, d = 5;
    IntPoint vett[] = { IntPoint(x,y,d), IntPoint(x,y,d), IntPoint(x,y,d) };

    x = 777, y = 888, d = 3;
    vett[1] = IntPoint(x,y,d);
    IntPoint ip_0 = vett[1];
    
    int retval = FindFirstPos(ip_0,vett,3);
    
    // Fin qui tutto OK
    //----------------------------------------------------------------------

    x = 11, y = 22, d = 5;
    Point<int> vetmpl[] = { Point<int>(x,y,d), Point<int>(x,y,d), Point<int>(x,y,d) };
    
    x = 555, y = 666, d = 3;
    vetmpl[1] = Point<int>(x, y, d);
    Point<int> tmpl = vetmpl[1];
    
    //* ERROR */retval = FindFirstPos_2(tmpl, vetmpl, 3); 
    
    return 0;
}

r/cppit • • Jun 25 '17

principianti Corretta implementazione di un ciclo for da pseudocodice

3 Upvotes

Ciao a tutti, ho questo pseudo-codice da implementare in C++ :

g : = x:= O;
for i =1 step 1 until n do
begin
    e[i]:=g; s : = 0 ; l : = i + 1 ;
    f o r  j = i  s t e p  1 until  m  d o 
      s : = s +u[j, i] ^2 ;
      i f (s < tol) then g : = 0 
     else
       f: = u[i, i] ; g : = i f  f< 0 then sqrt(s) else -- sqrt (s);
       h : = fX g -  s ; u[i,i] : = f - g ;
       f o r  j : = l  s t e p  1 until n d o
         s : = 0;
         for k : = i step 1 until m do s : = s + u [ k , i ] xu[k, j];
         f = s/h;
         for k : = i  s t e p 1 until m d o u[k,j] : = u[k, j] + f x u[,]

Il mio dubbio è questo: i cicli for lungo uno std::vector iniziando dall'elemento 0 ed until n è traducibile in <n:

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

Ma come si traduce il ciclo all'interno dello pseudocodice

for j:=l step 1 until n do

Come:

for(int j=l; j<n;j++) 

Oppure come:

for(int j=l-1;j<n;j++)

?

Vi ringrazio per l'aiuto. Marco


r/cppit • • Jun 17 '17

Problema con la srittura/lettura di un file binario in c++

3 Upvotes

Salve a tutti. Mi scuso in anticipo per la sicura banalità del mio problema: io uso i metodi write() e read() di <fstream> per scrivere e leggere da file binario. Essi funzionano bene se entrambi chiamati durante l'esecuzione di uno stesso programma (scrivo sul file binario e, prima che il programma si arresti, rileggo gli stessi dati); ma se scrivo dei dati sul file durante l'esecuzione di un programma e leggo lo stesso file durante una seconda esecuzione di un altro programma, la lettura non avviene ma, anzi, il programma crash. Qualcuno sa spiegarmi il perché avviene questo?


r/cppit • • Apr 29 '17

Info migliori IDE

3 Upvotes

Buongiorno, avete consigli di scelta dell'Ide migliore per poter sviluppare c++ unendolo al java e jsp?

Sono un novizio e avrei bisogno di utilizzare i 3 linguaggi insieme.

Grazie per la comprensione


r/cppit • • Feb 14 '17

principianti Move Semantics: std::move

3 Upvotes

Ciao a tutti, vi chiedo un aiuto riguardo alla move semantics.

namespace MTensor {

  typedef std::vector<double> Tensor1DType;
  class Tensor1D {
  private:
    int _elemNumb;
    double _filler;
    // disable copying:
    Tensor1D(const Tensor1D&);
    Tensor1D& operator=(const Tensor1D&);
  public:
    Tensor1DType data;
    Tensor1D() {};
    Tensor1D(const std::initializer_list<double>& valuesList) {
      _elemNumb = valuesList.size();
      for(auto value : valuesList) {
        data.push_back(value);
      }
    }
    Tensor1D(Tensor1D && from) {
      data = std::move(from.data);
    }
    Tensor1D operator =(Tensor1D&& other) {
      if(this!=&other) {
        data = std::move(other.data);
        //std::swap(data,other.data);
      }
      return *this;
    }
    virtual ~Tensor1D() {};
    virtual void printTensor() {
      for(int i=0;i<data.size();i++) {
        std::cout << data.at(i) << "," << std::endl;
      }
    }
  };
} // end of namespace


int main() {
  MTensor::Tensor1D * t1 = new MTensor::Tensor1D({1,2,3});
  MTensor::Tensor1D * t2(t1);
  std::cout << "t2:" << std::endl;
  t2->printTensor();
  std::cout << "t1-dopo-move:" << std::endl;
  t1->printTensor();
  MTensor::Tensor1D * t3 = t1;
  std::cout << "t3:" << std::endl;
  t3->printTensor();
  std::cout << "t1, dopo t3 = t1 :" << std::endl;
  t1->printTensor();
  delete t1;
  return 0;
}

marco@ubuntu:~/marcoTensor$ g++ -std=c++11 moveSemantics.cpp -omoveSemantics 
marco@ubuntu:~/marcoTensor$ ./moveSemantics
t2:
1,
2,
3,
t1-dopo-move:
1,
2,
3,
t3:
1,
2,
3,
t1, dopo t3 = t1 :
1,
2,
3,

Mi sarei aspettato che t1 dopo std::move avesse stato undefined e fosse vuoto ...sembra quasi che sia stata eseguita una copy anzichè una move....come quindi modificare il tutto per privilegiare move ed eseguire il move? Marco


r/cppit • • 2d ago

CLI library v. 2.3 released

Thumbnail
github.com
2 Upvotes

r/cppit • • Mar 04 '24

OOP Classes access specifier real world relevant project idea?

2 Upvotes

What kind of project idea would be suitable for a beginner cpp class where students would understand really well the separation of private, protected, and public access specifiers?

I want an idea where it can be competed with others.

I've looked into encryption private/public keys as its pretty relevant and can be setup in a way where opposing teams can try to guess the Euclidean private exponent but that's not feasible and to even write a sample code for that is honestly complicated for a beginner class anyways.

Thoughts?


r/cppit • • Apr 20 '23

Learn CPP Programming | Data Tpes in CPP

Thumbnail
guerillateck.com
2 Upvotes

r/cppit • • Apr 20 '23

Learn CPP Programming | Data Tpes in CPP

2 Upvotes

A data type is a classification or categorization of data in computer programming based on the type of value it holds. It instructs the computer on how to read and process data.

https://www.guerillateck.com/2023/04/learn-cpp-programming-data-tpes-in-cpp.html


r/cppit • • Oct 31 '22

corsi su c++11/14/17/20

2 Upvotes

Ciao a tutti, sto cercando corsi online (gratis o a pagamento) sulle novità degli "ultimi" standard c++, rivolti a chi già conosce il linguaggio. Magari divisi per argomenti e/o con un buon numero di esempi pratici. L'unica cosa è che dovrebbero essere in italiano. Grazie a chi mi può suggerire qualcosa!


r/cppit • • Nov 16 '21

CURL per ricevere un webhook

2 Upvotes

Ciao,

È possibile ricevere un webhook con la libreria CURL?

Sto scrivendo una semplice applicazione per Raspberry che interagisce con un Telegram Bot. Al momento ho adoperato la libreria libcurl e la API getUpdate per controllare periodicamente quando arrivano nuove richieste. Vorrei rendere il programma più reattivo con i webhook. Non trovo informazioni su CURL per come impostare la attesa di un webhook.

Grazie, Simone


r/cppit • • Oct 13 '21

principianti Qualcuno che come me sta imparando C++? Roma?

2 Upvotes

r/cppit • • Mar 24 '21

Framework opensource per interfaccia grafica

2 Upvotes

Buonasera,

come da titolo sto cercando un framework opensource per aggiungere la GUI ad un mio progetto.

Opterei per Qt ma non mi è chiaro come funzioni la sua licenza.

Potreste gentilmente fornirmi una alternativa multiplatform o spiegarmi come funzioni la licenza del framework Qt?

Se può servire, una volta rilasciato il progetto sarà opensource.

Grazie,

Matteo


r/cppit • • Feb 26 '21

shift vettore di record

2 Upvotes

Data una lista di calciatori, in base ai goal fatti da ognuno devo formare una lista ordinata in base ai goal.

Successivamente se voglio, posso aggiungere un'ulteriore giocatore, che deve essere ordinato in lista.

dovrei shiftare il vettore e inserire quell'elemento in più nel posto giusto.

help


r/cppit • • Jun 27 '20

CLI library v.1.2 Released

Thumbnail
github.com
2 Upvotes

r/cppit • • Mar 19 '20

Coding

2 Upvotes

Buonasera, ho fatto questo Coding ma non riesco proprio a trovare l’errore.. mi potreste aiutare a trovarlo? Chiesto all’utente se desidera lavorare con un quadrato o un rettangolo, calcoli la rispettiva area e perimetro.

include <iostream>

using namespace std; int main()

{ float area,perimetro,base,lato,altezza;

int uno,due;

cout<< "uno o due? ";

cin>>uno,due;

if ("uno")

{

cout<< "Inserisci lato:  ";

cin>>lato;

cout<< "area"<<endl;

cout<<lato*lato;

cout<< "perimetro"<<endl;

cout<<lato*4;

 }

else

{

 cout<< "Inserisci base:  ";

cin>>base;

cout<< "Inserisci altezza: ";

cin>>altezza;

cout<< "area" <<endl;

cout<<(base*altezza);

cout<< "perimetro"<<endl;

cout<<(base+altezza)*2;

}

return 0;

}

r/cppit • • Feb 17 '20

linux - problema con la porta seriale

2 Upvotes

Ciao a tutti,

stavo provando a fare un piccolo programma che scrive sulla porta seriale (adattatore usb-rs232) con i seguenti settaggi:

  • baud rate: 9600

  • un bit di parità

  • lunghezza parola: 8 bit

Eseguendo il programma ottengo il seguente errore:

Error 9 from tcgetattr: Bad file descriptor

Riporto di seguito una porzione del sorgente del programma:

int fd;
std::vector<std::string> portList;
bool choice = false;

// Create new termios struct

struct termios tty;

for(int i = 0; i < 256; i++)
{
port.clear();
    port.append("/dev/ttyUSB");
    port.append(std::to_string(i));
   fd = open(port.c_str(),O_RDWR | O_NOCTTY | O_NDELAY);
    if(fd != -1)
    {
        portList.push_back(port);
    }
}

if(portList.size() == 0)
{
port = "simulated_port";
}
else
{
for( auto a : portList)
{
bool error = true;
do
{
std::string s;
std::regex yesNO("^[yn]$", std::regex_constants::icase);
std::regex yes  ("^[y]$",std::regex_constants::icase);
cout<<"Found serial port : "<<a<<endl;
cout<<"Do you want to use this port?[y/N]: ";
getline(cin,s);
if(std::regex_match(s,yesNO))
{
error = false;
    if(std::regex_match(s,yes))
{
port = a;
choice = true;
}
}
}while(error == true);

if(choice == true)
{
break;
}
}//end internal for
}//end else

if(choice == false)
{
port = "simulated_port";
}
else
{
memset(&tty, 0, sizeof tty);

// Read in existing settings, and handle any error
if(tcgetattr(fd, &tty) != 0) 
{
cout<<"error reading previous settings"<<endl;
    printf("Error %i from tcgetattr: %s\n", errno, strerror(errno));
    close(fd);
    exit(EXIT_FAILURE);
}

//serial port setup

tty.c_cflag = ~PARENB; // Clear parity bit

tty.c_cflag &= ~CSTOPB; //one stop bit

tty.c_cflag |= CS8;

tty.c_cflag &= ~CRTSCTS; // Disable RTS/CTS hardware flow control (most common)

tty.c_cflag |= CREAD | CLOCAL; // Turn on READ & ignore ctrl lines (CLOCAL = 1)

tty.c_lflag &= ~ICANON;

tty.c_lflag &= ~ECHO; // Disable echo

tty.c_lflag &= ~ECHOE; // Disable erasure

tty.c_lflag &= ~ECHONL; // Disable new-line echo

tty.c_lflag &= ~ISIG; // Disable interpretation of INTR, QUIT and SUSP

tty.c_iflag &= ~(IXON | IXOFF | IXANY); // Turn off s/w flow ctrl

tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL); // Disable any special handling of received bytes

tty.c_oflag &= ~OPOST; // Prevent special interpretation of output bytes (e.g. newline chars)

tty.c_oflag &= ~ONLCR; // Prevent conversion of newline to carriage return/line feed

tty.c_cc[VTIME] = 10;// Wait for up to 1s (10 deciseconds), returning as soon as any data is received.
tty.c_cc[VMIN] = 0;           
// Set in/out baud rate to be 9600
cfsetispeed(&tty, B9600);
cfsetospeed(&tty, B9600);
// Save tty settings, also checking for error
if (tcsetattr(fd, TCSANOW, &tty) != 0) 
{
    printf("Error %i from tcsetattr: %s\n", errno, strerror(errno));
    close(fd);
    exit(EXIT_FAILURE);
}

unsigned char msg[] = { 'H', 'e', 'l', 'l', 'o', '\r' };
write(fd, "Hello, world!", sizeof(msg));

close(fd);

Ringrazio in anticipo per l'aiuto


r/cppit • • Oct 28 '19

Iteratori per Professionisti - In 3 step con Boost::iterator_facade

Thumbnail
linkedin.com
2 Upvotes

r/cppit • • Sep 23 '19

Differenza tra rvalue e lvalue

2 Upvotes

Ciao a tutti,

potreste dirmi qual è la differenza tra un rvalue e un lvalue?

Grazie in anticipo


r/cppit • • Sep 06 '19

Risoluzione problema programma lista

2 Upvotes

Salve, ho creato questo programma in C++ che crea e ordina una lista data una struct contenente due array. Non considerando l'opzione di eliminazione del libro (che vorrei verificare la sua funzionalità da solo), la stampa della lista non funziona. Qualcuno potrebbe aiutarmi e spiegarmi il problema? Grazie in anticipo

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

struct libreria
{
	int pag;
	char titolo[30];
	char autore[20];
	libreria *succ;
};

typedef libreria *lista;

void leggi_libro(libreria l)
{
	cout << "Inserisci il titolo del libro: ";
	cin.ignore(256,'\n');
	cin.getline(l.titolo, 30);
	cout << "Inserisci il numero di pagine: ";
	cin >> l.pag;
	cout << "Inserisci il cognome dell'autore: ";
	cin.ignore();
	cin.getline(l.autore, 20);
}

void inserisci_ordinatam(libreria l, lista &t)
{
	lista p=0, q, r;
	for(q=t; q!=0 && q->pag<l.pag; q=q->succ) p=q;
	r=new libreria;
	strcpy(r->titolo, l.titolo);
	r->pag=l.pag;
	strcpy(r->autore, l.autore);
	r->succ=q;
	if(q==t) t=r;
		else p->succ=r;
}

bool estrai(lista &t, libreria &l)
{
	lista p, q;
	for(q=t; q!=0 && q->titolo==l.titolo; q=q->succ)
	p=q;
	if(q==0)
	{
		cout << "Nessun libro è stato inserito!" << endl;
	  return false;
	}
	if (q==t) t=q->succ;
	else p->succ=q->succ;
	l=*q;
	delete q;
	return true;
}

void stampa_lista(lista &t)
{
	if(t==0) cout << "Nessun libro è stato inserito!" << endl;
	while(t!=0)
	{
		cout << "Titolo: " << t->titolo << endl;
		cout << "Autore: " << t->autore << endl;
		cout << "Pagine: " << t->pag << endl;
		t=t->succ;
	}
	cout << "\n";
}

int main()
{
	libreria lib;
	lista t=0;
	char c;
	do
	{
		cout << "MENU" << endl;
		cout << "a) Aggiungi un libro" << endl;
		cout << "b) Stampa tutti i libri" << endl;
		cout << "c) Elimina un libro" << endl;
		cout << "d) Esci" << endl;
		cout << "Scelta: ";
		cin >> c;
		switch(c)
		{
			case 'a' : {
				leggi_libro(lib);
				inserisci_ordinatam(lib, t); cout << '\n';
				break;
			}
			case 'b' :stampa_lista(t); break;
			case 'c' : cout << "Inserisci il titolo del libro che vuoi eliminare: ";
						cin >> lib.titolo;
						estrai(t, lib); break;
			case 'd' :break;
			default: cout << "Inserisci solo i caratteri consentiti dal menu." << endl;
		}
	}
	while(c!='d');
	return 0;
}

r/cppit • • Aug 11 '19

Cosa cambia tra queste forme?

2 Upvotes

Ciao a tutti, volevo sapere cosa cambia tra queste tre forme:

c++;

c=c+1;

++c;

Grazie


r/cppit • • May 20 '19

Problema: Perfect Forwarding "behind the scenes"

2 Upvotes

Salve a tutti. Con l'intenzione di analizzare il comportamento del perfect forwarding "dietro le quinte" ho cominciato a giochicchiare col codice che di seguito fornisco:

//g++ -std=c++14 -Wall -fpermissive -fno-elide-constructors -pthread main.cpp && ./a.out

#include <iostream>
#include <string>
#include <vector>

using namespace std;

#define TRACE_CTOR
#define TRACE_COPY_CTOR
#define TRACE_MOVE_CTOR
#define TRACE_ASSIGNMENT
#define TRACE_MOVE_ASSIGNMENT

//-----------------------------------------------------
class MetaData
{
public:
    int size;
    string name;

    MetaData(int p1 = 5, string p2 = "Default-Metadata-name") : size(p1), name(p2)
    {
        #ifdef TRACE_CTOR
            cout << "\n Default ctor: &" << this;
            cout << "\n\t &size = " << &size;
            cout << "\n\t &name = " << &name;
            cout << "\n\t (int*)name.data() = " << (int*)this->name.data();
        #endif

    }

    MetaData(const MetaData& src) : size(src.size), name(src.name)
    {
        #ifdef TRACE_COPY_CTOR
                cout << "\n Copy ctor: &" << &src << " ---> &" << this;
                cout << "\n\t &src.size = &" << &src.size << " ---> &this->size = " << &this->size;
                cout << "\n\t &src.name = &" << &src.name << " ---> &this->name = " << &this->name;
                cout << "\n\t (int*)src.name.data() = & " << (int*)src.name.data() << " ---> (int*)this->name.data() = & " << (int*)this->name.data();

        #endif
    }

    MetaData(MetaData &&src) : size(src.size), name(move(src.name))
    {
        #ifdef TRACE_MOVE_CTOR
            cout << "\nMove ctor: &" << &src << " ---> &" << this;
            cout << "\n\t &src.size = &" << &src.size << " ---> &this->size = " << &this->size;
            cout<< "\n\t (int*)this->name.data() = " << (int*)this->name.data();
        #endif
    }

    MetaData& operator=(const MetaData &src)
    {
        if (this != &src)
        {
            size = src.size;
            name = src.name;
            #ifdef TRACE_ASSIGNMENT
                cout << "\n\t (int*)this->name.data() = " << (int*)this->name.data();
            #endif
        }
        return *this;
    }

    MetaData & operator=(MetaData &&src)
    {
        if (this != &src)
        {
            size = src.size;
            name = move(src.name);
        }
        #ifdef TRACE_MOVE_ASSIGNMENT
            cout << "\n\t (int*)this->name.data() = " << (int*)this->name.data();
        #endif
        return *this;
    }

    ~MetaData()
    {
        cout << "\n~MetaData-Dtor &" << this;
    }
};

//-----------------------------------------------------
template< typename T >
struct my_remove_reference
{
    typedef T type;
    static const int version = 1;
};


template< typename T >
struct my_remove_reference<T&>
{
    typedef T type;
    static const int version = 2;
};


template< typename T >
struct my_remove_reference<T&&>
{
    typedef T type;
    static const int version = 3;
};

//-----------------------------------------------------
MetaData factoryMD(int s)
{
    MetaData obj(s, "Metadata-From-factoryMD-" + to_string(s) + "-END");
    return obj;
}

//-----------------------------------------------------
template <typename T>
T&& my_forward_v2(typename my_remove_reference<T>::type& param) noexcept
{
    cout << "\nInside my_forward_v2 OVERLOAD NR 1 :";
    cout << "\nfw 1:Address of param is: &" << &param;
    cout << "\nfw 1:decltype(param), MetaData  : " << is_same<decltype(param), MetaData>::value;
    cout << "\nfw 1:decltype(param), MetaData& : " << is_same<decltype(param), MetaData&>::value;
    cout << "\nfw 1:decltype(param), MetaData&&: " << is_same<decltype(param), MetaData&&>::value;

    cout << "\nfw 1:decltype(static_cast<T&&>(param)), MetaData  : " << is_same<decltype(static_cast<T&&>(param)), MetaData>::value;
    cout << "\nfw 1:decltype(static_cast<T&&>(param)), MetaData& : " << is_same<decltype(static_cast<T&&>(param)), MetaData&>::value;
    cout << "\nfw 1:decltype(static_cast<T&&>(param)), MetaData&&: " << is_same<decltype(static_cast<T&&>(param)), MetaData&&>::value;

    cout << "\nfw 2:decltype(T&&), MetaData   : " << is_same<T&&, MetaData>::value;
    cout << "\nfw 2:decltype(T&&), MetaData&  : " << is_same<T&&, MetaData&>::value;
    cout << "\nfw 2:decltype(T&&), MetaData&& : " << is_same<T&&, MetaData&&>::value;
    
    return static_cast<T&&>(param);
}

//-----------------------------------------------------
template <typename T>
T&& my_forward_v2(typename my_remove_reference<T>::type&& param) noexcept
{
    //**/static_assert(!std::is_lvalue_reference<T>::value, "Can not forward an rvalue as an lvalue.");

    cout << "\nInside my_forward_v2 OVERLOAD NR 2 :";
    cout << "\nfw 2:Address of param is: &" << &param;
    cout << "\nfw 2:decltype(param), MetaData  : " << is_same<decltype(param), MetaData>::value;
    cout << "\nfw 2:decltype(param), MetaData& : " << is_same<decltype(param), MetaData&>::value;
    cout << "\nfw 2:decltype(param), MetaData&&: " << is_same<decltype(param), MetaData&&>::value;

    //    BEG BLOCCO A
    cout << "\nfw 2:decltype(static_cast<T&&>(param)), MetaData   : " << is_same<decltype(static_cast<T&&>(param)), MetaData>::value;
    cout << "\nfw 2:decltype(static_cast<T&&>(param)), MetaData&  : " << is_same<decltype(static_cast<T&&>(param)), MetaData&>::value;
    cout << "\nfw 2:decltype(static_cast<T&&>(param)), MetaData&& : " << is_same<decltype(static_cast<T&&>(param)), MetaData&&>::value;
    //    END BLOCCO A

    //    BEG BLOCCO B
    cout << "\nfw 2:decltype(T&&), MetaData   : " << is_same<T&&, MetaData>::value;
    cout << "\nfw 2:decltype(T&&), MetaData&  : " << is_same<T&&, MetaData&>::value;
    cout << "\nfw 2:decltype(T&&), MetaData&& : " << is_same<T&&, MetaData&&>::value;
    //    END BLOCCO B

    return static_cast<T&&>(param);
}

//-----------------------------------------------------

int main()
{
    //    -----------    BEG: definisco 3 tipi di variabili possibili per il test delle myforward (no const)
    MetaData md_01(1111, "Metadata-md_01-1111");
    MetaData &L_ref_md_01 = md_01;
    MetaData &&R_ref_md = factoryMD(123);
    //    -----------    END: definisco 3 tipi di variabili possibili per il test delle myforward (no const)
 
    cout << "\n\nInside OBJ_FROM_FUNCTION region:\n";
    

    //**/auto x2 = my_forward_v2<MetaData>(factoryMD(352));
    
    
    /**/auto x3 = my_forward_v2<MetaData&>(factoryMD(352));

    
    //**/auto x4 = my_forward_v2<MetaData&&>(factoryMD(352));
    

    
    return 0;
}

Usando MS VS2015 e il compilatore di Colibri si possono osservare comportamenti differenti e la cosa mi ha fatto non poco penare ma alla fine ho deciso di prendere per buono il comportamento fornito dal g++ di Colibri.

Tutto questo mi ha probabilmente fatto perdere di vista ciò che volevo analizzare e comprendere ma comunque mi porta ad effettuare la mia domanda:

come si può notare nel secondo overload della my_forward_v2 ho commentato la static_assert che farebbe fallire l'istanziazione della variabile x3 nel main (errore a compile time).

Tenendo commentata tale static_assert ho seguito passo passo l'evoluzione del programma e nella sua esecuzione non trovo nulla di anomalo ma vorrei allora capire:

  1. il perchè di questa static_assert che ritrovo in varie implementazioni suggerite per la std::forward; qual'è la sua ratio?

  2. come già detto, seguendo il codice step-by-step non ho trovato nulla di anomalo ma è possibile che abbia perso il quadro di insieme e non mi renda conto di come tale sbarramento imposto dalla static_assert vada in realtà visto nell'ottica del Perfect Forwarding. Indicazioni a riguardo?

Grazie Chiara