jeudi 31 octobre 2019

How to use Boost::Variant inside a structure?

ValueType is a boost variant. I am using this as a member of struct1. I want to write + operator overloading for struct1.

  1. Currently I got an error in the below code. Please help me to solve this.

    using ValueType = boost::variant;

    struct struct1 { ValueType value; int length;

    struct1 &operator+(const struct1 &right)
    {
        length = length + right.length;
        value = value + right.value; // ------> error
        return *this;
    }
    

    };

  2. Can I use template structure here? If yes, please add the code with operator overloading.

How to resolve the ambiguity in the function passed to boost thread

I want to create a new thread using boost , the function RenderOut is a member of the class BlueOut.

the function is overloaded and how do i resolve this ambiguity while passing itto the boost thread.

void BlueOut( int i);
void BlueOut( std::string str);


boost::thread* thr = new boost::thread(boost::bind ( &BlueOut::RenderOut , &blueout ));

Custom compare class not working as I expect for pointers to a user defined class in a std::set container

I can't figure out why in this code example the std::set container is not ordering the Entities as I expect on the basis of the compare class I defined. Anyone can help me please? Thanks

 #include <iostream>
 #include <set>

 class Entity {
 public:
 int num;
 Entity(int num):num(num){}
     bool operator< (const Entity& _entity) const { return (this->num < _entity.num); }
 };

 struct my_cmp {
     bool operator() (const Entity* lhs, const Entity* rhs) const { return (lhs < rhs); }
 };

 class EntityManager {
     private:
        std::set<Entity*, my_cmp> entities;
   public:
        void AddEntity(int num) { entities.insert(new Entity(num)); }
        void ListAllEntities() const {
              unsigned int i = 0; 
              for (auto& entity: entities) {
                  std::cout << "Entity[" << i << "]: num:" << entity->num << std::endl;
                  i++;
              }
         }
};

int main(void) {
    EntityManager manager;
    manager.AddEntity(2);
    manager.AddEntity(1);
    manager.AddEntity(4);
    manager.AddEntity(3);
    manager.ListAllEntities();
    return 0;
}

Output:

Entity[0]: num:2

Entity[1]: num:1

Entity[2]: num:4

Entity[3]: num:3

I would expect the following output instead:

Entity[1]: num:1

Entity[0]: num:2

Entity[3]: num:3

Entity[2]: num:4

Is capturing a newly constructed object by const ref undefined behavior

Is the following (contrived example) okay or is it undefined behavior:

// undefined behavior?
const auto& c = SomeClass{};

// use c in code later
const auto& v = c.GetSomeVariable();

How can I get the leftover room space?

So this is the task I need help with:

The blueprint of a house is made on a unit square grid sheet. All rooms must be rectangular. So far, N rooms have been drawn on the blueprint. Each room is defined by the upper left and lower right corners. One field of the square grid is given by the x and y coordinates, the coordinates of the upper left field (0,0). The x-coordinates increase horizontally and the y-coordinates increase vertically. The designer wants to calculate how many new rectangular rooms can be added if the two sides of any two new rooms cannot have a common part, and all four sides are adjacent or existing, or the side of the house. The rooms planned so far are such that every free space is rectangular. Make a program that tells you what the largest possible new room area can be in your plan.

Input:

The first line of the standard input has the number of rooms in the design (1≤N≤10,000) and the coordinates of the upper left (FX, FY) and lower right (AX, AY) corners of the house (0≤FX

Output:

The first line of the standard output should be the area of ​​the largest new room!

Theres an example in the link and its the basic input and output that you can test the program with. I translated this task from hungarian so the Példa=example , Bemenet=input , Kimenet=output. I would be really happy to get some help with this taks because for me it is a little bit too hard.

Basic input example

Ball is launched at 45 degrees on a pool table, calculate how many times it hits wall before falls in hole, size of table are integers

Ball is launched at 45 degrees on a pool table, calculate how many times it hits wall before falls in hole, size of table are integers

How to get a reference/pointer to a class (not an object)?

I have a std::map where key is string and I want the value to be, not an object, but a reference/pointer to a class which I can instantiate.

std::map<::std::string, ?class_reference?> handlers_;

Once the specific entry is chosen, I want to create instance of the class and execute a member function.

Print duplicate values once in a multimap

I have a multimap that contains using myMap= std::multimap <std::string, std::string>;

here is a sample data that's in it.

West;Tuulensuu
West;Keskustori
South;Sammonaukio
West;Rautatieasema
West;Tulli
West;Sammonaukio
East;Sammonaukio

I'd like to print just the values, but all the values should only be printed once and should be sorted.

I've tried the following.

void print_lines(myMap& tramlines)
{
    for (auto it = tramlines.begin(); it != tramlines.end(); ) {
        std::string key = it->second;

        std::cout << it->second << std::endl;

        // Advance to next non-duplicate entry.
        do {
            ++it;
        } while (it != tramlines.end() && key == it->second);
    }
}

It still printed the values more than once. So I tried the following.

auto uniq = std::unique(tramlines.begin(), tramlines.end());
tramlines.erase(uniq, tramlines.end());

for(auto item : tramlines)
{
    std::cout << item.second << std::endl;
}

But that's giving me the following error

Severity    Code    Description Project File    Line    Suppression State
Error   C2679   binary '=': no operator found which takes a right-hand operand of type 'std::pair<const _Kty,_Ty>' (or there is no acceptable conversion)   Prog2Test

What are my options here? I can't find anything online that points to printing values, I've found plenty for Keys.

Would iterating through the values and adding them to set and printing them out a good idea?

Why is there an undefined reference to error when compiling a Catch2 test? How should I fix it?

I'm trying to write a test script for Catch2 but am having some major headscratching errors.

I've looked online for similar cases to mine, but it seems like they also used CMakeList.txt files whereas I only downloaded the catch.hpp from the Catch2 README.

In my folder, I have getDifferences.cpp, getDifferences.hpp, and test.cpp where where I put in

#define CATCH_CONFIG_MAIN, #include "catch.hpp", #include "getDifferences.hpp" on top of its header, and have no other main() defined.

My laptop: OS: Dualboot ChromeOS / XFCE4 Compiler+version g++ (Ubuntu 5.4.0) Catch version: 2.10.0 latest version

Next, I tried compiling test.cpp with:

g++ -std=gnu++11 test.cpp

and it results in the error below:

/tmp/ccd1AxMb.o: In function `____C_A_T_C_H____T_E_S_T____0()':
test.cpp:(.text+0x27be4): undefined reference to `getDifferences(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
test.cpp:(.text+0x27daf): undefined reference to `getDifferences(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
test.cpp:(.text+0x27f71): undefined reference to `getDifferences(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
/tmp/ccd1AxMb.o: In function `____C_A_T_C_H____T_E_S_T____2()':
test.cpp:(.text+0x284b7): undefined reference to `getDifferences(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
test.cpp:(.text+0x28740): undefined reference to `getDifferences(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
/tmp/ccd1AxMb.o:test.cpp:(.text+0x28ca8): more undefined references to `getDifferences(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)' follow
collect2: error: ld returned 1 exit status

I'm not sure why I receive an undefined reference to getDifferences, a function that I've defined and included in the header files. Any pointers would be so helpful. Thank you in advance!

Using templates in std::conditional to determine function argument types

I want all my saving and loading of data to go through the same functions to reduce the chance of bugs. To do this I used a lot of templates (and much function overloading). It worked, my code is now much cleaner, but I was unable to use const for saving (because it goes through the same functions as the loader does, where the data is kept non-const).

I'd like to use the const correctly, so here is an attempt to get a simple version working, where the data (in this case std::vector) is non-const for std::ifstream, and const otherwise:

#include <iostream>
#include <fstream>
#include <vector>

template <class Foo>
void Overload(const Foo & foo)
{
    std::cout << "went to const" << std::endl;
}

template <class Foo>
void Overload(Foo & foo)
{
    std::cout << "went to non-const" << std::endl;
}

template <class StreamType, typename... Arguments>
void ReadOrWrite (

    /* for 1st argument */ StreamType & filestream,

    /* type for 2nd argument */ typename std::conditional< 
        /* if */    std::is_same<StreamType, std::ifstream>::value,
            /* then */  std::vector<Arguments...>,
            /* else */  const std::vector <Arguments...>
            >::type

        /*2nd argument name */ & vector
        )
{
    Overload(vector);
}

int main ()
{
    std::ofstream output_filestream;
    std::ifstream intput_filestream;

    std::vector<int> vector;

    ReadOrWrite(output_filestream, vector);
    ReadOrWrite(intput_filestream, vector);

    return 0;
}

I know that it will compile/run properly if I edit the function calls to this:

ReadOrWrite<std::ofstream, int>(output_filestream, vector);
ReadOrWrite<std::ifstream, int>(intput_filestream, vector);

But I don't want the user of the function to need to list the types during the function call.

Is there a clean way to do what I'm suggesting?

C++ - proper way to map objects (like strings) to member functions in table

I'm processing events defined by a 3rd party API. The events are identified by string identifiers i.e. "EventABC"

I need to map these (string) events in a table to member-functions of an object.

QUESTION

What's the safest and cleanest way to do this?

Why can't I inherit from Eigen::Matrix?

I have this class:

template < unsigned N, typename T >
class MY_EXPORT my_point : protected Eigen::Matrix< T, N, 1 >
{
public:
  using vector_type = Eigen::Matrix< T, N, 1 >;

  my_point() : vector_type{ vector_type::Zero() } {}
  using vector_type::vector_type;
};

My Linux (GCC) build is fine. However, on Windows (MSVC 15.9.16), I get really strange errors:

c:\include\eigen3\eigen\src\core\densebase.h(482): error C2338: THIS_METHOD_IS_ONLY_FOR_1x1_EXPRESSIONS (compiling source file c:\code\my_point.cxx) [C:\workspace\KwiverWindows\build\vital\vital.vcxproj]
  c:\include\eigen3\eigen\src\core\densebase.h(481): note: while compiling class template member function 'const float &Eigen::DenseBase<Derived>::value(void) const'
          with
          [
              Derived=Eigen::Matrix<float,4,1,0,4,1>
          ] (compiling source file c:\code\my_point.cxx)
  c:\include\eigen3\eigen\src\core\matrixbase.h(50): note: see reference to class template instantiation 'Eigen::DenseBase<Derived>' being compiled
          with
          [
              Derived=Eigen::Matrix<float,4,1,0,4,1>
          ] (compiling source file c:\code\my_point.cxx)
  c:\include\eigen3\eigen\src\core\plainobjectbase.h(100): note: see reference to class template instantiation 'Eigen::MatrixBase<Derived>' being compiled
          with
          [
              Derived=Eigen::Matrix<float,4,1,0,4,1>
          ] (compiling source file c:\code\my_point.cxx)
  c:\include\eigen3\eigen\src\core\matrix.h(180): note: see reference to class template instantiation 'Eigen::PlainObjectBase<Eigen::Matrix<float,4,1,0,4,1>>' being compiled (compiling source file c:\code\my_point.cxx)

It looks like the compiler is trying to instantiate inappropriate methods (e.g. a later error is trying to instantiate w() for a 3-vector). What am I doing wrong? (Why is this not a problem when using Eigen::Matrix directly?)

Here is a live demo.

Unable to debug c++ program with class implementation

I am trying to setup debugging environment in visual studio and I hope I was successful in doing it,because when I am trying to debug a normal math c++ program then my break point is hitting(or first line of code as default breakpoint) but when I am trying to debug the main program with class header file name included in the main program(i.e with class object or class implementation) then my breakpoint are not hitting. Any help where I am going wrong??

#include <iostream>
#include "Sales_item.h"
using namespace std;
int main()
{
 cout<<"hello";
 Sales_item item1, item2;
 cin >> item1 >> item2; // read a pair of transactions
 cout << item1 + item2 << endl; // print their sum
 return 0;
}

This is showing in cppdgb console:

C:\Users\admin\Documents\cpp>c:\Users\admin.vscode\extensions\ms-vscode.cpptools-0.26.1\debugAdapters\bin\WindowsDebugLauncher.exe --stdin=Microsoft-MIEngine-In-w2a4a5fw.4hb --stdout=Microsoft-MIEngine-Out-q2oc4jsv.b14 --stderr=Microsoft-MIEngine-Error-rlvf2qhl.2bw --pid=Microsoft-MIEngine-Pid-3fayxkbu.ji4 --dbgExe=C:\MinGW\bin\gdb.exe --interpreter=mi

Make Templates for basic data types only

How can we make a template accept only basic data types.

template <typename T> 
void GetMaxValue( T& x ) 
{ 
//... Finds max Value
} 

In the above function GetMaxValue we are able to pass any value without any an error.

But the std Function std::numeric_limits<T>::max() has handled it. For example:

auto max = std::numeric_limits< std::map<int,int> >::max();

will Give an error error C2440: '<function-style-cast>' : cannot convert from 'int' to 'std::map<_Kty,_Ty>'

Sort unique values from a map

I have a custom map in my header file

class Tramway
{
private:
    using stations = std::vector <std::string>;
    using Tramlines = std::map <std::string, stations>;
...../

I'm trying to sort the unique values, but so far my approach is giving me compile errors. Here is my code.

void Tramway::print_stations(const Tramway::Tramlines &tramlines)
{

    for(auto map_iter = tramlines.cbegin(); map_iter != tramlines.cend(); ++map_iter)
    {
        std::unique(map_iter->second.cbegin(), map_iter->second.cend());

        std::sort(map_iter->second.begin(), map_iter->second.end());

       for( auto vec_iter = map_iter->second.cbegin() ; vec_iter != map_iter->second.cend() ; ++vec_iter )
           std::cout << *vec_iter << std::endl;
    }

}

Is there a way to get unique values and sort them at the same time? I tried ´std::sort(std::unique(..,..))´ but ´std::sort()´ needs two arguments to work.

How does shared_ptr work in c++ without initialization

I was going through shared_ptr and came across this.

class A
{
    public:
        A() { cout << "In constructor" << endl; }
        ~A() { cout << "Destructor" << endl; }
        void fun() { cout << "In fun... " << endl; }
};
int main()
{
    shared_ptr<A> a;
    a->fun();
    return 0;
}

The output of this is - In fun...

I would like to understand how is this giving above output.

On further experimentation if there is a member variable and being used in this function it throws an SIGSEGV.

class A
{
    public:
        A() { cout << "In constructor" << endl; }
        ~A() { cout << "Destructor" << endl; }
        void fun() { a = 5 ; cout << "In fun... " << endl; }
        int a;
};

int main()
{
    // A::fun();
    shared_ptr<A> a;
    a->fun();
    return 0;
}

Above throws SIGSEGV stating this pointer is null.

no member named 'to_string' in namespace 'std' - when using C++11 compile option

I'm writing an Android Native-Activity App in Microsoft Visual Studio 2017, using the nhlomann json library, a header only library (nlohmann/json.hpp), which includes the std::to_string() function.

On compilation I get "no member named 'to_string' in namespace 'std' "

  • C++ language standard is defined as C++11
  • gnu-libstdc++ 4.9
  • is in the header file

Is the problem that gnu_libstdc++ 4.9 doesn't fully implement C++11?

As the code is a 3rd party library, I don't want to replace std::to_string() with my own template, and edit the library code (for maintainability reasons).

Any suggestions on how to get past this error?

How would I get this functionality in my matrix class? [duplicate]

This question already has an answer here:

#include <iostream>
#include <array>

template<typename T, std::size_t R, std::size_t C>
class matrix
{
   std::array<T, R * C> m_data;
};

int main() 
{
   matrix<float, 2, 2> a = { 1,2,3,4 }; // COMPILER ERROR!
}

Clang reports that there is no matching constructor!

I have tried writing a constructor of the form

matrix(std::array<T,R*C> a);

and tried experimenting with && as I think the right-hand side of the expression in question is temporary. Which leads me to some confusion. As we would expect that it would be created then assigned(!) to the value of a.

Object address suddenly changed

class test
{
    void thread1()
    {
        int i = 0;

        for(unsigned int k = 0;k < mLD.size(); k++ )
        {

            mLD[k] = i++;

        }
    }

    void thread2()
    {
        std::cout << "thread2 address  : " << &mLD << "\n";
        C();
    }


    void B()
    {
        std::cout << "B address  : " << &mLD << "\n";

        for(unsigned int k = 0;k < mLD.size(); k++ )
        {

            if(mLD[k]<=25)
            {

            }
        }
    }

    void C()
    {
        B();

        std::cout << "C address  : " << &mLD << "\n";

        double distance = mLD[0];  //  <---- segmetation fault

    }

    std::array<double, 360> mLD;
};

cout result --->

thread2 address : 0x7e807660

B address : 0x7e807660

C address : 0x1010160 (sometimes 0x7e807660 )

Why mLD's address changed ....?

even i change "std::array" to "std::array, 360>", the result is the same.

How to remove the Apostrophe at the from and the back from a string with c++

I ran into a little trouble with removing the first and last apostrophe from string. I have a vector of string and some of them have apostrophe either at from or back of string. For example, I have {'cause, 'til, holdin', don't} I want output like this {cause, til, holdin, don't} How do I do this?

mercredi 30 octobre 2019

How to Fix This error while running this DFS code?

I have written a code to implement dfs on a graph as follows:

#include <iostream>
#include<stack>
#include<stdbool.h>
#define MAX 10
using namespace std;
int vertex_id=0;
int graph_id=0;
class vertex{
    public:
    int id;
    int visited;
    int adj[MAX];
    vertex();
};
vertex::vertex()
{
    visited=0;
    id=++vertex_id;
    for(int i=0;i<MAX;i++)
    {
        adj[i]=0;
    }
}
class graph:public vertex{
    public:
    stack<vertex> s;
    int g_id;
    vertex adj_matrix[MAX+1][MAX+1];
    void dfs(vertex v);
    void show_dfs(vertex v);
    void add_edge(vertex v1,vertex v2);
    graph();
};
graph::graph(){
    g_id=graph_id++;    //for multiple graphs
    vertex_id=0;
    for(int i=1;i<MAX+1;i++)
    {
        for(int j=1;j<MAX+1;j++)
        {
            adj_matrix[i][j].id=-1;
        }
    }
}
void graph::add_edge(vertex v1,vertex v2){
    v1.adj[v2.id]=1;
    v2.adj[v1.id]=1;
    adj_matrix[v1.id][v2.id]=v2;
    adj_matrix[v2.id][v1.id]=v1;
}
void graph::dfs(vertex v){
    s.push(v);
    v.visited=true;
    int counter=0;
    for(int i=1;i<MAX+1;i++)
    {
        if(adj_matrix[v.id][i].visited==0 && adj_matrix[v.id][i].id!=-1)
        {
            adj_matrix[v.id][i].visited=1;
            counter=1;  //successfully found adjacent unvisited vertex
            vertex va=adj_matrix[v.id][i];
            dfs(va);
            return;         //once dfs is excecuted, no breadth traversal should follow
        }
    }
    if(!counter)
    {
        show_dfs(v);
        cout<<endl;
        return;
    }
}
void graph::show_dfs(vertex v){
        if(s.empty())
        cout<<"No Paths Found ";
        while(!s.empty())
        {
            cout<<(s.top()).id<<"<---";
            s.pop();
        }
}
int main()
{
    graph g;
    vertex v1,v2,v3,v4,v5,v6,v7,v8,v9,v10;
    g.add_edge(v1,v2);
    g.add_edge(v1,v3);
    g.add_edge(v1,v5);
    g.add_edge(v3,v4);
    g.add_edge(v3,v2);
    g.add_edge(v2,v8);
    g.add_edge(v8,v9);
    g.add_edge(v9,v10);
    g.add_edge(v5,v7);
    g.add_edge(v5,v6);
    g.add_edge(v6,v7);
    g.dfs(v2);
    //g.show_dfs(v2);
    return 0;
}

The problem with my code is although it compiles without error but it keeps on pushing the same vertices more than once even when the visited attribute is made true and is checked for each time the loop runs. for example the graph used here produces the following output: Sample output

How can i display the suit variable like ( Suit is: XXXXX (Hearts, Clubs, Spades, Diamonds))?

class Card
{ private: int value; // stores value of card(1,2,3,4,5,6,7,8,9,0) char suit; // stores suit of card('h','d','s','c' char card; // stores card symbol(1,2,3,4,5,6,7,8,9,0,k,q,j,a)

public:


    void setValue(int v)         {value = v;}  
    void setCard(char c)         {card = c;} 
    void setSuit(char s)         {suit = s;} 


    int getValue()        {return value;} 
    char getSuit()        {return suit;} 
    char getCard()        {return card;} 

    void display();

};

void Card :: display() // display member function {

cout << "Value is: " << getValue() << endl; 
cout << "Suit is : " << getSuit() << endl; 


cout << "Card is: " << getCard() << endl;

}

Why did expression types change in C++ between versions?

I try to understand expression types of C++ and the more I read, the more confused I was, since I find the C++ draft very difficult to digest and therefore prefer other resources but they either contradict each other or don't take into account that the wording and definition between C++ versions heavily changes.

In the following I refer to the following drafts:

  • C++11 [n3690] (final draft)
  • C++17 [n4659] (final draft)
  • C++20 [n4835] (current draft)

C++11 3.10 Lvalues and rvalues

... A prvalue (“pure” rvalue) is an rvalue that is not an xvalue. [ Example: The result of calling a function whose return type is not a reference is a prvalue. The value of a literal such as 12, 7.3e5, or true is also a prvalue. — end example ]

C++17 3.10 Lvalues and rvalues

... A prvalue is an expression whose evaluation initializes an object or a bit-field, or computes the value of the operand of an operator, as specified by the context in which it appears.

C++20 7.2.1 Value categories*

... A prvalue is an expression whose evaluation initializes an object or a bit-field, or computes the value of an operand of an operator, as specified by the context in which it appears, or an expression that has type cv void.

I would understand the wording changes, and some adjustments are made, but for me the entire definition changes. Can someone help me to understand this? For instance, why was the sentence removed that a prvalue is an rvalue that is not an rvalue? Or why did the helpful example got removed?

c++11 thread sleep/wakeup without lock?

I use a lockfree queue between two threads. One produce data,another consume data. What I want to do is that, when the queue is empty, consumer thread yield cpu until producer thread push data to the queue. I can't call sleep() since there is no way to wakeup a sleeping thread, I think. What I found is std::condition_variable, but it needs a mutex. producer thread need to hold the lock and then notify consumer thread for every data pushing. Is there a better and lighter way to realize my goal?

Why std::memory_order_relaxed is preferred at CAS loop when failing?

When it comes to implementing CAS Loop using std::atmoic, cppreference in this link gives the following demonstration for push:

template<typename T>
class stack
{
    std::atomic<node<T>*> head;
 public:
    void push(const T& data)
    {
      node<T>* new_node = new node<T>(data);
      new_node->next = head.load(std::memory_order_relaxed);

      while(!head.compare_exchange_weak(new_node->next, new_node,
                                        std::memory_order_release,
                                        std::memory_order_relaxed /* Eh? */));
    }
};

Now, I don't understand how come std::memory_order_relaxed is used for the failure case, because as far as I understand, compare_exchange_weak (same for -strong but I'll just use the weak version for convenience) is a load operation at failure, which means it loads from a successful CAS operation in another thread with std::memory_order_release, and thus it should use std::memory_order_acquire instead to be synchronized-with...?

What if, hypothetically, the 'relaxed load' gets one of the old values, ending up failing again and again, staying in the loop for extra time?

The following scratchy picture is where my brain is stuck at.

enter image description here

So to sum up my question,

  • Why not std::memory_order_acquire, instead of std::memory_order_relaxed at failure?
  • What makes std::memory_order_relaxed sufficient?
  • Does std::memory_order_relaxed on failure mean (potentially) more looping?
  • Likewise, does std::memory_order_acquire on failure mean (potentially) less looping? (beside the downside of the performance)

If my class mnages a resource correctly then what is the point in having smart poointers?

I am new to smart pointers, I liked using them for the safety and power of sharing object...

I have one question: If my class manages a resource in its constructors and destructors applying some rules of thumb like the Big 5 and the Big 3... Should I still use smart pointers? or my class is an alternative to them. Because as I've read in C++ primer 5 edition that smart pointers came to solve problems raw pointers were facing like memory-leaks, double-deleting pointers and accessing a dangling pointer... My class can avoid those problems:

class BallGame {
    public:
        using Resource = int;

        BallGame(int);
        BallGame(const BallGame&);
        BallGame(BallGame&&);
        BallGame& operator=(const BallGame&);
        BallGame& operator=(BallGame&&);
        ~BallGame();
    private:
        Resource m_res;
};
  • Consider that the member of my class are doing the right job so can I avoid smart pointer?

  • I want to know some scenarios when I should use smart pointers rather than managing resources in my class.

  • Are they really for "dumb classes" (classes that define constructors but not well-behaved destructors) like in C++ primer book.

Thank you.

Expand std::vector into parameter pack

I have methods with the following signature:

void DoStuff(int i);
void DoStuff(int i, k);
void DoStuff(int i, int k, int l);

I have a method from where I would like to call the DoStuff methods as follows:

void CallDoStuff(const std::vector<int>& vElements) {
  // What magic is supposed to happen here to make vElements an expandable pack?
  DoStuff(vElemets...);
}

Is there any chance to achieve this? Is using std::index_sequence the right way? If yes, could you please provide me a simple example how to apply this to my problem?

How to find the minimum vale between three (for loop)?

I need to find the minimum value between sonarRange[i], sonarRange2[i] and sonarRange3[i].Each one of the three previous arrays is in an individual (for loop) as it showed the code

I used the If statement to calculate the minimum value. It works but I wrote many codes.

    for (int i = 0; i < 8; i++)
    {
        sonarSensor[i] = robot.getSonarReading(i);
        sonarRange[i] = sonarSensor[i]->getRange();

    }
    for (int i = 0; i < 8; i++) {
        sonarSensor[i] = robot.getSonarReading(i);
        sonarRange2[i] = sonarSensor[i]->getRange();

        }

    for (int i = 0; i < 8; i++) {
        sonarSensor[i] = robot.getSonarReading(i);
        sonarRange3[i] = sonarSensor[i]->getRange();

        }

Convertion from Integer to bool does not work (beginner)

Good evening, I am at the very start of c++ and I can´t understand why

int ival{1};
bool bval{ival};

does not work but

int ival = 1;
bool bval = ival;

works? Thanks for any hints or an answer!

Have a nice evening.

How to unify the Scoreboard class to have Team classes as members?

I want to be able to declare statements in int main() like:

Scoreboard s1; //assuming T1 and T2 as public members

s1.T1.setName("Dallas Cowboys");
s1.T2.setName("Houston Texans");

Scoreboard s2; //assuming T1 and T2 as private members passed as parameters accessed with setters and getters

s2.Team1().setName("Dallas Cowboys"); 
s2.Team2().setName("Houston Texans"); 

That what I have in my main but it currently throws an error of:

  • No member named T1 in scoreboard
  • No member named T2 in scoreboard

The second error comes from the second Scoreboard and throws exactly the same error but with the difference that instead of using T1, T2. It uses Team1(), Team2(). I tried changing their names to T1 & T2 but still its not working :/.

My scoreboard class pretty much just looks like this but I just can not figure out my problem:

class Scoreboard{
  private:
    Team T1;
    Team T2;
  public:
    Scoreboard(){
      T1.setName(""); 
      T2.setName(""); 
    }
    // Setters
    void setTeam1(Team team1) { T1 = team1; }
    void setTeam2(Team team2) { T2 = team2; }

    // Getters
    Team getTeamOne() const { return T1; }
    Team getTeamTwo() const { return T2; }
    // Print current data stored at Student on demand
    void showScoreboard(){
      cout << "SCOREBOARD CURRENT DATA" << endl;
      cout << "Team1                          Visitor" << endl;
      cout << " " << T1 << "\t\t\t\t\t\t\t\t" << T2 << endl;
    }
};

Do you guys have any idea of where my error comes from?

Handling of switch enum class returns in clang, gcc and icc consistently

I am generally using clang to develop code, using all reasonable warnings I can (-Wall -Wextra [-Wpedantic]). One of the nice things about this setup is that the compiler checks for the consistency of the switch stataments in relation to the enumeration used. For example in this code:

enum class E{e1, e2};

int fun(E e){
    switch(e){
        case E::e1: return 11;
        case E::e2: return 22; // if I forget this line, clang warns
    }
}

clang would complain (warn) if I omit either the e1 or the e2 case, and if there is no-default case.

<source>:4:12: warning: enumeration value 'e2' not handled in switch [-Wswitch]
    switch(e){

This behavior is great because

  1. it checks for consistency at compile time between enums and switches, making them a very useful and inseparable pair of features.
  2. I don't need to define an artificial default case for which I wouldn't have a good thing to do.
  3. It allows me to omit a global return for which I wouldn't have a good thing to return (sometimes the return is not a simple type like int, it could be a type without a default constructor for example.

(Note that I am using an enum class so I assume only valid cases, as an invalid case can only be generated by a nasty cast on the callers end.)

Now the bad news: Unfortunately this breaks down quickly when switching to other compilers. In GCC and Intel (icc) the above code warns (using the same flags) that I am not returning from a non-void function.

<source>: In function 'int fun(E)':
<source>:11:1: warning: control reaches end of non-void function [-Wreturn-type]
   11 | }
      | ^
Compiler returned: 0

The only solution I found for this working to both have a default case and return a non-sensical value.

int fun(E e){
    switch(e){
        case E::e1: return 11;
        case E::e2: return 22;
        default: return {}; // or int{} // needed by GCC and icc
    }
}

This is bad because of the reasons I stated above (and not even getting to the case where the return type has no default constructor). But it is also bad because I can forget again one of the enum cases and now clang will not complain because there is a default case.

So what I ended up doing is to have this ugly code that works on these compilers and warns when it can for the right reasons.

enum E{e1, e2};

int fun(E e){
    switch(e){
        case E::e1: return 11;
        case E::e2: return 22;
#ifndef __clang__    
        default: return {};
#endif
    }
}

or

int fun(E e){
    switch(e){
        case E::e1: return 11;
        case E::e2: return 22;
    }
#ifndef __clang__    
    return {};
#endif
}

Is there a better way to do this?

This is the example: https://godbolt.org/z/h5_HAs


In the case on non-default constructible classes I am really out of good options completely:

A fun(E e){
    switch(e){
        case E::e1: return A{11};
        case E::e2: return A{22};
    }
#ifndef __clang__
    return reinterpret_cast<A const&>(e);  // :P, because return A{} would be invalid
#endif
}

https://godbolt.org/z/3WC5v8

How can I find and display something in a data file?

#include <iostream>
#include <fstream>
#include <conio.h>
#include <iomanip>
#include <math.h>
#include <stdlib.h>

using namespace std;


int main()
{



int option, recordnum, count = 0;
float grosspay, hours, payrate, taxes, taxrate, netpay, taxp, payamount;
char firstname[10], lastname[10], employid[10], again = 'y';

do
{
    system("cls");
    cout << "Enter An Option.\n";
    cout << "1. Write new Records to the Data File.\n";
    cout << "2. Display Records from the Data File.\n";
    cout << "3. Find all records with a pay rate less than $ N dollar per hour.\n";
    cout << "4. Exit\n";
    cout << "What would you like to do?: ";
    cin >> option;
    option = fabs(option);

    if (option < 1 or option > 4)
    {
        system("cls");
        cout << "Enter An Option.\n";
        cout << "1. Write new Records to the Data File.\n";
        cout << "2. Display Records from the Data File.\n";
        cout << "3. Find all records with a pay rate less than $ N dollar per hour.\n";
        cout << "4. Exit\n";
        cout << "What would you like to do?: " << "\n";
        cin >> option;
    }

    system("cls");
    switch (option)
    {
    case 1:
    {   
        ofstream outFile("personnel.dat", ios::out | ios::app);
        outFile.precision(2);
        outFile.setf(ios::fixed);

        cout << "How Many Records Do You Want to Enter?: ";
        cin >> recordnum;
        recordnum = abs(recordnum);

        if (recordnum == 0)
            break;

        for (int count = 1; count <= recordnum; count++)
        {
            system("cls");
            cout << "Enter Employee's First Name: ";
            cin >> firstname;
            cout << "Enter Employee's Last Name: ";
            cin >> lastname;
            cout << "Enter Employee's ID #: ";
            cin >> employid;
            cout << "Enter Employee's Hours Worked: ";
            cin >> hours;
            hours = fabs(hours);
            cout << "Enter Employee's Pay Rate: ";
            cin >> payrate;
            payrate = fabs(payrate);
            cout << "Enter Employee's Tax Rate: ";
            cin >> taxrate;
            taxrate = fabs(taxrate);

            grosspay = hours * payrate;
            taxes = grosspay * taxrate;
            netpay = grosspay * taxes;

            outFile << firstname << " " << lastname << " " << employid << " " << hours << " " << payrate << " " << taxrate << " " << grosspay << " " << taxes << " " << netpay << " " << "\n";
        }
        outFile.close();
        break;
    }
    case 2:
    {
        ifstream inFile("personnel.dat", ios::in);
        inFile >> firstname >> lastname >> employid >> hours >> payrate >> taxrate >> grosspay >> taxes >> netpay;

        while (!inFile.eof())
        {
            count++;
            taxp = taxrate * 100;
            cout << "\n\n Record Number: " << count;
            cout << "\n\n First Name: " << firstname;
            cout << "\n\n Last Name: " << lastname;
            cout << "\n\n Employee's ID #: " << employid;
            cout << "\n\n Hours Worked: " << hours;
            cout << "\n\n Pay Rate: " << payrate;
            cout << "\n\n Gross Pay: $" << grosspay;
            cout << "\n\n Taxes: " << taxes;
            cout << "\n\n Net Pay: $" << netpay;
            cout << "\n\n Tax Rate: " << taxp << "%";
            inFile >> firstname >> lastname >> employid >> hours >> payrate >> taxrate >> grosspay >> taxes >> netpay;
        }

        cout << "\n\n Total Numbers of Files: " << count;
        inFile.close();
        count = 0;
        cout << "\n\n Press Any Keys to Continue...";
        getch();
        break;
    }
    case 3:
    {
        cout << "Enter the Pay Rate amount to Find All Employee's Pay Rate Less than: ";
        cin >> payamount;

        for (payamount = payamount; payamount <= payamount; payamount++)
        {

        }
    }
} while (again == 'y');

}

So for case 3, I have to find the pay amount that is less than the pay amount inputted and display it. But i also have to display everything along with that pay amount, ie the first name, last name, empid, etc. Would i need to do another inFile along with a for loop? or would I have to do something else?

Explanation why std::this_thread::sleep_for() sleep time differs between MSVC and MinGW-GCC?

Identifying the Problem

I was busy editing a library for lua bindings to rtmidi. I wanted to fix MinGW-GCC and LLVM/Clang compilation compability. When I was done making the edits and compiling the bindings, I noticed a weird timing issue caused by std::this_thread::sleep_for() when compared to MSVC.

I understand that there are bound to be some scheduling differences between different compilers, but in the following examples you can hear large timing issues:

  • MIDI playback using MSVC compiled bindings
  • MIDI playback using GCC compiled bindings

I have narrowed it down that this is the piece of code in question:

lua_pushliteral(L, "sleep");
lua_pushcfunction(L, [] (lua_State *L) {
    auto s = std::chrono::duration<lua_Number>(luaL_checknumber(L, 1));
    std::this_thread::sleep_for(s);
    return 0;
});
lua_rawset(L, -3);

Obviously it's about these two lines:

auto s = std::chrono::duration<lua_Number>(luaL_checknumber(L, 1));
std::this_thread::sleep_for(s);

The average waiting time that is passed to sleep_for() is around 0.01s, with some calls here and there between 0.002s - 0.005s.

Troubleshooting

First off I have checked whether the problem was present with my current version of GCC (9.2.0) by using a different version and even using LLVM/Clang. Both GCC 8.1.0 and LLVM/Clang 9.0.0 yield the same results.

At this point I can conclude there is some weird scheduling going on with the winpthreads runtime, since they depend on it and MSVC does not.

After that I tried to switch out the code with the Windows Sleep() call. I had to multiply by 1000 to adjust for the correct timing.

Sleep(luaL_checknumber(L, 1) * 1000);

As I expected, the timing issue is not present here; this indeed confirms that winpthreads is the culprit here.

Obviously I do not want to make calls to Windows Sleep() and keep using sleep_for().

The Questions

So based on what I gathered I have the following questions:

  • Is winpthread indeed the culprit? Am I perhaps missing some compiler defines that would solve the problem?
  • If winpthreads is indeed the culprit, why are the timing differences so big?
  • If there is no compiler define 'fix', what would you recommend to do tackle the problem?

To partially answer the third question (if it may come to it), I was thinking of doing something like:

#ifdef _WIN32 && MINGW
    #include <windows.h>
#endif

...

#ifdef _WIN32 && MINGW
    Sleep(luaL_checknumber(L, 1) * 1000);
#elif _WIN32 && MSVC
    auto s = std::chrono::duration<lua_Number>(luaL_checknumber(L, 1));
    std::this_thread::sleep_for(s);
#endif

Of course the problem arises that Window's Sleep() call is less precise (or so I've read).

What is the correct way to call this method?

I'm trying to understand placeholders but i can't call this method. I have an implicit parameters Dummy{}, float and LastDummy{}. When i call function i skip these parameters. Also my call doesn't work.

struct AnotherDummy {};
struct YetAnotherDummy {};
struct LastDummy {};

class X { public:
    void foo(std::string one, Dummy two, int three, AnotherDummy four, 
             float five, YetAnotherDummy six, double seven, int eight, LastDummy nine)
    {

    }
};

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

    auto functor = std::bind(&X::foo, _6, _3, Dummy{}, _5, _1, 5.0f, _4, _2, _7, LastDummy{});

    X obj;
    functor(&obj, YetAnotherDummy{}, 1, 2.3f, 'x', AnotherDummy{}, Dummy{}, 2.3);

    return 0;
}

Undefined behaviour during compile time and run time

I still can't pinpoint exactly on which level undefined behaviour is actually defined. Assume the following code:

int i = value;
unsigned int x = static_cast<unsigned int>(i);

This is valid C++ code and defined if e.g. i is 1. But on i = -1 it becomes undefined behaviour, so the application is in UB state during runtime.

In the code smell below UB is already apparent during compile time. So my question is, is it correct that UB can be either during compile time or runtime? What is the right terminology here?

void foo(int* p)
{
    int v = *p;
    if (p == nullptr)
        return;
}

Call to lambda is ambiguous despite explicitly stating the return type

An overloaded function should take both functors in, given the type of the lambda is decidable ( castable to an std::function (please correct me if I'm wrong ). The question is: Why is there a compile error below, despite the lambda type being explicitly defined? ( & -> Type {} )

Please note, that for my current solution I need the capture-by-reference, that's why the code contains the logic for it.

The following example describes the problem:

#include <iostream>
#include <string>

#include <functional>

void do_some(std::function<void(int)> thing){
    thing(5);
}

void do_some(std::function<bool(int)> thing){
    if(thing(10)){
        std::cout << "it's true!" <<std::endl;
    }
}

int main()
{
    int local_to_be_modified = 0;
    do_some([&](int in){
        local_to_be_modified = in;
        std::cout << "This is void-" <<std::endl;
    });
    do_some([&](int in) -> bool{ // error: call to 'do_some' is ambiguous
        local_to_be_modified += in;
        std::cout << "This is bool-" <<std::endl;
        return true;
    });
}

returning a class from a metod gives wrong values for class variables

My header file contains a class that holds a Boolean and a string

#ifndef RESULT_P
#define RESULT_P

#include <string>
#include <utility>

class MyResult {

public:
    MyResult() = default;
    MyResult( const bool& ok, std::string  msg) : ok_(ok), msg_(std::move(msg)) {}
    explicit MyResult(bool ok) : ok_(ok) {}
    explicit MyResult(std::string msg) : ok_(false), msg_(std::move(msg)) {}

    bool ok() const {
        return ok_;
    }

    void ok(bool ok) {
        ok_ = ok;
    }

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

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

private:
    bool ok_ { false };
    std::string msg_;

};

#endif

I am using the MyResult(std::string) constructor to create a result that takes by default false on the ok_ method variable.

I am calling

auto result = do_something()

The method do somethings looks like this

   MyResult do_something() {

      if ( something ) {
         //code    } else {
          return MyResult("something wrong happened");    
      }
    }

So returns false and a string. When this method returns and I am calling

cout << result.ok() << endl;

it prints false!!! instead of true. What is wrong?

Is calling a small function twice (e.g. in if condition and boby) preferable than storing result in local variable?

Which of the two options below is better (or preferable), and why ?

ReturnType *function1(const ParamType *param) {
  const ValueType* value = getSomeValue(param);
  if (value) {
     return value->finalStuff();
  }
  return nullptr;
}

VS

ReturnType *function2(const ParamType *param) {
  if (getSomeValue(param)) {
     return getSomeValue(param)->finalStuff();
  }
  return nullptr;
}

Given getSomeValue like :

ValueType * getSomeValue(const ParamType *param) {
    if (param) {
        return param->some.very.boring.stuff.value;
    }
    return nullptr;
}

Any better option ? Thanks

How to display copies of images captured by OpenCV VideoCapture correctly

I am trying to use the OpenCV VideoCapture class to read images sequentially from a specific folder, as shown in the code below, which is extracted from https://www.kevinhughes.ca/tutorials/reading-image-sequences-with-opencv. The reading works just fine and I can view the video streaming of the read images (imgSrc) correctly. The problem happens when I try to copy each frame into a new Mat object using nested for loops, the new image (imgDst) is different from the original one. I attached the results of the frame below ? Is there anything I am doing wrong so that I get this weird result?

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace cv;
using namespace std;

void help(char** argv)
{
cout << "\nThis program gets you started reading a sequence of images using cv::VideoCapture.\n"
     << "Image sequences are a common way to distribute video data sets for computer vision.\n"
     << "Usage: " << argv[0] << " <path to the first image in the sequence>\n"
     << "example: " << argv[0] << " right%%02d.jpg\n"
     << "q,Q,esc -- quit\n"
     << "\tThis is a starter sample, to get you up and going in a copy paste fashion\n"
     << endl;
}

int main(int argc, char** argv)
{
if(argc != 2)
{
  help(argv);
  return 1;
}

string arg = argv[1];
VideoCapture sequence(arg);
if (!sequence.isOpened())
{
  cerr << "Failed to open Image Sequence!\n" << endl;
  return 1;
}

Mat imgSrc; // source image
for(;;)
{
  sequence >> imgSrc;

if(imgSrc.empty())
  {
      cout << "End of Sequence" << endl;
      break;
  }
  Mat imgDst = cv::Mat::zeros(cv::Size(imgSrc.size().width,imgSrc.size().height),CV_16U);


  // Copying the elements of imgSrc to imgDst
  uint16_t* imgSrcPtr;
  uint16_t* imgDstPtr;
  for(int i = 0; i < imgSrc.rows; i++)
  {
      imgDstPtr = imgDst.ptr<uint16_t>(i);
      imgSrcPtr = imgSrc.ptr<uint16_t>(i);

       for(int j= 0; j < imgSrc.cols; j++)
       imgDstPtr[j] = imgSrcPtr[j];
  }

  namedWindow("Source image ",WINDOW_AUTOSIZE );

  namedWindow("Destination image ",WINDOW_AUTOSIZE );
  imshow("Destination image ", imgDst);
  waitKey(0;

return 0;
}

Source image Destination image

Can I std::forward the arguments in fold expression?

In C++11 we have variadic templates, in which we can std::forward the arguments like in the following code

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

void printVariadic()
{}
template<typename T, typename... Args>
void printVariadic(T&& arg, Args&&... args)
{
   std::cout << arg << "\n";
   printVariadic(std::forward<Args>(args)...); // here we forward the arguments
}

But, in C++17 we have fold expression (and from my understanding it doesn't make recurive function call until last argument).

template<typename ... Args>
void print(Args ... args)
{
    ((cout << args << "\n"), ...); // did we here miss the part of `std::forward`?
}

In the online examples, I couldn't see a std::forward ing of the arguments, when fold expression has used.

Can I forward the arguments in fold expression? Or don't we need it at all?

It might a dumb beginner qestion, still I couldn't find an answer in online.

How to iterate through range based for loop with variable end point

I'm trying to use a range based for loop to iterate from the beginning of a vector to a variable destination x as shown.

void algorithm(vector<int>, int n)
{
int count=0;
for (int i:arr[n])
count++;
}

I understand the above function is rather useless but I'm trying to conceptually understand if there is a way to do so. arr[n] gives me an error as does arr.begin()+n

Can not construct a class from std::function when used inside std::vector

I want to have an std:array of std::function, but I want to make sure that all elements of the array are initialized. For that end I built a wrapper class that takes an std::function as a construction parameter.

But when I initialize an array of my wrapper class directly with my function (the one who should be inside std::function) it fails to compile.

Here is the problem, distilled:

#include <functional>
#include <array>

static void f() {}
using F = std::function<void(void)>;
enum { Count = 4 };

struct C
{
    //To get a compilation error when some
    //  elements of the array are not initialized.
    C() = delete;

    C(F) {}
};

//OK
static const C c {f};

//OK
static const std::array<F,Count> direct
{
    F{f},
    {f},
    f,
    f
};

static const std::array<C,Count> wrapper
{
    F{f},   //OK
    C{f},   //OK
    {f},    //OK
    f       //could not convert 'f' from 'void()' to 'C'
};

I tried changing the array to an std::vector<C> (although it defeats my whole purpose of using an std:array to begin with) and it refuses to compile any of the above initializations.

What will cause the data members in class initialized to zeros?

Default constructor shouldn't zero out any data member. But in some situation, it seems not to be like this.

The code example is brief.

#include <iostream>

using namespace std;

class Foo {
public:
  int val;
  Foo() = default;
};

int main() {
  Foo bar;
  if (bar.val != 0) {
    cout << "true" << endl;
  } else {
    cout << "false" << endl;
  }
  return 0;
}

As excepted, above program outputs:

true

However, if a print statement for bar's data member added, the var member will be initialized to zero:

...
int main() {
  Foo bar;
  cout << bar.val << endl;
  ...
}

The outputs will be:

0
false

Similarly, if adding virtual function and destructor to the class Foo:

#include <iostream>

using namespace std;

class Foo {
public:
  virtual void Print() {}
  ~Foo() {}
  int val;
  Foo() = default;
};

int main() {
  Foo bar;
  if (bar.val != 0) {
    cout << "true" << endl;
  } else {
    cout << "false" << endl;
  }
  return 0;
}

Also

false

So what‘s the cause that influence the data member value of class? Shouldn't all of this test outputs with true?

mardi 29 octobre 2019

Modern C++ makes memory leaks harder to find

How are you supposed to test modern C++ for memory leaks?

Out unit test cases typically look like this:

TestCase {
  Instantiate testObject
  testObject->AllocateSomeResources
  testObject->PerformATest
  testObject->DeallocateResources
  Destroy testObject
}

We use valgrind for detecting memory leaks. This is very effective if the resource allocation is done with new and delete, but when the resources are stored as smart pointers inside standard containers, the automatic cleanup at testObject destruction prevents us from finding faults.

When the system is live. resource containers may grow over time due to a faulty deallocation procedure. This would have been trivial to find if the allocation was done with new and delete.

Are there any techniques that will remedy this aspect of modern C++?

Ideas:

  • Make all destructors test for allocated resources. This would impact the production code base quite a bit.
  • Create more separated and testable allocation and deallocation procedures. Of course, but since we got alot of this "for free" with more traditional C++, i still would like to find alternatives.

Obviously i see a benefit in standard containers and smart pointers, sorry about the click bait header

Infinite do-while loop in c++

This function displayMenu() is being called in Main under the condition while(menuChoice != Q), but the function itself has an internal infinite loop. Any help on why the loop in the display menu function is infinite would be great... I think it may be something to do with the do-while structure or the relational operator != working improperly.

FUNCTION DISPLAYMENU:
char displayMenu()
{
// can be useful info during development
cout << "Entered function displayMenu..." << endl;

char whatToDo = '?';


do {
    //Display Menu Options
    cout <<"Upload a regional sales data file \tU" <<endl;
    cout <<"display details (All loaded data) \tA" <<endl;
    cout <<"list details for specific Order number \tO" <<endl;
    cout <<"display summary by Region \tR" <<endl;
    cout <<"display summary by print method \tM" <<endl;
    cout <<"Clear all data \tC" <<endl;
    cout <<"Quit \tQ" <<endl;
    cout <<"\nPlease Enter Your Menu Choice: " <<endl;
    cin >> whatToDo;
} while (whatToDo != 'U' ||
         whatToDo != 'A' ||
         whatToDo != 'O' ||
         whatToDo != 'R' ||
         whatToDo != 'M' ||
         whatToDo != 'C' ||
         whatToDo != 'Q');

// can be useful info during development
cout << "Returning " << whatToDo << " from displayMenu..." << endl;

return whatToDo;

} // END function displayMenu()


FUNCTION MAIN 
while (menuChoice != 'Q'){
    menuChoice = displayMenu();
}

Performing function on variable by referance vs setting variable equal to function outcome

Below is some general code that accomplishes the same task and requires relatively the same amount of typing. It is my understand that the first method initializes the variable directly to desired output while the second first creates a variable initialized to null and later changes it. Does this mean the first method runs faster? Additionally is there any reason why I would use one method over another?

int main()
{int x=foo(2);}

int foo(x)
{return x*x;}

vs

int main()
{int x;
foo(x);}

void foo(&x)
{x*x}

Why does make_shared allocate same address in separate calls?

Why does this make_shared allocate the same memory address in two separate calls?

typedef struct {
    int a;
    int b;
    int c;
} test_t;

void call_func()
{
    std::shared_ptr<test_t> tst = std::make_shared<test_t>();

    std::cout << "addr: " << tst << std::endl;
}

int main()
{
    call_func();
    call_func();
}

Here it is online: http://coliru.stacked-crooked.com/a/ffc92bc131009402

Can I store an iterator after inserting a pair in a set, and later use that iterator to remove the pair in the set?

I have a class with two methods. Always Method1 is called, so the pair (value, index) is always stored in the ending_points set. In some cases, I need to call the Method2 and remove the iterator from the inserted pair. However, when I call Method2 the program crashes.

class TheClass: public ParentClass {
        public:
            TheClass(int value, int index, std::set<std::pair<int,int>>* const ending_points)
                : value_(value), index_(index), ending_points_(ending_points) {}
            ~TheClass() {}

            void Method1() {
                last_inserted_ = ending_points_->insert(std::make_pair(value_, index_)).first;
            }

            void Method2() {
                ending_points_->erase(last_inserted_);
            }

        private:
          int value_;
          int index_;
          std::set<std::pair<int64,int64>>::iterator last_inserted_;
          std::set<std::pair<int64,int64>>* const ending_points_;
    };      

I will really appreciate your help.

C++ primr 5 edition. unique_ptr constructor from custom deleter function

On C++ primer 5 edition. Chapter 12. Dynamic memory. The table that shows std::unique_ptr operations:

unique_ptr<T, D> u2 Null unique_ptrs that can point to objects of type T. u2 will use a callable object of type D in place of delete to free its pointer.

unique_ptr<T, D> u(d) Null unique_ptr that points to objects of type T that uses d, which must be an object of type D in place of delete.

But if I try to create one like this:

void cust_del(std::string* pStr){
     std::cout << *pStr + " destroying..." << std::endl;
     delete pStr;
}

int main(){


    {// new scope
    std::unique_ptr<std::string, void(*)(std::string*)> u(cust_del); // error

    std::unique_ptr<std::string, void(*)(std::string*)> u(new string("Hello unique!"), cust_del); // ok
    // or
    // std::unique_ptr<std::string, decltype(&cust_del)> u(new string("Hello unique!"), cust_del);

    }

}

So as I can see it is possible to construct a unique_ptr just from the custom delete function.

  • One last point: it is said there:

Unlike shared_ptr, there is no library function comparable to make_shared that returns a unique_ptr. Instead, when we define a unique_ptr, we bind it to a pointer returned by new. As with shared_ptrs, we must use the direct form of initialization:

But there is std::make_unique. Is this because make_uniqueis added by C++14 and the book has been rewritten for C++11?

Why does `constexpr` constant produce linker error? [duplicate]

Using gcc 9.2.1, I get a strange linker error with this code. When I compile with this line:

g++ -std=c++11 -Wall -Wextra -pedantic foo.cpp -o foo

I get this error:

/usr/bin/ld: /tmp/ccLjChns.o: in function `Foo::Foo()':
foo.cpp:(.text._ZN3FooC2Ev[_ZN3FooC5Ev]+0x11): undefined reference to `Foo::empty'
collect2: error: ld returned 1 exit status

If I change the contents of the constructor to board.fill('x');, however, everything works just fine.

I think this is because fill wants a reference instead of a value passed, but I'm not sure how to fix this while still using the named constant. Note that I'm using C++11 and not C++20, so I can't use the constexpr form of std::array::fill. I also wasn't able to figure out a way to use aggregate initialization or list initialization that uses both side and empty.

I know I could create a custom char class and assign a default initializer, but that seems inelegant and overly verbose.

foo.cpp

#include <iostream>
#include <algorithm>
#include <iterator>
#include <array>

class Foo {
public:
    Foo() { board.fill(empty); }
    friend std::ostream& operator<<(std::ostream& out, const Foo& foo);
private:
    static constexpr unsigned side{3};
    static constexpr char empty{'x'};
    std::array<char, side*side> board;
};

std::ostream& operator<<(std::ostream& out, const Foo& foo) {
    std::copy(std::begin(foo.board), std::end(foo.board), std::ostream_iterator<char>{out, ","});
    return out;
}

int main()
{
    Foo foo;
    std::cout << foo;
}

Why is reference type a lvalue when accessed with temporary object

Why assigning a value to a reference variable being accessed using temporary object works but not for non reference type?

class a
{
    public:
        int m;
        int &n;
        a():m(2),n(m)
        {
            cout<< "A's constructor"<<endl;
        }
};

int main()
{
    // a().m = 6; // this gives an error that temporary object being used 
                  // as lvalue
    a().n = 20;   // But this line works

    return 0;
}

What can possible use of making a class friend and inheriting it also?

I was going through one of my local libraries and noticed the follwowing:

class Derived : public Base
{
        friend class Base; // serves as a factory
    protected:
        pthread_spinlock_t allocLock;
        bool isSafe{ true };

        Derived();
        char *funcA() override;

    public:
        void funcB( bool _in ) override;
        virtual ~Derived();
};

I am not able to understand if Base has been inherited then why it has been made a friend of Derived. Also how the comment serves as a factory make sense here?

If it were to access Base function, :: operator would have been sufficient.

Is it more related to Design approach?

Inherit from classes passed to constructor as a template parameters an inherit from them

I want to have something like that:

template<class... Args>
class MyClass : public Args
{
    MyClass<class... Args>(/*some parameters*/)
    { }
}

// ana then:
MyClass<Base1, Base2, Base3>(/*some arguments*/)

That i want to dynamic_cast to Base1 or etc. and to use his methods.

I know that this code will not work, but do you have any ideas how to do it?

C++ pass parameter pack to std::map results in error C3245

I try to call functions hold in a map (to achieve reflection), with passed arguments as parameter pack which might look a bit strange... I want to get it to run anyway. Currently I end up with the following error:

main.cpp(36): error C3245: 'funcMapA': use of a variable template requires template argument list
main.cpp(23): note: see declaration of 'funcMapA'

Here is my minimum (not)working example:

#include <functional>
#include <map>
#include <string>
#include <sstream>
#include <iostream>
#include <iterator>
#include <vector>
#include <utility>

void DoStuff_1(int i) {
  std::cout << "DoStuff_1 " << i << "\n";
}

void DoStuff_2(int i, int k) {
  std::cout << "DoStuff_2 " << i << ", " << k << "\n";
}

void DoStuff_3(int i, int k, int l) {
  std::cout << "DoStuff_3 " << i << ", " << k << ", " << l << "\n";
}

template <typename ... Ts>
std::map<std::string, std::function<void(Ts&& ... args)>> funcMapA = {
  {"DoStuff_1", [](Ts&& ... args) {DoStuff_1(std::forward<Ts>(args)...); }},
  {"DoStuff_2", [](Ts&& ... args) {DoStuff_2(std::forward<Ts>(args)...); }},
  {"DoStuff_3", [](Ts&& ... args) {DoStuff_3(std::forward<Ts>(args)...); }}
};

std::map<std::string, std::function<void(int, int, int)>> funcMapB = {
  {"DoStuff_1", [](int x, int y, int z) {DoStuff_1(x); }},
  {"DoStuff_2", [](int x, int y, int z) {DoStuff_2(x, y); }},
  {"DoStuff_3", [](int x, int y, int z) {DoStuff_3(x, y, z); }}
};

int main(int argc, char** argv) {
  funcMapA["DoStuff_" + std::to_string(3)](1, 2, 3); //Failing
  funcMapB["DoStuff_" + std::to_string(3)](1, 2, 3); //Working
  getchar();
  return 0;
}

Questions: 1. How can I get this (funcMapA) to work?

Cheers Bob

property_tree get array value as String

I want to parse a json file/string with boosts property_tree, but instead of having sub-trees parsed into an array I would like it to stay as a string for use in another existing function which only deals with json-Strings.

I hope the following example is sufficient:


example.json

{
    "type": "myType",
    "colors": {
        "color0":"red",
        "color1":"green",
        "color2":"blue"
    }
}

main.cpp

std::stringstream ss("example.json");
ptree pt;
read_json(ss, pt);

std::string sType = pt.get("type", "");
std::string sColors = pt.get<std::string>("colors");

std::cout << "sType: " << sType << std::endl; // sType: myType
std::cout << "sColors: " << sColors << std::endl; // sColors: {"color0":"red", "color1":"green", "color2":"blue"}

I've tried several functions, for example pt.get_child("colors") would just return another ptree and pt.get_value<std::string>("colors") does return an empty string ("").

The desired output would look like this:

sColors: {"color0":"red", "color1":"green", "color2":"blue"}

or

sColors: {\"color0\":\"red\", \"color1\":\"green\", \"color2\":\"blue\"}

Is there a way to recive the desired output for sColors?

Is it legal to return a deference of newly allocated shared_ptr in a function return?

Is this code ok? I know that the reference counter is getting down to zero after the function returns, so the memory should be freed. But it works and prints the dereference successfully outside the function.

Can someone please explain if what I am trying to do is wrong or not, and why? Thanks

#include <iostream>
#include <memory>
#include <string>

std::string& get_string(bool en)
{ 
  return *std::make_shared<std::string>("hello world");
}

int main () {
  auto& my_str = get_string(true);
  std::cout << "str=" << my_str <<std::endl;
  return 0;
}

output:

> ./main
str=hello world

Does std::string in c++ has encoding format

I want to find the default encoding format about std:: string.
I am trying to find out the encoding format, but I have no idea. Does std:: string in c++ has encoding format ?

Inherited from qthread class doesn't work with queued connection

I wrote simple class of smart container for producer consumer approach. Data in container are added by posix thread via callBack, after it my thread is awakening and parse all received messages. The main problem is that my thread calling method of other QObject subclass where signal emmiting are exists, the main problem that after signal emmiting, slot doesn't receive a message only direct connection are work.

   #ifndef SHAREDCONTAINEREXTERNAL_H
#define SHAREDCONTAINEREXTERNAL_H
#include <QThread>
#include <QWaitCondition>
#include <QMutex>
#include <QQueue>
#include <QObject>

class Device;

class SharedContainerExternal : public QThread
{
    Q_OBJECT
public:
    explicit SharedContainerExternal(QObject* parent = nullptr);
    ~SharedContainerExternal()override;
    void setRawMessage(const QJsonObject& _message);
    void setConsumerObject(Device* _consumer);
    void consumerRead();

protected:
    void run() override;

private:
    QMutex mtx;
    QWaitCondition cv;
    QQueue<QJsonObject> messages;
    Device* consumer;
    bool canAccomplish;
};


#include "sharedcontainerexternal.h"
#include "device.h"

SharedContainerExternal::SharedContainerExternal(QObject* parent) : QThread (parent)
{
    canAccomplish = false;
}

SharedContainerExternal::~SharedContainerExternal()
{
    mtx.lock();
    canAccomplish = true;
    cv.notify_all();
    mtx.unlock();
    wait();
}

void SharedContainerExternal::setRawMessage(const QJsonObject &_message)
{
    mtx.lock();
    messages.push_back(_message);
    cv.wakeAll();
    mtx.unlock();
}

void SharedContainerExternal::run()
{
    while(!canAccomplish){
        mtx.lock();
        if(messages.isEmpty() && !canAccomplish)
            cv.wait(&mtx);
        consumerRead();
        mtx.unlock();
    }
}

void SharedContainerExternal::setConsumerObject(Device *_consumer)
{
    consumer = _consumer;
}

void SharedContainerExternal::consumerRead()
{
    while(!messages.isEmpty()){
        consumer->getDriverMessage(messages.front());
        messages.pop_front();
    }
}

So after in driver class I have emit a signal.

void Device::getDriverMessage(const QJsonObject& _message)
{
    emit sendCallBackMessage(_message);
}

And in mainwindow class I have a connect, but signal doesn't received via slot, device is a field of class mainwindow.

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    fields[LinkAgentType] = TypeOfConnection::EXTERNAL;
    fields[PathToDriver] = "C:/Users/user/Desktop/RouterCpp/RouterCore/build-Driver101-104-Desktop_Qt_5_13_0_MinGW_32_bit-Debug/debug/Driver101-104";
    fields[IpAddr] = "127.0.0.1";
    fields[Port] = 2404;
    fields[TypeOfDevice] = TypeOfDevice::External;
    fields[TypeOfMessage] = TypeOfMessage::Service;
    fields[ConnectionState] = ConnectState::On;

    /*Prepare parameters for the jsonObject*/
    builder = new DeviceBuilder(this);
    builder->setConstructorStructure(fields);
    device = builder->getDeviceObject();
    device->setMessage(fields);

    connect(device.get(),&Device::sendCallBackMessage,
            this,&MainWindow::callBackMessageSlot,Qt::QueuedConnection);


}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::callBackMessageSlot(QJsonObject _data)
{
    qDebug()<<_data;
}

Cpp reference.com did not use typename for following case, why?

I have been reading about removing reference of the type, here

I saw the following code in the link

#include <iostream> // std::cout
#include <type_traits> // std::is_same

template<class T1, class T2>
void print_is_same() {
  std::cout << std::is_same<T1, T2>() << '\n';
}

int main() {
  std::cout << std::boolalpha;

  print_is_same<int, int>();
  print_is_same<int, int &>();
  print_is_same<int, int &&>();

  print_is_same<int, std::remove_reference<int>::type>(); // Why not typename std::remove_reference<int>::type ?
  print_is_same<int, std::remove_reference<int &>::type>();// Why not typename std::remove_reference<int &>::type ?
  print_is_same<int, std::remove_reference<int &&>::type>();// Why not typename std::remove_reference<int &&>::type ?
}

The type 's in std::remove_reference traits are dependednt type.

Possible implementation

template< class T > struct remove_reference      {typedef T type;};
template< class T > struct remove_reference<T&>  {typedef T type;};
template< class T > struct remove_reference<T&&> {typedef T type;};

But why it has not been used typename std::remove_reference</*TYPE*/>::type?

Minimum number of supernodes such that all other nodes are connected by supernodes

Let's say I have graph, in that graph I have to mark some nodes as supernodes such that all other nodes can have direct access this supernodes (nodes which are supernodes have access to it's own).

Nodes

Let's say based on image my supernodes are 1,3,5 as all other nodes are connected by it.

My question is how to find minimum number of such supernode?

Thanks.

having problems when using PCLVisualizer to display polygons

I'd like to use addpolygon() to show planar patches extracted from point clouds. A certain polygon surface can only display at a certain viewpoint, but after some rotation it will disappear. I also tried to use addplane() and got the same result.

pcl::visualization::PCLVisualizer pViewer("planes");

pViewer.addCoordinateSystem (1.0);

Eigen::Vector4f planarCoeff(p.plane.normal()(0), p.plane.normal()(1), p.plane.normal()(2), p.plane.offset());

pcl::PlanarPolygonpcl::PointXYZ planeHull(hull.points, planarCoeff);

std::string planeName = "polygon";

pViewer.addPolygonpcl::PointXYZ(hull.makeShared(), dist(rd)%255, dist(rd)%255, dist(rd)%255, planeName);

pViewer.setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_REPRESENTATION, pcl::visualization::PCL_VISUALIZER_REPRESENTATION_SURFACE, planeName);

pViewer.setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_OPACITY, 1.0, planeName);

How to parse icu::UnicodeString to an Integer or Float in ICU4C C++11?

How should I parse a icu::UnicodeString string to an integer or float number in ICU4C C++11 ?

Is there a mature API, or I must implement my own number parser?

How to determine number of values added to vector in C++?

I'm trying to build a little task using C++ in which I need to allow the user to determine up front how many gross_paychecks they would like to place in a vector called 'gross_paychecks_vector'.

So far this is what I have:

vector<double> gross_paychecks_vector (5);
  double gross_paychecks;
  // Add 5 doubles to vector
  cout << "Please enter an integer" << endl;
  cin >> gross_paychecks;
  for(gross_paychecks = 0; gross_paychecks <= gross_paychecks_vector; ++gross_paychecks ){
    cin >> gross_paychecks;
  }

Right now I'm somewhat lost because I'm not sure whether to switch the vector to something like vector<double> gross_paychecks {} because it trows me an error in the for loop.

Also I'm not sure how to go with the for loop(should I actually use a for-loop or something else?). I need to accept input from the user as long as it has not met the numbers of gross_paychecks that he/she has specified.

lundi 28 octobre 2019

How to delete a string based on spaces

I have a std::string I want to keep the string after two spaces like in Newa and Newb

   String a = "Command send SET  Command comes here";
   String b = "Command GET  Command comes here"; 

   string Newa = "SET  Command comes here";
    string Newb = "Command comes here";

what comes to my mind is that i can do std::string::find(' ') two times and use std::string::substr to get the desired result.

Can we do it in more refined manner.

How to create STL map of set where set uses a comparator

My issue is simple, I want to have a map of set where the set uses lambda comparator

auto comp = [](const int& i, const int& j) {
    return i < j;
};

map<int, set<int>> map1;
map<int, set<int, decltype(comp)>> map2;

set<int, decltype(comp)> set1(comp);      // works fine
map1[0] = set<int>();                     // works fine
map2[0] = set<int, decltype(comp)>(comp); // compile error

There is some syntax which is wrong which I don't know nor I could find any resource on web which is doing what I want to do

The compiler error is a very long message which I pasted below for the complete picture.

In file included from a.cpp:1:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/set:458:19: error: no matching constructor for initialization of 'std::__1::set<int, (lambda at a.cpp:8:17), std::__1::allocator<int> >::value_compare' (aka '(lambda at a.cpp:8:17)')
        : __tree_(value_compare()) {}
                  ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/tuple:1360:7: note: in instantiation of member function 'std::__1::set<int, (lambda at a.cpp:8:17), std::__1::allocator<int> >::set' requested here
      second(_VSTD::forward<_Args2>(_VSTD::get<_I2>(__second_args))...)
      ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/utility:509:11: note: in instantiation of function template specialization 'std::__1::pair<const int, std::__1::set<int, (lambda at a.cpp:8:17), std::__1::allocator<int> > >::pair<int &&, 0>' requested here
        : pair(__pc, __first_args, __second_args,
          ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/memory:1825:31: note: in instantiation of function template specialization 'std::__1::pair<const int, std::__1::set<int, (lambda at a.cpp:8:17), std::__1::allocator<int> > >::pair<int &&>' requested here
            ::new((void*)__p) _Up(_VSTD::forward<_Args>(__args)...);
                              ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/memory:1717:18: note: in instantiation of function template specialization 'std::__1::allocator<std::__1::__tree_node<std::__1::__value_type<int, std::__1::set<int, (lambda at a.cpp:8:17), std::__1::allocator<int> > >, void *> >::construct<std::__1::pair<const int, std::__1::set<int, (lambda at a.cpp:8:17), std::__1::allocator<int> > >, const std::__1::piecewise_construct_t &, std::__1::tuple<int &&>, std::__1::tuple<> >' requested here
            {__a.construct(__p, _VSTD::forward<_Args>(__args)...);}
                 ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/memory:1560:14: note: in instantiation of function template specialization 'std::__1::allocator_traits<std::__1::allocator<std::__1::__tree_node<std::__1::__value_type<int, std::__1::set<int, (lambda at a.cpp:8:17), std::__1::allocator<int> > >, void *> > >::__construct<std::__1::pair<const int, std::__1::set<int, (lambda at a.cpp:8:17), std::__1::allocator<int> > >, const std::__1::piecewise_construct_t &, std::__1::tuple<int &&>, std::__1::tuple<> >' requested here
            {__construct(__has_construct<allocator_type, _Tp*, _Args...>(),
             ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/__tree:2202:20: note: in instantiation of function template specialization 'std::__1::allocator_traits<std::__1::allocator<std::__1::__tree_node<std::__1::__value_type<int, std::__1::set<int, (lambda at a.cpp:8:17), std::__1::allocator<int> > >, void *> > >::construct<std::__1::pair<const int, std::__1::set<int, (lambda at a.cpp:8:17), std::__1::allocator<int> > >, const std::__1::piecewise_construct_t &, std::__1::tuple<int &&>, std::__1::tuple<> >' requested here
    __node_traits::construct(__na, _NodeTypes::__get_ptr(__h->__value_), _VSTD::forward<_Args>(__args)...);
                   ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/__tree:2147:29: note: in instantiation of function template specialization 'std::__1::__tree<std::__1::__value_type<int, std::__1::set<int, (lambda at a.cpp:8:17), std::__1::allocator<int> > >, std::__1::__map_value_compare<int, std::__1::__value_type<int, std::__1::set<int, (lambda at a.cpp:8:17), std::__1::allocator<int> > >, std::__1::less<int>, true>, std::__1::allocator<std::__1::__value_type<int, std::__1::set<int, (lambda at a.cpp:8:17), std::__1::allocator<int> > > > >::__construct_node<const std::__1::piecewise_construct_t &, std::__1::tuple<int &&>, std::__1::tuple<> >' requested here
        __node_holder __h = __construct_node(_VSTD::forward<_Args>(__args)...);
                            ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/map:1431:20: note: in instantiation of function template specialization 'std::__1::__tree<std::__1::__value_type<int, std::__1::set<int, (lambda at a.cpp:8:17), std::__1::allocator<int> > >, std::__1::__map_value_compare<int, std::__1::__value_type<int, std::__1::set<int, (lambda at a.cpp:8:17), std::__1::allocator<int> > >, std::__1::less<int>, true>, std::__1::allocator<std::__1::__value_type<int, std::__1::set<int, (lambda at a.cpp:8:17), std::__1::allocator<int> > > > >::__emplace_unique_key_args<int, const std::__1::piecewise_construct_t &, std::__1::tuple<int &&>, std::__1::tuple<> >' requested here
    return __tree_.__emplace_unique_key_args(__k,
                   ^
a.cpp:17:9: note: in instantiation of member function 'std::__1::map<int, std::__1::set<int, (lambda at a.cpp:8:17), std::__1::allocator<int> >, std::__1::less<int>, std::__1::allocator<std::__1::pair<const int, std::__1::set<int, (lambda at a.cpp:8:17), std::__1::allocator<int> > > > >::operator[]' requested here
    map2[0] = set<int, decltype(comp)>(comp);
        ^
a.cpp:8:17: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 0 were provided
    auto comp = [](const int& i, const int& j) {
                ^
a.cpp:8:17: note: candidate constructor (the implicit move constructor) not viable: requires 1 argument, but 0 were provided
In file included from a.cpp:1:
In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/set:402:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/__tree:1752:14: error: object of type 'std::__1::__compressed_pair<unsigned long, (lambda at a.cpp:8:17)>' cannot be assigned because its copy assignment operator is implicitly deleted
    __pair3_ = _VSTD::move(__t.__pair3_);
             ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/__tree:1819:5: note: in instantiation of member function 'std::__1::__tree<int, (lambda at a.cpp:8:17), std::__1::allocator<int> >::__move_assign' requested here
    __move_assign(__t, integral_constant<bool,
    ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/set:562:21: note: in instantiation of member function 'std::__1::__tree<int, (lambda at a.cpp:8:17), std::__1::allocator<int> >::operator=' requested here
            __tree_ = _VSTD::move(__s.__tree_);
                    ^
a.cpp:17:13: note: in instantiation of member function 'std::__1::set<int, (lambda at a.cpp:8:17), std::__1::allocator<int> >::operator=' requested here
    map2[0] = set<int, decltype(comp)>(comp);
            ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/memory:2208:27: note: copy assignment operator of '__compressed_pair<unsigned long, (lambda at a.cpp:8:17)>' is implicitly deleted because base class '__compressed_pair_elem<(lambda at a.cpp:8:17), 1>' has a deleted copy assignment operator
                          private __compressed_pair_elem<_T2, 1> {
                          ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/memory:2169:50: note: copy assignment operator of '__compressed_pair_elem<(lambda at a.cpp:8:17), 1, true>' is implicitly deleted because base class '(lambda at a.cpp:8:17)' has a deleted copy assignment operator
struct __compressed_pair_elem<_Tp, _Idx, true> : private _Tp {
                                                 ^
a.cpp:8:17: note: lambda expression begins here
    auto comp = [](const int& i, const int& j) {
                ^
2 errors generated.

Make a loop to append in c++?

I have below code and i would like to make loop for appending to the graph!

Example:

    graph[1].push_back(make_pair(2, 3)); 
    graph[2].push_back(make_pair(4, 8)); 
    graph[3].push_back(make_pair(3, 7)); 
    ...
    graph[6].push_back(make_pair(5, 8)); 

To:

// is there any better way!!!
int n,a,b;

    vector< pair<int,int> > graph[n+1]; 


for (int i = 0; i < n; i++){
        cin >> a >> b;

    graph[n].push_back(make_pair(a, b)); 
}

My main Function...

int main() 
{ 
    // n is number nodes
    int n = 6; 

    vector< pair<int,int> > graph[n+1]; 

    // create undirected graph 
    // first edge 
    graph[1].push_back(make_pair(2, 3)); 
    graph[2].push_back(make_pair(1, 3)); 

    // second edge 
    graph[2].push_back(make_pair(3, 4)); 
    graph[3].push_back(make_pair(2, 4)); 

    // third edge 
    graph[2].push_back(make_pair(6, 2)); 
    graph[6].push_back(make_pair(2, 2)); 

    // fourth edge 
    graph[4].push_back(make_pair(6, 6)); 
    graph[6].push_back(make_pair(4, 6)); 

    // fifth edge 
    graph[5].push_back(make_pair(6, 5)); 
    graph[6].push_back(make_pair(5, 5)); 

    cout << myFunction(graph, n); 

    return 0; 
} 

Would anyone help me to fix the issues! Is there any better way to solve the loop!.............................. tnx

How to parsing the input in c++?

I'm trying to parsing the input in c++!

  • 10 will be as n input!
  • Words will be string! Note: Some of them has space!
  • 10 16 -> 10 will be as n input again! the 16 will be as int e;
  • 0 2 to 9 7 should be followed by a and b.

example: all input on the left consider as a and on the right consider as b.

INPUT:


10
den
bou
alberquerque
santa fe
burl
mont
bratt
annap
washin
alexan
10 16
0 2
0 1
1 0
2 3
2 0
3 2
4 5
5 4
5 6
6 5
7 8
7 9
8 7
8 9
9 8
9 7
// Driver code 

int main() { 

  int n,e,a,b;

  cin>>n; 
  string str; 
   int t = n; 
   while (t--) 
   { 
       getline(cin, str); 

       // Keep reading a new line while there is 
       // a blank line 
       while (str.length()==0 ) 
           getline(cin, str); 

     //  cout << str << " : Testing" << endl; 
   } 





//    Graph g(n); 
//    g.addEdge(a, b); 




   return 0; 
} 

So far i have above code! but it's not complete! Can anyone help me to write the correct parsing code to read entire input correctly!

Thanks

Why the copy and move constructors end up in the same amount of memcopies?

Thee problem here is to understand if the copy or move constructor was called when initializing a vector by a return object of a function. Checking the mallocs with a profiler shows similar memcopies in both cases. Why?

We have a class of type "message". The class provides a function "data_copy" which returns the contents of the "message" as vector.

There are 2 options that I tried. One is to use directly the copy constructor to initialize a new vector.

std::vector<uint8_t> vector1 ( message.data_copy() );

The second option was to try to avoid the extra copy and do

std::vector<uint8_t> vector1 ( std::move( message.data_copy() ) );

For reference I attach what data_copy() does.

std::vector<uint8_t> message::data_copy(void) const
{
    std::vector<uint8_t> d(this->size());
    copy_data_to_buffer(d.data());
    return d;
}
void message::copy_data_to_buffer(uint8_t* buffer) const
{
    DEBUG_LOG("copy_data_to_buffer");
    for(const fragment* p = &head; p != nullptr; p = p->next)
    {
        memcpy(buffer, p->data[0], p->size[0]);
        buffer += p->size[0];

        if(p->size[1])
        {
            memcpy(buffer, p->data[1], p->size[1]);
            buffer += p->size[1];
        }
    }
}

Finally, by using a profiler I compare the amount of malloc calls. While one would expect that the move constructor would avoid the extra memcopy in reality they are the same in both cases.

Using std::valarray in numerical simulation

I posted a simple n-body class that I have written in C++ here in Code Review.

There I was told to use std::valarray instead of plain std::array with the goal that I can rewrite some code that looks currently like this

void Particle::update_position() {
    for (unsigned int d = 0; d < DIM; ++d) {
        position[d] += dt*(velocity[d] + a*force_new[d]);
        force_old[d] = force_new[d];
    }
}

to this

void Particle::update_position() {
    position += 0.1*(velocity + force_new);
    force_old = force_new;
}

Since I am a beginner in C++ I wrote a short program that uses the std::valarray such that I can learn how to use this data structure. The compiler, however, throws a lot of errors and I do not know why. I hope you can help me with this. Here is the small program I wrote:

#include <iostream>
#include <vector>
#include <array>
#include <valarray>

constexpr unsigned int DIM = 2;

struct Particle{
    std::array<std::valarray<double>, DIM> position; 
    std::array<std::valarray<double>, DIM> velocity;
    std::array<std::valarray<double>, DIM> force_new;
    std::array<std::valarray<double>, DIM> force_old;
    void update_position();
};

void Particle::update_position() {
    position += 0.1*(velocity + force_new);
    force_old = force_new;
}

void compute_position(std::vector<Particle>& particles) {
    for (auto& particle: particles) { 
        particle.update_position();
    }
}

void print_data(const std::vector<Particle>& particles) {
    for (const auto& particle: particles) {
        for (const auto& x: particle.position) std::cout << x << " ";
        for (const auto& v: particle.position) std::cout << v << " ";
        for (const auto& F: particle.position) std::cout << F << " ";
        std::cout << std::endl;
    }
}

void init_data(std::vector<Particle>& particles) {
    for (auto& particle: particles) {
        for (const auto& p: particle) {
            p.position = 1.0
            p.velocity = 2.0
            p.force_new = 3.0
            p.force_old = 4.0
        }
    }
}

int main() { 
    const unsigned int n = 10;
    std::vector<Particle> particles(n);
    init_data(particles);
    compute_position(particles);
    print_data(particles); 
    return 0;
}

When I try to compile this code, I get the following errors:

so.cpp: In member function ‘void Particle::update_position()’:
so.cpp:17:31: error: no match for ‘operator+’ (operand types are ‘std::array<std::valarray<double>, 2>’ and ‘std::array<std::valarray<double>, 2>’)
     position += 0.1*(velocity + force_new);

so.cpp: In function ‘void print_data(const std::vector<Particle>&)’:
so.cpp:29:58: error: no match for ‘operator<<’ (operand types are ‘std::ostream’ {aka ‘std::basic_ostream<char>’} and ‘const std::valarray<double>’)
         for (const auto& x: particle.position) std::cout << x << " ";


so.cpp: In function ‘void init_data(std::vector<Particle>&)’:
so.cpp:38:29: error: ‘begin’ was not declared in this scope
         for (const auto& p: particle) {
                             ^~~~~~~~
so.cpp:38:29: note: suggested alternative:
In file included from so.cpp:4:
/usr/include/c++/8/valarray:1211:5: note:   ‘std::begin’
     begin(const valarray<_Tp>& __va)
     ^~~~~
so.cpp:38:29: error: ‘end’ was not declared in this scope
         for (const auto& p: particle) {

How to assign variadic template arguments to std::array

I have an std::array and I have a variadic template function with the number of parameters that matches the size of the array. I need to assign the arguments to the elements of the array. In other words, in the code below I wish a to get values {1, 2, 3} and b to get values {1, 2, 3, 4, 5}

std::array<int, 3> a;
std::array<int, 5> b;

assign_values(a, 1, 2, 3);
assign_values(b, 1, 2, 3, 4, 5);

The question is how to implement the assign_values variadic template function.

I'm limited with the C++14 version.