samedi 31 octobre 2020

Defining a map with custom comparator where the value datastructure also has custom comparator

I wanted to define a datastructure like:

struct node {
    int x_coordinate;
    int y_coordinate;
    // some variables
};

map<node, priority_queue<node> > M;
// or lets say 
map<node, set<node> > M

The problem I am facing is I don't know how to write it's custom comparator

Also do you think if it is possible to sort the priority_queue based on the distance from the it's key node. For example let's say if I have key node with x_coordinate=0 and y_coordinate=0, and I want to insert (8,6),(4,3),(15, 9),(0,1).

So priority_queue would be something like (0,1) (4,3) (8,6) (15,9)

warning: extended initializer lists only available with -std=c++11 or -std=gnu++11 [enabled by default]

I don't know why I am getting below error

" warning: extended initializer lists only available with -std=c++11 or -std=gnu++11 [enabled by default]"

I have .h and .cpp file

in .h file, I have declare variable name

 class file
 {
   private:
     string* arr;
   public:
     void list();
 }

in .cpp file

void file::list()
{
  arr = new string[2]{"1", "2"}; 
}

C++ Linked list using template and overloading [closed]

Hi everyone. I couldn't solve this problem myself. Who can help? I'm stuck with this task whole day. May be for some of you it will be easy, but I spend most of time in my day doing this. I'll appreciate if there's someone who can solve it. A lot of thanks for that person who will do it. This is sinly linked list and I need to do it. After that I need also to do doubly linked, but for now I want at least singly linked list.

        #include<iostream>
        using namespace std;
        
        //<T>
        //Linked List
        template <typename T> class SingleList {
            class Node {
            public: T data; Node* next;
                Node(T data = T(), Node* next = nullptr) {
                    this->data = data;
                    this->next = next;
                }
            };
            int size;
            Node* head;
        public:
            SingleList() {
                size = 0;
                head = nullptr;
            }
            int length() {
                return size;
            }
            void push_front(T data) {//O(1)
                if (head == nullptr)
                    head = new Node(data);
                else {
                    Node* temp = new Node(data, head);
                    head = temp;
                }
                size++;
            }
            void pop_front() {
                if (size <= 0)
                    throw out_of_range("");
                else {
                    Node* temp = head;
                    head = head->next;
                    delete temp;
                }
                size--;
            }
            void clearAll() {
                while (size != 0)
                    pop_front();
                cout << "List is empty, size = " << size << endl;
            }
            T operator [] (int index) {
                T res = T();
                int counter = 0;
                Node* cur = head;
                while (cur != nullptr) {
                    if (counter == index) {
                        res = cur->data;
                        break;
                    }
                    cur = cur->next;
                    counter++;
                }
                return res;
            }
        
            void push_back(T data){
                Node* temp = new Node(data);
                Node* cur = head;
                if (head == nullptr)
                    head = new Node(data);
                else {
                    while (cur != nullptr) {
                        if (cur->next == nullptr) {
                            cur->next = temp;
                            break;
                        }
                        cur = cur->next;
                    }
                }
                size++;
        
            }
            void pop_back(){
                Node* cur = head;
                if (size <= 0)
                    throw out_of_range("");
                else {
                    while (cur->next != nullptr) {
                        cur = cur->next;
                    }
                    delete cur->next;
                    cur->next = NULL;
                }
                size--;
            };
        
            void add(T element, int index){
                int counter = 0;
                Node* cur = head;
                Node* temp = new Node(element);
                while (cur != nullptr) {
                    if (counter == index) {
                        temp->next = cur->next;
                        cur->next = temp;
                        break;
                    }
                    cur = cur->next;
                    counter++;
                }
                size++;
            };
        
            void set(T element, int index){
                int counter = 0;
                Node* cur = head;
                while (cur != nullptr) {
                    if (counter == index) {
                        cur->data = element;
        
                        break;
                    }
                    cur = cur->next;
                    counter++;
                }
            };
        
            void remove(int index){
                int counter = 0;
                Node* cur = head;
                while (cur!= nullptr){
                    if (counter == index){
        
                        cur->next = NULL;
                        delete cur-> next;
                        size--;
                        break;
                    }
                    cur = head->next;
                    counter++;
        
                }
        
        
            };
        
            T operator == (int index){
        
                T res = T();
                int counter = 0;
                Node* cur = head;
                while (cur != nullptr) {
                    if (counter == index) {
                        res = cur->data;
                        break;
                    }
                    cur = cur->next;
                    counter++;
                }
                return res;
            }
            T operator != (int index){
        
            }
            T operator >> (int index){
        
            }
            T operator << (int index){
        
            }
        
            /*~SingleList(){
                clearAll();
            }*/
        };
        
        /*
         TODO List:
         1. methods: push_back(T element), pop_back(), add(T element, int index),
            set(T element, int index), remove(int index)
         2. operators: ==, !=, >>, <<
         */
        
        int main() {
            //1 2 3 4
            //add(5, 2)
            //Output: 1 2 5 3 4
            // set(10, 0)
            //Output: 10 2 3 4
            SingleList<int> sl;
            sl.push_front(4);//4
            sl.push_front(3);//3,4
            sl.push_front(2);//2,3,4
            sl.push_front(1);//1,2,3,4
        //    sl.pop_front();//2,3,4;
        //    sl.add(5,2);// 1 2 3 5 4
        //    sl.pop_back();//1,2,3
        //    sl.set(10,0); //10 2 3 4
            sl.remove(2);
            for (int i = 0; i < sl.length(); i++)
                cout << sl[i] << " ";
            cout << endl;
            return 0;
        }

P.s. Some parts of the task are solved myself. But anyway I stuck doing it.

Rotate a 2D array around the center C++

I was asked to rotate the contents of a 2D array around the center 90 degrees counter clockwise sample output I can only use loops (nested of course) how can I do this

C++ factorial execution time [closed]

I am confuse to why this piece of code does not work.Can someone please help me to why it does not show the time taken to find the factorial in the end?Thank you in advance.

#include<iostream>
#include <time.h>
using namespace std;
int main()
{
    int n,faktoriel=1;
    cout << "n= "; cin >> n;
    clock_t tStart = clock();
    for (int i = 1; i<= n; i++)
    {
        faktoriel = faktoriel * i;
    }
    cout <<"Faktoriel < "<<n<<" > = "<< faktoriel<<endl;
    cout<<("Time taken:", (double)(clock() - tStart)/CLOCKS_PER_SEC);
    
    return 0;
}

Writing custom comparator for a priority_queue which is value for a key in map where map itself has a custom comparator for it's keys

I wanted to define a datastructure like:

struct node {
    int x_coordinate;
    int y_coordinate;
    // some variables
};

map<node, priority_queue<node> > pq;

The problem I am facing is I don't know how to write it's custom comparator

Also do you think if it is possible to sort the priority_queue based on the distance from the it's key node. For example let's say if I have key node with x_coordinate=0 and y_coordinate=0, and I want to insert (8,6),(4,3),(15, 9),(0,1).

So priority_queue would be something like (0,1) (4,3) (8,6) (15,9)

Initialize constant to integer value [duplicate]

I am trying to create an array of a size specified by a command line argument. I assign it to a const int using const int size = stoi(argv[3]);. However when I pass this value into an object constructor someConstructor(const int size) and I try to create an array based off that size in the construtor int table[size]; I get "expression did not evaluate to a constant". What am I doing wrong?

OpenSSL memory overload

So, i have a class:

// in tcpserver.h
class TcpServer {
public:
 void mainLoop();
private:
 SSL* ssl;
 SSL_CTX* ssl_ctx;
 std::unordered_map<const char*, std::string> pages;
 // also here many non-related (i think) stuff
};
// in tcpserver.cpp
#include "tcpserver.h"

// too much code of initialization socket and setting it's properties
void TcpServer::mainLoop() {
 int i32ConnectFD;
 std::vector<char> buffer(4096U);
 for (
 ssl = SSL_new(ssl_ctx); // means TcpServer::ssl and TcpServer::ssl_ctx (configurated)
 ;
 SSL_free(ssl),
 ssl = SSL_new(ssl_ctx)
 ) {
  i32ConnectFD = accept(i32SocketFD, (sockaddr*)&cliAddr, &cliAddrLen); // means TcpServer::i32SocketFD, TcpServer::cliAddr and TcpServer::cliAddrLen
  if (i32ConnectFD < 0) { /* handle error */ }
  SSL_set_fd(ssl, i32ConnectFD);
  int code{ 1 };
  if ((code = SSL_accept(ssl)) <= 0) { /* handle error */ }
  int rcv_bytes = SSL_read(ssl, &buffer.front(), buffer.size() - 1);
  std::string request{ buffer.begin(), buffer.end() };
  if (rcv_bytes > 0 && static_cast<size_t>(rcv_bytes) < buffer.size()) {
   int snd_bytes{ 0 };
   for (const auto page : pages) {
    if (request.find(page.first) != std::string::npos) {
     snd_bytes = SSL_write(ssl, &page.second.front(), static_cast<int>(page.second.size()));
     break;
    }
   }
   if (snd_bytes == 0)
    snd_bytes = SSL_write(ssl, &pages["404_default"].front(), static_cast<int>(pages["404_default"].size()));
   // next section of logging with std::cout, std::setw, std::right, std::left and std::flush
   // i test it by myself, so i don't think problem caused here
   SSL_shutdown(ssl);
   closeConnection(i32ConnectFD);
   /*
   void closeConnection(int _fd) {
    shutdown(_fd);
    close(_fd);
   }
   */
  }
 }
}

Problem is memory being overloaded. Every new connection makes +240-260 or +640 or +800-1000 bytes. If you need more code, i can provide it. I have shortened the code as much as possible (OpenSSL only).

How do I display the contents of a std::vector of my own datatype and displaying the name on the console using std::copy?

Hi Stackoverflow community, I have a little bit of a problem. I would like to display the contents of the std::vector using std::copy similar to how I've achieved it through std::for_each (see in the main). Is it possible to achieve this? Many thanks in advance to anyone who provides me a solution.

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
class User {
private:
    std::string m_sName;
public:
    User(std::string sName):m_sName(sName) {}
    std::string GetName()const {
        return m_sName;
    }
};
int main()
{
    std::vector<User> vectNames;
    vectNames.emplace_back("Jack");
    vectNames.emplace_back("George");
    vectNames.emplace_back("Jose");
//How can I get std::copy to do what the std::for_each is doing?
    std::copy(vectNames.begin(), vectNames.end(), std::ostream_iterator<User>(std::cout, "\n"));
//The following line is what I really would like std::copy to do. 
    std::for_each(vectNames.begin(), vectNames.end(), [](const User &user) {std::cout << user.GetName() << "\n"; });
    
}

vendredi 30 octobre 2020

Error initializing shared pointer with an array of list

I'm trying to implement a Graph class with shared_ptr. I've declared my class as below.

class Graph
{
    public:
        Graph(int V);
        Graph()=delete;
        void AddEdge(int src, int dest);
        void BFS(int s);
        ~Graph();
    private:
        int V;
        std::shared_ptr<std::list<int>[]> adj;
};

When I try to initialize my adjList like below in the constructor, I'm getting a compilation error.

Graph::Graph(int V)
{
    this->V = V;
    adj = std::make_shared<std::list<int>[]>(new std::list<int>[V]);
}

Error:

/usr/include/c++/9/bits/shared_ptr.h:717:39:   required from ‘std::shared_ptr<_Tp> std::make_shared(_Args&& ...) [with _Tp = std::__cxx11::list<int> []; _Args = {std::__cxx11::list<int, std::allocator<int> >*}]’
Graph.cpp:21:67:   required from here
/usr/include/c++/9/ext/new_allocator.h:145:20: error: no matching function for call to ‘std::__cxx11::list<int>::list(std::__cxx11::list<int>*)’

What am I doing wrong ?

Why does std::copy() require std::back_inserter to insert into a vector with sufficient capacity?

REFERENCE CODE:

#include <vector>
#include <algorithm>
#include <string>

void print(std::string label, std::vector<int> & arr) {
  std::cout << label << ":" << " size: " << arr.size() << " cap: " << arr.capacity() << " [ ";
  for (auto elem : arr) {
    std::cout << elem << " ";
  }
  std::cout << " ] " << std::endl;
}

void reserve_dest_use_begin() {
  std::vector<int> s_arr = {0, 1, 2, 3, 4, 5}; 
  print("source", s_arr);

  std::vector<int> d_arr;
  d_arr.reserve(3);
  print("dest", d_arr);

  auto min_elems = std::min(s_arr.size(), d_arr.capacity());

  std::cout << "COPYING FIRST" << min_elems << "3 FROM SOURCE TO DEST" << std::endl;

  std::copy(s_arr.begin(), s_arr.begin() + min_elems, d_arr.begin());

  print("source", s_arr);
  print("dest", d_arr);
}

void reserve_dest_use_back_inserter() {
  std::vector<int> s_arr = {0, 1, 2, 3, 4, 5}; 
  print("source", s_arr);

  std::vector<int> d_arr;
  d_arr.reserve(3);
  print("dest", d_arr);

  auto min_elems = std::min(s_arr.size(), d_arr.capacity());

  std::cout << "COPYING FIRST" << min_elems << " ELEMENTS FROM SOURCE TO DEST" << std::endl;

  std::copy(s_arr.begin(), s_arr.begin() + min_elems, std::back_inserter(d_arr));

  print("source", s_arr);
  print("dest", d_arr);
}

int main() {
  std::cout << "RESERVE DEST ARR. USE BEGIN() TO COPY" << std::endl;
  reserve_dest_use_begin();
  std::cout << "RESERVE DEST ARR. USE BACK_INSERTER() TO COPY" << std::endl;
  reserve_dest_use_back_inserter();

OUTPUT:

RESERVE DEST ARR USE BEGIN() TO COPY
source: size: 6 cap: 6 [ 0 1 2 3 4 5  ] 
dest: size: 0 cap: 3 [  ] 
COPYING FIRST 3 ELEMENTS FROM SOURCE TO DEST
source: size: 6 cap: 6 [ 0 1 2 3 4 5  ] 
dest: size: 0 cap: 3 [  ] 
=============================================
RESERVE DEST ARR USE BACK_INSERTER() TO COPY
source: size: 6 cap: 6 [ 0 1 2 3 4 5  ] 
dest: size: 0 cap: 3 [  ] 
COPYING FIRST 3 ELEMENTS FROM SOURCE TO DEST
source: size: 6 cap: 6 [ 0 1 2 3 4 5  ] 
dest: size: 3 cap: 3 [ 0 1 2  ]

In both scenarios, the destination array has sufficient capacity. The documentation from cppreference indicates:

Copies the elements in the range, defined by [first, last), to another range beginning at d_first.
1) Copies all elements in the range [first, last) starting from first and proceeding to last - 1. The behavior is undefined if d_first is within the range [first, last). In this case, std::copy_backward may be used instead.

The d_arr.begin() points to a range that is outside of the source range of [first, last), but in the provided example, I need to use std::back_inserter() to copy instead of just providing d_arr.begin() despite the underlying vector having enough capacity.

Is the std::back_inserter() operation optimized to just memmove the block of memory, or is it pushing back every element? The note from cppreference indicates:

In practice, implementations of std::copy avoid multiple assignments and use bulk copy functions such as std::memmove if the value type is TriviallyCopyable and the iterator types satisfy LegacyContiguousIterator.

However, with std::back_inserter() I suspect it doesn't optimize with memmove.

In summary, I have the following questions:

  1. Why can't I use d_arr.begin() as the OutputIt in std::copy when the underlying vector has sufficient capacity?
  2. Is use std::back_inserter() optimized to bulk copy ranges?

Dynamic graph using Treap data structure

I am trying to implement Dynamic graph using Treap data structue.

Here is node structure:

    class TreapNode
    {
        public:
                int key;
                int priority;
                TreapNode* left, *right;
                vector<int> neighbourNode;
                
                TreapNode(int key)
                {
                    this->priority = 0;
                    this->key = key;
                    this->left  = nullptr;
                    this->right = nullptr;
                }
                
                TreapNode()
                {}
                
                TreapNode* addNode(TreapNode*&,int);
                void updateNode(TreapNode*&,int,int);
     };          
     

When I want to add neighbouring node to particular node,

  1. I search the node , and then add neighbouring node to search node's vector<int> neighbourNode through updateNode(), in the following way.

searchAddress->neighbourNode.push_back(x);

But my professor says, store address of vector<int> neighbourNode in the node.

  1. Is it going to reduce my TreapNode size ?
  2. How to store address and access it ? I tried this way in TreapNode class but it is giving neighbourNode undefine error.

int* neighbourNodeAddress = neighbourNode.data()

Can anyone help me ?

Programmatic bindings in pybind11

I am using pybind11 to export a library written in c++ as a python module. My situation is perhaps a little unusual in that the c++ library already contains structures with all of the metadata of the classes I want to export. I am considering whether I could make use of this existing metadata, rather than re-entering it all again to create the pybind11 bindings.

Normal pybind11 code might look something like this;

namespace py = pybind11;

PYBIND11_MODULE(pet, m) {
    py::class_<Pet>(m,"Pet")
            .def("feed", &Pet::feed, "Feed the pet")
            .def("walk", &Pet::walk, "Walk the pet");
}

I am considering doing something along these lines;

namespace py = pybind11;

PYBIND11_MODULE(pet, m) {
    py::class_<Pet> pet(m,"Pet");    
    for (int i = 0; i < pet_metadata.num_funcs; i++)
    {
        auto& md = pet_metadata.func[i];
        pet.def(md.name, md.fptr, md.descr);
    }
}

Are there any performance hits for doing something like this? I don't have a good understanding of how pybind11 works behind the scenes. Would the for loop run each time one of the bound functions is invoked from python? Or is it all being evaluated at compile time? Will this approach even work?

global const var declared once, is it possible?

I've an header file with all const values I need within the DLL I'm making, such as:

// myHelpers.hpp
const int kMaxNumVoices = 16;
const int kMaxBeats = 32;
....

and so on. Once I include the .hpp on every .cpp, I can use those constant also on std::array definition.

The problem (theoretically) is that this will violate ODR, since a copy of each var will be used (even if they are const) on each compilation unit, right?

Is this acceptable? Or could deal in some undefined behavior? If its not acceptable, whats the right approch to it?

jeudi 29 octobre 2020

Parsing the string and populate the map

Consider this:

command1 -keep -path { {path1} }  { {./input.doc} }

I wanted to parse the above line and collect the information into a map where value would be contents of -path option and key would be everything else. The format of the string would be fixed that after -path there would be two opening and two closes brackets. In this case,

key would be:

command1 -keep { {./input.doc} }

Value would be:

path1

I was doing it using brute force method as like:

Get the position of -path.

Get the position of second closing bracket.

Little more processing and create two substring of -path and remaining else with above two positions.

This seems little rusty to me. Can we discuss other methods to extract this information?

ROS 2 Subscriber Callback with a method of member class

I'd like to use member class method in callback function. The following C++ code is a simple subscriber with a callback using a member class method hello().

#include <functional>
#include <memory>

#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"

using std::placeholders::_1;

class Subclass
{
private:
public:
    Subclass(/* args */);
    ~Subclass();
    std::string hello(std::string &s)
    {
        return "Hello " + s;
    }
};

class MinimalSubscriber : public rclcpp::Node
{
public:
    MinimalSubscriber()
        : Node("minimal_subscriber")
    {
        subscription_ = this->create_subscription<std_msgs::msg::String>(
            "topic", 10, std::bind(&MinimalSubscriber::topic_callback, this, _1));
    }

private:
    Subclass subclass_;
    void topic_callback(const std_msgs::msg::String::SharedPtr msg) const
    {
        std::string s = subclass_.hello(msg->data);
        RCLCPP_INFO(this->get_logger(), "I heard: '%s'", s.c_str());
    }
    rclcpp::Subscription<std_msgs::msg::String>::SharedPtr subscription_;
};

int main(int argc, char *argv[])
{
    rclcpp::init(argc, argv);
    rclcpp::spin(std::make_shared<MinimalSubscriber>());
    rclcpp::shutdown();
    return 0;
}

I build the C++ code and I catch below message. How I fix the code? ROS2 Foxy in Ubuntu LTS 20.04 is used to build.

/home/ubuntu/dev_ws/src/ros2_pigpio/src/subclass.cpp: In member function ‘void MinimalSubscriber::topic_callback(std_msgs::msg::String_<std::allocator<void> >::SharedPtr) const’:
/home/ubuntu/dev_ws/src/ros2_pigpio/src/subclass.cpp:35:50: error: passing ‘const Subclass’ as ‘this’ argument discards qualifiers [-fpermissive]
   35 |         std::string s = subclass_.hello(msg->data);
      |                                                  ^
/home/ubuntu/dev_ws/src/ros2_pigpio/src/subclass.cpp:15:17: note:   in call to std::string Subclass::hello(std::string&)’
   15 |     std::string hello(std::string &s)
      |                 ^~~~~
make[2]: *** [CMakeFiles/subclass.dir/build.make:63: CMakeFiles/subclass.dir/src/subclass.cpp.o] Error 1
make[1]: *** [CMakeFiles/Makefile2:84: CMakeFiles/subclass.dir/all] Error 2
make: *** [Makefile:141: all] Error 2

wxWidgets: class wxDialog * cannot convert to class wxApp *

The problem is exactly what is in the title, my wxWidgets application is breaking down because the conversion from the dialog class to the app class isn't working. Any help?

Error meassage:

error C2440: 'initializing': cannot convert from 'MP *' to 'MPApp *'

error C2664: 'void wxAppBase::SetTopWindow(wxWindow *)': cannot convert argument 1 from 'MPApp *' to 'wxWindow *'

error C2039: 'Show': is not a member of 'MPApp'

MPApp.cpp:

#include "MPApp.h"
#include "MP.h"

IMPLEMENT_APP(MPApp)

bool MPApp::OnInit()
{
    MPApp* dialog = new MP((NULL));
    SetTopWindow(dialog);
    dialog->Show(true);
    return true;
}

int MPApp::OnExit()
{
    return 0;
}

MPApp.h:

#ifndef __MPApp_h__
#define __MPApp_h__

#ifdef __BORLANDC__
#pragma hdrstop
#endif

#ifndef WX_PRECOMP
#include <wx/wx.h>
#else
#include <wx/wxprec.h>
#endif

class MPApp : public wxApp
{
public:
    bool OnInit();
    int OnExit();
};

#endif

MP.h:

#ifndef __MP_h__
#define __MP_h__

#ifdef __BORLANDC__
#pragma hdrstop
#endif

#ifndef WX_PRECOMP
#include <wx/wx.h>
#include <wx/dialog.h>
#else
#include <wx/wxprec.h>
#endif

#include <list>


#include <wx/menu.h>
#include <wx/timer.h>
#include <wx/listctrl.h>
#include <wx/textctrl.h>
#include <wx/stattext.h>
#include <wx/checkbox.h>
#include <wx/mediactrl.h>
#include <wx/slider.h>
#include <wx/button.h>
#include <wx/bmpbuttn.h>
#include <wx/panel.h>
#include <wx/sizer.h>
#include <wx/toplevel.h>

#undef MPSTYLE
#define MPSTYLE wxWANTS_CHARS | wxALWAYS_SHOW_SB | wxCAPTION | wxRESIZE_BORDER | wxSYSTEM_MENU  | wxDIALOG_NO_PARENT | wxMINIMIZE_BOX | wxMAXIMIZE_BOX | wxCLOSE_BOX

class MP : public wxDialog
{
private:
    DECLARE_EVENT_TABLE();
public:
    //Constuctor
    MP(wxWindow* parent, wxWindowID id = 0, const wxString& title = wxT("Music"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = MPSTYLE);
    virtual ~MP();
    //Player
    void PlayFileNow();
    // EVENTS
    // Command Events
    void AddToQueue(wxCommandEvent& event);
    void WxButton1Click(wxCommandEvent& event);
    void PlayButtonClick(wxCommandEvent& event);
    void NextButtonClick(wxCommandEvent& event);
    void PreviousButtonClick(wxCommandEvent& event);
    void StopButtonClick(wxCommandEvent& event);
    void RandomCheckboxClick(wxCommandEvent& event);
    void WxButton2Click(wxCommandEvent& event);
    void SavePlaylistClick(wxCommandEvent& event);
    void LoadPlaylistClick(wxCommandEvent& event);
    void AddButtonClick(wxCommandEvent& event);
    void PlaylistsButtonClick(wxCommandEvent& event);
    void FindButtonClick(wxCommandEvent& event);
    void FindTextEditEnter(wxCommandEvent& event);
    void FindNextButtonClick(wxCommandEvent& event);
    void FindPrevButtonClick(wxCommandEvent& event);
    //Media Events
    void WxMediaCtrl1MediaFinished(wxMediaEvent& event);
    void WxMediaCtrl1MediaPause(wxMediaEvent& event);
    void WxMediaCtrl1MediaPlay(wxMediaEvent& event);
    void WxMediaCtrl1MediaStop(wxMediaEvent& event);
    void WxMediaCtrl1MediaLoaded(wxMediaEvent& event);
    //Key Events
    void HotKeyNext(wxKeyEvent& event);
    void HotKeyStop(wxKeyEvent& event);
    void HotKeyPlay(wxKeyEvent& event);
    void HotKeyPrev(wxKeyEvent& event);
    //List Events
    void WxListCtrl1ColLeftClick(wxListEvent& event);
    void WxListCtrl1ColRightClick(wxListEvent& event);
    void WxListCtrl1RightClick(wxListEvent& event);
    void WxListCtrl1ItemActivated(wxListEvent& event);
    void WxListCtrl1KeyDown(wxListEvent& event);
    //UI Event
    void SavePlaylistUpdateUI0(wxUpdateUIEvent& event);
    //Scroll Events
    void WxSlider2Scroll(wxScrollEvent& event);
    void WxSlider1Scroll(wxScrollEvent& event);
    //Timer Event
    void WxTimer1Timer(wxTimerEvent& event);
    //File Event
    void MPDropFiles(wxDropFilesEvent& event);
    //Mouse Event
    void MPRightUP(wxMouseEvent& event);
private:
//GUI Control
    //Menu items
    wxMenu* PlaylistMenu;
    wxMenu* WxPopupMenu1;
    wxMenu* AddMenu;
    //Timer item
    wxTimer* WxTimer1;
    //List item
    wxListCtrl* WxListCtrl1;
    //Button items
    wxButton* FindPrevButton;
    wxButton* FindNextButton;
    wxButton* AddButton;
    wxButton* PlaylistsButton;
    wxButton* FindButton;
        //Bitmaps
    wxBitmapButton* PlayButton;
    wxBitmapButton* PreviousButton;
    wxBitmapButton* NextButton;
    //Text items
    wxTextCtrl* FindTextEdit;
    wxStaticText* WxStaticText1;
    //Slider items
    wxSlider* WxSlider2;
    wxSlider* WxSlider1;
    //Panel items
    wxPanel* SearchPanel;
    wxPanel* WxPanel1;
    wxPanel* WxPanel;
    //Check item
    wxCheckBox* RandomCheckbox;
    //Media item
    wxMediaCtrl* WxMediaCtrl1;
    //Sizer items
    wxFlexGridSizer* WxFlexGridSizer1;
    wxBoxSizer* WxBoxSizer1;
private:
    //Enum IDs for GUI
    enum
    {
        ////GUI Enum Control ID Start
        ID_MNU_LOADPLAYLIST_1028 = 1028,
        ID_MNU_SAVEPLAYLIST_1029 = 1029,

        ID_MNU_PLAY_PAUSE_1019 = 1019,
        ID_MNU_STOP_1020 = 1020,
        ID_MNU_NEXT_1021 = 1021,
        ID_MNU_PREVIOUS_1022 = 1022,
        ID_MNU_ADDFOLDER_1023 = 1023,
        ID_MNU_SAVEPLAYLIST_1024 = 1024,
        ID_MNU_LOADPLAYLIST_1025 = 1025,

        ID_MNU_ADDFILES_1026 = 1026,
        ID_MNU_ADDFOLDER_1027 = 1027,

        ID_WXTIMER1 = 1017,
        ID_WXLISTCTRL1 = 1015,
        ID_FINDPREVBUTTON = 1034,
        ID_FINDNEXTBUTTON = 1033,
        ID_FINDEDITTXT = 1044,
        ID_WXSTATICTEXT1 = 1032,
        ID_SEARCHPANEL = 1031,
        ID_FINDBUTTON = 1030,
        ID_RANDOMCHECKBOX = 1018,
        ID_WXMEDIACTRL1 = 1016,
        ID_WXSLIDER2 = 1014,
        ID_WXSLIDER1 = 1013,
        ID_ADDBUTTON = 1008,
        ID_PLAYLISTS = 1007,
        ID_NEXTBUTTON = 1006,
        ID_STOPBUTTON = 1005,
        ID_PLAYBUTTON = 1004,
        ID_PREVIOUSBUTTON = 1003,
        ID_WXPANEL2 = 1002,
        ID_WXPANEL1 = 1011,
        ////GUI Enum Control ID End
        ID_HOT_PLAY,
        ID_HOT_STOP,
        ID_HOT_NEXT,
        ID_HOT_PREV,
        ID_DUMMY_VALUE_ //don't remove this value unless you have other enum values
    };

private:
    void OnClose(wxCloseEvent& event);
    void CreateGUIControls();
protected:
    // No description
    void AddFilesFromFolder(wxString FileName);
    //FileList Dirs, Files;
    //wxTreeItemId root;
    bool isPlaying;
    long selItem;
    // No description
    void PlayThisFile(long id);
    // No description
    void PlayFromQueue();
    std::list<wxString> lastPlayed, nextPlay;
    // No description
    void PlayNextFile();
    void DeselectAllFiles();

};

#endif

I couldn't include MP.cpp due to the length of the file, but it compiles fine and I have already debugged the issues.

Creating permutations for the Contdown problem

I'm trying to make a small program to solve the countdown problem. Basically, given a number n and a vector of numbers, the problem outputs if n can be constructed applying simple operations (say addition, div, mult, and subs).

The input I'm trying to give to the program is a string with reverse polish notation, so I made a small function to solve this kind of expressions.

Here is my code:

#include <iostream>
#include <stack>
#include <string>
#include <vector>
using namespace std;

bool is_number(const std::string& s) {
    string::const_iterator it = s.begin();
    while (it != s.end() && std::isdigit(*it)) ++it;
    return !s.empty() && it == s.end();
}

vector<string> parseInput(const string& expression) {
    vector<string> parsedInp;
    string current = "";
    for (auto token : expression) {
        if (isdigit(token)) {
            current += token;
        }
        else if (token == ' ') {
            if (current != "") {
                parsedInp.push_back(current);
                current = "";
            }
        }
        else {
            parsedInp.push_back(string(1, token));
        }
    }
    return parsedInp;
}

double operateExpression(const vector<string>& parsedInp) {
    stack<double> expression;
    for (auto token : parsedInp) {
        if (is_number(token)) {
            expression.push(stod(token));
        }
        else {
            double op1 = expression.top();
            expression.pop();
            double op2 = expression.top();
            expression.pop();
            if (token == "+") {
                expression.push(op1 + op2);
            }           
            if (token == "-") {
                expression.push(op1 - op2);
            }           
            if (token == "*") {
                expression.push(op1 * op2);
            }           
            if (token == "/") {
                expression.push(op1 / op2);
            }
        }
    }
    return expression.top();
}


vector<int> getSolution(vector<string> inp, const int target) {
    vector<string> op = { "+", "-", "*", "/", "" };
    //TODO....
    
}


int main() {
    string expression;
    getline(cin, expression);
    vector<string> parsedInp = parseInput(expression);
    cout << operateExpression(parsedInp) << endl;
}

So my first instinct was to create all possible permutations of the vector, and then try to concatenate the operations in the vector, but the problem that I'm facing now is that I can not find an easy way to do it. I can't concatenate it carelessly, because operateExpression would fail, but I don't want to use try and catch for this problem. Also, I think there should be an easier way to do it.

So is there any better way to write getSolution here? Thanks.

std::vector

I am not exactly sure about this, so please explain me how does it work.

Let's consider following code.

std::vector<std::string> vec {};
 
void add (std::vector<std::string>&& v) {
    using iter = std::vector<std::string>::iterator;
    vec.insert (vec.end (), 
                std::move_iterator<iter> (v.begin ()), 
                std::move_iterator<iter> (v.end ()));
}

Are all elements of v going to be moved? std::vector<T>::insert() for the range version requires first and last iterators, so having the code like this how can it know that v.begin()+1 has also to be moved? Is the implementation of std::vector<T>::insert() distinguish between "normal" and "move" iterators?

qTcpSocket server/client crash

I try to do a basic communication between serveur and client in c++ with qTcpSocket, and I don't understand what append. I launch the server first (everything ok), when I run my client after, it directly crashes without print my first qDebug() on the first line of program. If I launch my client first (everything ok), when I run server after, it directly crashes without print my first qDebug.

I show you my code but I don't think this is the problem :

main.cpp (client)

#include <QCoreApplication>
#include <QObject>
#include <QDebug>

#include "client.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    qDebug() << "App lancee !!!!!!!!!!!";
    Client c;
    c.doConnect();
    return a.exec();
}

client.h

#include <QDebug>
#include <QHostAddress>
#include <QDebug>

#include "client.h"

Client::Client(QObject *parent) : QObject(parent)
{
    _socket = new QTcpSocket(this);
}

void Client::doConnect()
{
    qDebug() << "DEBUT CONNECT";
    _socket->connectToHost(QHostAddress::LocalHost, 4242);
    _socket->waitForConnected();
    connect(_socket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
    qDebug() << "FIN CONNECT";
}

void Client::onReadyRead()
{
    QByteArray datas = _socket->readAll();
    qDebug() << "Tous va bien";
    _socket->write(QByteArray("ok !\n"));
}

client.cpp

#include <QDebug>
#include <QHostAddress>
#include <QDebug>

#include "client.h"

Client::Client(QObject *parent) : QObject(parent)
{
    _socket = new QTcpSocket(this);
}

void Client::doConnect()
{
    qDebug() << "DEBUT CONNECT";
    _socket->connectToHost(QHostAddress::LocalHost, 4242);
    _socket->waitForConnected();
    connect(_socket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
    qDebug() << "FIN CONNECT";
}

void Client::onReadyRead()
{
    QByteArray datas = _socket->readAll();
    qDebug() << "Tous va bien";
    _socket->write(QByteArray("ok !\n"));
}

main.cpp (server)

#include <QCoreApplication>
#include <QTcpServer>
#include <QTcpSocket>
#include <QDebug>
#include <QHostAddress>
#include <QAbstractSocket>
#include <thread>
#include <unistd.h>

#include "server.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    Server s;
    return a.exec();
}

server.h

#ifndef SERVER_H
#define SERVER_H

#include <QObject>
#include <QVector>
#include <QTcpServer>
#include <QTcpSocket>

class Server : public QObject
{
    Q_OBJECT

public:
    explicit Server(QObject *parent = 0);
    static void sendNmea(QTcpSocket *clientSocket);


public slots:
    void onNewConnection();
    void onSocketStateChanged(QAbstractSocket::SocketState socketState);
    void onReadyRead();
private:
    QTcpServer  *_server;
    QList<QTcpSocket*>  _sockets;
    QVector<QString> _nmea;
};

#endif // SERVER_H

server.cpp

#include <thread>
#include <unistd.h>

#include "server.h"

Server::Server(QObject *parent) : QObject(parent)
{
    qDebug()<<"TCPCommunicationPort on port 4242\n";
    _server = new QTcpServer(this);
    _server->listen(QHostAddress::Any, 4242);
    connect(_server, SIGNAL(newConnection()), this, SLOT(onNewConnection()));
    qDebug()<<"Waiting connexion:";


//    _nmea << tr("$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,589.4,M,46.9,M,,*47")
//         << tr("$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,544.4,M,46.9,M,,*47")
//         << tr("$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,594.4,M,46.9,M,,*47")
//         << tr("$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,537.4,M,46.9,M,,*47")
//         << tr("$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,556.4,M,46.9,M,,*47")
//         << tr("$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,579.4,M,46.9,M,,*47")
//         << tr("$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,538.4,M,46.9,M,,*47")
//         << tr("$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,554.4,M,46.9,M,,*47")
//         << tr("$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,534.4,M,46.9,M,,*47");
}

void Server::onNewConnection()
{
    QTcpSocket *clientSocket = _server->nextPendingConnection();
    connect(clientSocket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
    connect(clientSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(onSocketStateChanged(QAbstractSocket::SocketState)));

    QTcpSocket client(clientSocket);
    _sockets.push_back(clientSocket);
    for (QTcpSocket* socket : _sockets) {
        socket->write(QByteArray::fromStdString(clientSocket->peerAddress().toString().toStdString() + " connected to server !\n"));
    }
    qDebug() << "Connected !";
    std::thread xthread(sendNmea, &client);
}

void Server::onReadyRead()
{
    QTcpSocket* sender = static_cast<QTcpSocket*>(QObject::sender());
    QByteArray datas = sender->readAll();
    for (QTcpSocket* socket : _sockets) {
        if (socket != sender)
            socket->write(QByteArray::fromStdString(sender->peerAddress().toString().toStdString() + ": " + datas.toStdString()));
    }
}
void Server::onSocketStateChanged(QAbstractSocket::SocketState socketState)
{
    if (socketState == QAbstractSocket::UnconnectedState)
    {
        QTcpSocket* sender = static_cast<QTcpSocket*>(QObject::sender());
        _sockets.removeOne(sender);
    }
}

void Server::sendNmea(QTcpSocket *clientSocket)
{
    while (42) {
        clientSocket->write(QByteArray::fromStdString(clientSocket->peerAddress().toString().toStdString() + " connected to server !\n"));
        sleep (1);
    }
}

What is the equivalent of std::thread::join in QThread C++

How can I wait for the finish of a QThread or What is the equivalent of std::thread::join() method in QThread

In std::thread, I can do it like the following

#include <iostream>
#include <thread>
#include <chrono>
 
void foo()
{
    // simulate expensive operation
    std::this_thread::sleep_for(std::chrono::seconds(1));
}
 
void bar()
{
    // simulate expensive operation
    std::this_thread::sleep_for(std::chrono::seconds(1));
}
 
int main()
{
    std::cout << "starting first thread executing foo\n";
    std::thread thread1(foo);
 
    std::cout << "starting second thread executing bar \n";
    std::thread thread2(bar);
 
    std::cout << "waiting for threads to finish..." << std::endl;
    thread1.join();
    thread2.join();
 
    std::cout << "done!\n";
}

The output gives the following output

c++ std transform calls copy constructor multiple times

During implementation of a code copying of map elements into a vector I found out that std::transform calls the copy ctor of my custom class multiple times despite of prior vector size reservation. So I compared different ways to do this, and saw that the best method is a simple for-loop. So my question is: are these algorithms really more expensive? If so what is the advantage of them? Or does it not matter for small number of elements? Here my test code:

class A
{
public:
    A() {}
    A(int ai) : i(ai) {}
    A(A& a) : i(a.i) { std::cout << "copy ctor " << i << std::endl; }
    A(const A& a) : i(a.i) { std::cout << "copy const ctor " << i << std::endl; }
    A(A&& a) : i(std::move(a.i)) { std::cout << "move ctor " << i << std::endl; }    
    
    // I removed overloaded operators because they are not called here...

private:
    int i;
};

std::map<int, A> m;
m.insert(std::make_pair(0, A(7)));
m.insert(std::make_pair(1, A(3)));
m.insert(std::make_pair(2, A(1)));
 
std::vector<A> vec;

vec.reserve(m.size());
std::transform(m.begin(), m.end(), std::back_inserter(vec), [](const std::pair<int, A> & p) { return p.second; }); // 3 calls for each ctor

//... clean up and reserve vec
std::for_each(m.begin(), m.end(), [&vec](const std::pair<int, A> & p) { vec.push_back(p.second); }); // 2 calls for each ctor

//... clean up and reserve vec
for (const auto & p : m) // 1 call for each ctor
{
    vec.emplace_back(p.second);
}

Why some of the string variable not taking inputs from structure to void function?

In the below code some of the string is taking inputs but some are just skipping. I checked everything didn't discover anything. It would be ideal if you let me know where I am fouling up.I need to mention that I have a lot more work to do on this problem that's why I created functions

Expected Output

:::::::::::::::::::::::::: Choose Option From Below ::::::::::::::::::::::::::

1.for add new student

2.for add new teacher

3.for add new notice

1

Enter student's first name : Marry

Enter student's last name :lisa

Enter student's roll no :245

Enter student's section : C

Enter student's year :1

Enter student's semester :2

Enter student's department : IR

Enter student's email :lisa2@hotmail.com

Enter student's phone :15648955

Enter student's address : 2/A XYZ street

Output Now

:::::::::::::::::::::::::: Choose Option From Below ::::::::::::::::::::::::::

1.for add new student

2.for add new teacher

3.for add new notice

1

Enter student's first name :Enter student's last name :lisa

Enter student's roll no :245

Enter student's section :Enter student's year :1

Enter student's semester :2

Enter student's department :Enter student's email :lisa2@hotmail.com

Enter student's phone :15648955

Enter student's address :

Process returned 0 (0x0) execution time : 52.725 s Press any key to continue.

#include <iostream>
#include<string>
#include<iomanip>
using namespace std;

struct student{
string firstName;
string lastName;
int Roll;
string Section;
int Year;
int Semester;
string Department;
string Email;
int Phone;
string Address;
};

void student_part(void){
struct student stu;
cout<<"Enter student's first name :";
getline(cin,stu.firstName);
cout<<"Enter student's last name :";
getline(cin,stu.lastName);
cout<<"Enter student's roll no :";
cin>>stu.Roll;
cout<<"Enter student's section :";
getline(cin,stu.Section);
cout<<"Enter student's year :";
cin>>stu.Year;
cout<<"Enter student's semester :";
cin>>stu.Semester;
cout<<"Enter student's department :";
getline(cin,stu.Department);
cout<<"Enter student's email :";
getline(cin,stu.Email);
cout<<"Enter student's phone :";
cin>>stu.Phone;
cout<<"Enter student's address :";
getline(cin,stu.Address);

}



void add_info(void){
int choice;
cout<<"::::::::::::::::::::::::::"<<endl;
cout<<" Choose Option From Below"<<endl;
cout<<"::::::::::::::::::::::::::"<<endl;
cout<<"\n1.for add new student"<<endl;
cout<<"2.for add new teacher"<<endl;
cout<<"3.for add new notice"<<endl;
cin>>choice;
if(choice==1){
    student_part();
}


}


int main()
{
    add_info();

}

mercredi 28 octobre 2020

C++17 Template argument deduction failed

I wanted to simulate timer which would call a function (callback) periodically for that i wrote following snippet (naive though) wherein, Argument deduction is failing at line Timer/<int, int, float>/.. in main function. I am compiling this code with c++17 std. How I can fix this? or those arguments necessary? Any help in this regard is appreciated.

#include <iostream>
#include <functional>
#include <chrono>
#include <thread>

using namespace std::chrono_literals;

template<typename ...Args>
class Timer
{
public:
  Timer(std::function<void(Args...)> func, Args&&... args, std::chrono::milliseconds step)
    : m_callback{ func },
      m_args{ std::forward<Args>(args)... },
      m_stop{ false },
      m_time{ step }
  {
    this->start();
  }

  ~Timer() { stop(); puts(__func__); }

  void stop() { m_stop = true; }

private:
  void start()
  {
    auto callback = [this]() {
      while (!this->m_stop)
      {
        std::apply(m_callback, this->m_args);
        std::this_thread::sleep_for(this->m_time);
      }
    };

    m_executer = std::thread{ callback };
    m_executer.detach();
  }

private:
  std::function<void(Args...)> m_callback;
  std::thread m_executer;
  std::tuple<Args...> m_args;
  std::chrono::milliseconds m_time;
  bool m_stop;
};

int main()
{
  // Create a timer
  auto timer = Timer/*<int, int, float>*/([](int a, int b, float c) { std::cout << a + b + c << '\n'; }, 15, 17, 12.0f, 500ms);

  // Stop timer after 10s
  bool running{ true };
  std::thread{ [&]() { std::this_thread::sleep_for(10s); timer.stop(); running = false; } }.join();
  
  // Simulate long running process
  //size_t n{ 0 };
  //while (running) n += 1;

  return 0;
}

static_assert failed: size of struct is not the same as sum of sizes of all properties [duplicate]

I'm new to C++ languages and I'm writing a data structure which will be used to serialize/deserialize data saved on local machine. The code data structure looks like this:

struct DerMeasurementData
{
    float DerAnalogMeasValue = 0.0;
    int DerStatusMeasValue = 0;
    int DerMeasQuality = 0;
    time_t DerReadingTime = 0;
    time_t DerLastUpdateTime = 0;
};

// Ensure that comparison using memcmp will work correctly (currently there is 1 double value, 2 integer value, 2 time_t values in DerMeasurementData struct)
static_assert(sizeof(DerMeasurementData) == (sizeof(float) + 2 * sizeof(int) + 2 * sizeof(time_t)), "sizeof(DerMeasurementData) should be equal to summary size of it's fields");

However, this code failed to compile because the static assert failed with this error:

Error (active)  E1574   static assertion failed with "sizeof(DerMeasurementData) 
should be equal to summary size of it's fields" dnom    D:\ETD_Repo\IDMS_Dev\dmsSource\portable\serialization\MappedSerializationNew.h  2571    

But I don't quite understand why this is happening. I have one float, two integers, and two time_t in my data structure, so the size of this struct should be the same as "(sizeof(float) + 2 * sizeof(int) + 2 * sizeof(time_t)"

Also, when I changed the static_assert to code below, it somehow worked:

static_assert(sizeof(DerMeasurementData) == (sizeof(float) + 3 * sizeof(int) + 2 * sizeof(time_t))

Can someone please let me know why this is happening?

Best

How to drag and drop a specific QPixmap into a QGraphicsView

On a subclassed QListWidget I have several items. Every QListWidget item (e.g. "ROS Init", "Images" etc) that is shown below is associated with a specific icon.

The problem I have is that I am trying to drag and drop the specific icon corresponding to that QListWidget item, but nothing happens.

Below the function responsible for the dragging:

void ListView::startDrag(Qt::DropActions supportedActions)
{
    QMap<int, QString> icons;
    icons.insert(IT_RosInit, "ROS Init");
    icons.insert(IT_Images, "Images");
    icons.insert(IT_Path, "Path");
    icons.insert(IT_RosShutDown, "ROS Shutdown");

    if (supportedActions & Qt::CopyAction)
    {
        const QList<QListWidgetItem *> &m_items(selectedItems());
        if (m_items.isEmpty())
            return;

        QPixmap pixmapLaser("/home/images/laserscan.png");
        QPixmap pixmapPCloud2("/home/images/pcloud2.png");
        // etc ...

        QStringList iconImages;

        for(int i = 0; i < icons.count(); ++i)
        {
            for (const QString &tableType : iconImages) {
                if (tableType == "ROS Init")
                {
                    auto *data = mimeData(m_items);
                    auto *drag = new QDrag(this);
                    drag->setPixmap(pixmapLaser);
                    drag->setMimeData(data);
                    drag->setHotSpot(pixmapLaser.rect().center());
                    drag->exec(Qt::CopyAction);
                 }
                else if(tableType == "Images")
                {
                    auto *data2 = mimeData(m_items);
                    auto *drag2 = new QDrag(this);
                    drag2->setPixmap(pixmapPCloud2);
                    drag2->setMimeData(data2);
                    drag2->setHotSpot(pixmapPCloud2.rect().center());
                    drag2->exec(Qt::CopyAction);
                }
            }
        }
    }
    else
    {
        QListWidget::startDrag(supportedActions);
    }
}

After subclassing the QListWidget I just reimplemented the usual drag and drop function. All other function are working properly but the startDrag and in fact as I try to drag the proper QPixmap, I actually see nothing being dragged.

I consulted this source, useful, and also this other source which was useful but it didn't reimplement the startDrag but instead dropEvent which for me is not a problem because that is working well.

I also consulted this source and this other source but that also didn't help fixing the problem.

Thanks for shedding light on this matter for solving the problem

Invalid initializer for array member

I'm trying to specify an attribute of a class as being a array of 5 position of the type Stock like follows:

#include "stdio.h"
#include "string"
#include "array"
#include "./stock.h"

#ifndef WALLET_H

class Wallet {
  public:
    Wallet(std::string name, Stock stocks[5]) : name_(name), stocks_(stocks) {}

    //! Calculate de wallet return
    float wallet_return(Stock *stock);

    //! Return the name of the wallet
    std::string get_name();

    //! Return all the stocks in the wallet
    Stock* get_stocks();

  private:
    std::string name_;
    Stock stocks_[5];
};

#endif

std::string Wallet::get_name() {
  return name_;
}

Stock* Wallet::get_stocks() {
  return stocks_;
}

But I keep getting the error invalid initializer for array member 'Stock Wallet::stocks_ [5]', referring to the constructor method.

What I'm I doing wrong?

Problem with For Loop and Base Class Pointer which points to a derived class

I'm slightly perplexed. In my int main() I have created two std::unique_ptr, one which points to the parent class "User" and another one that points to the derived class "Admin". I subsequently std::move() these two std::unqiue_ptr to a std::vector of std::unique_ptr. I then pass the std::vector to a stand-alone function which will be able to iterate through the collection. Because I'm coming at this from the base class pointer in the for-loop I am unable to access the AdminFunction(). Why is this? Is there a solution to what I'm trying to achieve without creating an overloaded function? I really hope this makes sense. Sometimes is so hard to explain-code related problems.

// Polymorpism.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#include <iostream>
#include <memory>
#include <vector>
class User {
private:
    std::string name;
    std::string password;
public:
    std::string GetName() { return name; }
    std::string GetPassword() { return password; }
    void BasicUserFunction() { std::cout << "Basic user function\n"; }
};

class Admin : public User {
private:
public:
    void AdminFunction() { std::cout << "Admin function\n"; }


};

void DisplayPrivileges(std::vector<std::unique_ptr<User>>&users) {
    for (std::unique_ptr<User>&user : users) {
        user->BasicUserFunction();
        user->AdminFunction();
    }
}
int main()
{
    std::unique_ptr<User>ptrAdmin = std::make_unique<Admin>();
    std::unique_ptr<User>ptrUser = std::make_unique<User>();
    std::vector<std::unique_ptr<User>>users;
    users.push_back(std::move(ptrAdmin));
    users.push_back(std::move(ptrUser));
   
    
   
   
}

C++: Will any exception be missed by catch( ... )

Does catch(...) catch all exceptions or will there be some exception that could be missed by this?

Searching for a subsequence using Regular Expressions | C++ [duplicate]

I would like to search for a sequence of 0s inside my string, starting and ending with 1. For example,

for 100001 function should print out: 100001 for 1000101 function should print out: 10001 and 101

I tried to accomplish it using regular expressions, but my code fails to do so.

#include <iostream>
#include <regex>



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

     std::string number(argv[1]);
     std::regex searchedPattern("1?[0]+1");

     std::smatch sMatch;

     std::regex_search(number,sMatch,searchedPattern);

     for(auto& x : sMatch){
         std::cout << x << std::endl;
     }

     return 0;
}

The command, that I'm using to compile the code on the Linux(Ubuntu version 18.04):

g++ Cpp_Version.cpp -std=c++14 -o exec
./exec 1000101

g++ version:

g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

The output is:

10001

I quess that my pattern is wrong. Any ideas how to improve it?

Assigning a const_iterator to an iterator

I have the below snippet of code (which you can run here: http://coliru.stacked-crooked.com/a/2f62134b5c125051)

#include <iostream>
#include <set>
#include <map>

int main() 
{
    std::set<std::pair<const int, const int>> const mySet0; // value_type = std::pair<const int, const int>
    for (std::set<std::pair<const int, const int>>::iterator it  = mySet.cbegin(); it != mySet.cend(); ++it)
    {
        std::cout<<"set it = " << it->first << " " << it->second << std::endl;
    }

    std::map<const int, const int> const myMap0; // value_type = std::pair<const int, const int>
    for (std::map<const int, const int>::iterator it  = myMap.cbegin(); it != myMap.cend(); ++it)
    {
        std::cout<<"map it = " << it->first << " " << it->second << std::endl;
    }   
}

Can someone please explain me why for std::set the below does not throw any error:

std::set<std::pair<const int, const int>>::iterator it  = mySet.cbegin();

while for std::map the below throws error (no known conversion from _Rb_tree_const_iterator<std::pair<const int, const int> > to _Rb_tree_iterator<std::pair<const int, const int> >) as expected:

std::map<const int, const int>::iterator it  = myMap.cbegin();

How does it work for std::set? Shouldn't assigning a const_iterator to an iterator always throw an error?

How to write same digit multiple times in a text file?

I have just started Operator overloading (stream insertion and stream extraction) in C++, and got stuck at point. The program should work like If user enters the value 10 then program must store 10 five times in a text file in different lines. but the program is not storing any of the value in text file.

#include<iostream>
#include<fstream>
using namespace std;
class cntr
{
private:
    int cnt;
public:
    cntr();
    friend istream& operator>>(istream& in, cntr& c);
    friend ostream& operator<<(ostream& out, cntr& c);
};
cntr::cntr()
{
    cnt = 0;
}
istream& operator>>(istream& in, cntr& c)
{
    in >> c.cnt;
    return in;
    ofstream file;
    file.open("lab5.txt", ios::app);
    if (file.is_open())
    {
        for (int i = 0; i <= 5; i++)
        {
            if (c.cnt == 10)
            {
                in >> c.cnt;
                return in;
                cout << endl;
            }
        }
    }
    else
    {
        cout << "Error!" << endl;
    }
}
ostream& operator<<(ostream& out, cntr& c)
{
    out << c.cnt;
    return out;
}
int main()
{
    cntr r;
    cin >> r;
    cout << "\n" << r << endl;
    
    return 0;
}

What is program received signal sigsegv segmentation fault? [duplicate]

I'm working on a project which involves creating a very simple compiler. I currently have 2 versions of my code. Neither work properly, but the messier one gets a lot further than the better organized one. Both will be included as well as the file I'm using for testing.

I've tried using the debug function in dev-c++ but don't at all understand it. All I know is it returns "program received signal sigsegv segmentation fault"

Any help would be greatly appreciated y'all.

This code snippet is the entire first version, it's excessively hard to read, and the only reason I included it was because it was useful for comparison to my second version.

#include<iostream>
#include<array>
#include<string>
#include<fstream>
#include<sstream>
#include<vector>
#include<typeinfo>
#include<ctype.h>
using namespace std;

vector <char> spacer(string &input) {
    vector <char> var;
    for(int i = 0; i < input.size(); i++) {
        var.push_back(input[i]);
        var.push_back(' ');
    }
    return var;
}



string ifHandler(vector<string> &com, array <string, 100> &SML, int &InstPtr, int (&gotoPlace)[100] 
[2], int &gotoCtr, string dataTable[300][3], int &datCtr) {
    //string con=to_string(com[2]);
    //stringstream(com[1])>>con;
    vector<char> condition=spacer(com[2]);
    int caser;
    int loc;
    for (int i = 0; i < condition.size(); i++) {
        if (condition[i] == '!') {
            loc=i;
            caser = 1;  
            break;
        }
        else if(condition[i] == '=') {
            loc=i;
            caser = 2;
            break;
        }
        else if(condition[i] == '<') {
            loc=i;
            if(condition[i + 2] == '=') {
                caser = 5;
            }
            else {
                caser = 3;
            }
            break;
        }
        else if(condition[i] == '>') {
            loc=i;
            if (condition[i + 2] == '=') {
                caser = 6;
            }
            else {
                caser = 4;
            }
            break;
        }
     }
     switch(caser) {
        case 1:
            for(int it=0;it<300;it++){
                if(dataTable[it][0][0]==condition[loc-2]){
                    if(dataTable[it][2].size()>1){
                        SML[InstPtr]="20"+dataTable[it][2];
                    }else{
                        SML[InstPtr]="200"+dataTable[it][2];
                    }
                    InstPtr++;
                    break;
                }
            }
            for(int it=0;it<300;it++){
                if(dataTable[it][0][0]==condition[loc+4]){
                    if(dataTable[it][2].size()>1){
                        SML[InstPtr]="31"+dataTable[it][2];
                    }else{
                        SML[InstPtr]="310"+dataTable[it][2];
                    }
                    InstPtr++;
                    break;
                }
            }
            if(com[4]<com[0]){
                for(int it=0;it<300;it++){
                    if (dataTable[it][2]==com[4]){
                        if(dataTable[it][2].size()>1){
                            SML[InstPtr]="42"+dataTable[it][2];
                        }else{
                            SML[InstPtr]="420"+dataTable[it][2];
                        }
                        InstPtr++;
                    }
                }
            }else{
                SML[InstPtr]="42";
                stringstream(com[4])>>gotoPlace[gotoCtr][0];
                gotoPlace[gotoCtr][1]=InstPtr;
                gotoCtr++;
                InstPtr++;
            }
            for(int it=0;it<300;it++){
                if(dataTable[it][0][0]==condition[loc+4]){
                    if(dataTable[it][2].size()>1){
                        SML[InstPtr]="20"+dataTable[it][2];
                    }else{
                        SML[InstPtr]="200"+dataTable[it][2];
                    }
                    InstPtr++;
                    break;
                }
            }
            for(int it=0;it<300;it++){
                if(dataTable[it][0][0]==condition[loc-2]){
                    if(dataTable[it][2].size()>1){
                        SML[InstPtr]="31"+dataTable[it][2];
                    }else{
                        SML[InstPtr]="310"+dataTable[it][2];
                    }
                    InstPtr++;
                    break;
                }
            }
            if(com[4]<com[0]){
                for(int it=0;it<300;it++){
                    if (dataTable[it][2]==com[4]){
                        if(dataTable[it][2].size()>1){
                        SML[InstPtr]="42"+dataTable[it][2];
                        }else{
                            SML[InstPtr]="420"+dataTable[it][2];
                        }
                        InstPtr++;
                    }
                }
            }else{
                SML[InstPtr]="42";
                stringstream(com[4])>>gotoPlace[gotoCtr][0];
                gotoPlace[gotoCtr][1]=InstPtr;
                gotoCtr++;
                InstPtr++;
            }
            break;
        case 2:
            for(int it=0;it<300;it++){
                if(dataTable[it][0][0]==condition[loc-2]){
                    if(dataTable[it][2].size()>1){
                        SML[InstPtr]="20"+dataTable[it][2];
                    }else{
                        SML[InstPtr]="200"+dataTable[it][2];
                    }
                    InstPtr++;
                    break;
                }
            }
            for(int it=0;it<300;it++){
                if(dataTable[it][0][0]==condition[loc+4]){
                    if(dataTable[it][2].size()>1){
                        SML[InstPtr]="31"+dataTable[it][2];
                    }else{
                        SML[InstPtr]="310"+dataTable[it][2];
                    }
                    InstPtr++;
                    break;
                }
            }
            if(com[4]<com[0]){
                for(int it=0;it<300;it++){
                    if (dataTable[it][2]==com[4]){
                        if(dataTable[it][2].size()>1){
                            SML[InstPtr]="42"+dataTable[it][2];
                        }else{
                            SML[InstPtr]="420"+dataTable[it][2];
                        }
                        InstPtr++;
                    }
                }
            }else{
                SML[InstPtr]="42";
                stringstream(com[4])>>gotoPlace[gotoCtr][0];
                gotoPlace[gotoCtr][1]=InstPtr;
                gotoCtr++;
                InstPtr++;
            }
            break;
        case 3:
            for(int it=0;it<300;it++){
                if(dataTable[it][0][0]==condition[loc-2]){
                    if(dataTable[it][2].size()>1){
                        SML[InstPtr]="20"+dataTable[it][2];
                    }else{
                        SML[InstPtr]="200"+dataTable[it][2];
                    }
                    InstPtr++;
                    break;
                }
            }
            for(int it=0;it<300;it++){
                if(dataTable[it][0][0]==condition[loc+2]){
                    if(dataTable[it][2].size()>1){
                        SML[InstPtr]="31"+dataTable[it][2];
                    }else{
                        SML[InstPtr]="310"+dataTable[it][2];
                    }
                    InstPtr++;
                    break;
                }
            }
            if(com[4]<com[0]){
                for(int it=0;it<300;it++){
                    if (dataTable[it][2]==com[4]){
                        if(dataTable[it][2].size()>1){
                            SML[InstPtr]="42"+dataTable[it][2];
                        }else{
                            SML[InstPtr]="420"+dataTable[it][2];
                        }
                        InstPtr++;
                    }
                }
            }else{
                SML[InstPtr]="42";
                stringstream(com[4])>>gotoPlace[gotoCtr][0];
                gotoPlace[gotoCtr][1]=InstPtr;
                gotoCtr++;
                InstPtr++;
            }
            break;
        case 4:
            for(int it=0;it<300;it++){
                if(dataTable[it][0][0]==condition[loc+2]){
                    if(dataTable[it][2].size()>1){
                        SML[InstPtr]="20"+dataTable[it][2];
                    }else{
                        SML[InstPtr]="200"+dataTable[it][2];
                    }
                    InstPtr++;
                    break;
                }
            }
            for(int it=0;it<300;it++){
                if(dataTable[it][0][0]==condition[loc-2]){
                    if(dataTable[it][2].size()>1){
                        SML[InstPtr]="31"+dataTable[it][2];
                    }else{
                        SML[InstPtr]="310"+dataTable[it][2];
                    }
                    InstPtr++;
                    break;
                }
            }
            if(com[4]<com[0]){
                for(int it=0;it<300;it++){
                    if (dataTable[it][2]==com[4]){
                        if(dataTable[it][2].size()>1){
                            SML[InstPtr]="42"+dataTable[it][2];
                        }else{
                            SML[InstPtr]="420"+dataTable[it][2];
                        }
                        InstPtr++;
                    }
                }
            }else{
                SML[InstPtr]="42";
                stringstream(com[4])>>gotoPlace[gotoCtr][0];
                gotoPlace[gotoCtr][1]=InstPtr;
                gotoCtr++;
                InstPtr++;
            }
            break;
        case 5:
            for(int it=0;it<300;it++){
                if(dataTable[it][0][0]==condition[loc-2]){
                    if(dataTable[it][2].size()>1){
                        SML[InstPtr]="20"+dataTable[it][2];
                    }else{
                        SML[InstPtr]="200"+dataTable[it][2];
                    }
                    InstPtr++;
                    break;
                }
            }
            for(int it=0;it<300;it++){
                if(dataTable[it][0][0]==condition[loc+4]){
                    if(dataTable[it][2].size()>1){
                        SML[InstPtr]="31"+dataTable[it][2];
                    }else{
                        SML[InstPtr]="310"+dataTable[it][2];
                    }
                    InstPtr++;
                    break;
                }
            }
            if(com[4]<com[0]){
                for(int it=0;it<300;it++){
                    if (dataTable[it][2]==com[4]){
                        if(dataTable[it][2].size()>1){
                            SML[InstPtr]="41"+dataTable[it][2];
                        }else{
                            SML[InstPtr]="410"+dataTable[it][2];
                        }
                        InstPtr++;
                    }
                }
            }else{
                SML[InstPtr]="41";
                stringstream(com[4])>>gotoPlace[gotoCtr][0];
                gotoPlace[gotoCtr][1]=InstPtr;
                gotoCtr++;
                InstPtr++;
            }
            if(com[4]<com[0]){
                for(int it=0;it<300;it++){
                    if (dataTable[it][2]==com[4]){
                        if(dataTable[it][2].size()>1){
                            SML[InstPtr]="42"+dataTable[it][2];
                        }else{
                            SML[InstPtr]="420"+dataTable[it][2];
                        }
                        InstPtr++;
                    }
                }
            }else{
                SML[InstPtr]="42";
                stringstream(com[4])>>gotoPlace[gotoCtr][0];
                gotoPlace[gotoCtr][1]=InstPtr;
                gotoCtr++;
                InstPtr++;
            }
            break;
        case 6:
            for(int it=0;it<300;it++){
                if(dataTable[it][0][0]==condition[loc+4]){
                    if(dataTable[it][2].size()>1){
                        SML[InstPtr]="20"+dataTable[it][2];
                    }else{
                        SML[InstPtr]="200"+dataTable[it][2];
                    }
                    InstPtr++;
                    break;
                }
            }
            for(int it=0;it<300;it++){
                if(dataTable[it][0][0]==condition[loc-2]){
                    if(dataTable[it][2].size()>1){
                        SML[InstPtr]="31"+dataTable[it][2];
                    }else{
                        SML[InstPtr]="310"+dataTable[it][2];
                    }
                    InstPtr++;
                    break;
                }
            }
            if(com[4]<com[0]){
                for(int it=0;it<300;it++){
                    if (dataTable[it][2]==com[4]){
                        if(dataTable[it][2].size()>1){
                            SML[InstPtr]="41"+dataTable[it][2];
                        }else{
                            SML[InstPtr]="410"+dataTable[it][2];
                        }
                        InstPtr++;
                    }
                }
            }else{
                SML[InstPtr]="41";
                stringstream(com[4])>>gotoPlace[gotoCtr][0];
                gotoPlace[gotoCtr][1]=InstPtr;
                gotoCtr++;
                InstPtr++;
            }
            if(com[4]<com[0]){
                for(int it=0;it<300;it++){
                    if (dataTable[it][2]==com[4]){
                        if(dataTable[it][2].size()>1){
                            SML[InstPtr]="42"+dataTable[it][2];
                        }else{
                            SML[InstPtr]="420"+dataTable[it][2];
                        }
                        InstPtr++;
                    }
                }
            }else{
                SML[InstPtr]="42";
                stringstream(com[4])>>gotoPlace[gotoCtr][0];
                gotoPlace[gotoCtr][1]=InstPtr;
                gotoCtr++;
                InstPtr++;
            }
            break;
    }
    cout<<"Not struggling with if"<<endl;
}



string compressor(string &input) { // we can pass a substring of the string to the method if we dont        want the whole thing to be compressed
    for (int i = 0; i < input.size(); i++) {
        if (input[i] == ' ') {
            input.erase(i,1); // erases the space at index i
        }
    }
    return input;
}



int gotoFix(array<string,100> &SML, string (&datTab)[300][3], int (&got)[100][2]){
    for(int i=0; i<sizeof(got);i++){
        for(int it=0; it<sizeof(datTab);it++){
            if(datTab[it][0]==""){
                break;
            }
            if(datTab[it][0]==to_string(got[i][0])){
                if(datTab[it][2].size()<2){
                    SML[got[i][1]]+="0"+datTab[it][2];
                }else{
                    SML[got[i][1]]+=datTab[it][2];
                }
            }
        }
    }
}



vector<string> parse(string &line){   //Takes the line and separates all of it's elements
    string parser="";                 //A placeholder string used to store each word into a vector
    vector<string> parsed;            //The Return vector
    char space = ' ';                
    for(int i=0; i<line.size();i++){   //If the character is not a space it is added into parser
        if (line[i]!=space){
            parser+=line[i];
        }else {                        //If the character is a space, parser is added into the vector, and is then reset
            parsed.push_back(parser);
            parser="";
        }
        if(i==(line.size()-1)){        //When the last character is reached, parser needs to be added into the vector, or it would be left out entirely
            parsed.push_back(parser);
        }
    }
    return parsed;
}



int registry(string command,int &DataCtr,int &InstPtr,int &symCtr){     //Used to determine what command is being worked with
    int literal;
    if(command==""){      //Absences are just here for blank lines
        return 5;
    }else if(command=="rem"){   //If command is rem, we stop the loop because content after rem is useless to the assembler
        return 5;
    }else if(command=="input"){   //If command is input, sets up the assembler command
        symCtr++;
        return 0;
    } else if(command=="print"){   //If command is print, sets up the assembler command
        return 1;
    }else if(command=="end"){   //If primary command is end, completely stops processing data
        return 2;
    }else if(command=="goto"){
        return 6;
    }
    else if(command=="if"){
        
        return 7;
    }else{
        if(isdigit(command[0])){   //Checks for a literal
            return 3;
        }else{   //if no literal is found, just establishes a variable
            return 4;
        }
    }
}



int maneuver(string (&arr)[300][3], vector<string> &com, int &line,int &DatCtr,int &InstPtr,array<string,100> &SML,int (&got)[100][2], int &gotoCtr){   //This creates the data table
    if (com[0]==""){
        return 1;
    }
    cout<<com[1]<<endl;
    line++;
    arr[line][0]=com[0];   //Processes line numbers
    arr[line][1]="L";
    arr[line][2]=to_string(InstPtr);
    for(int i=1;i<com.size();i++){     //This passes each part of the vector the function was passed to the registry for processing
        int retStat=registry(com[i],DatCtr,InstPtr,line);
        switch(retStat){
            case 0: 
                cout<<"input"<<endl;
                SML[InstPtr]="10"+to_string(DatCtr);
                InstPtr++;
                break;
            case 1:
                for(i=0;i<300;i++){
                    if(com[2]==arr[i][0]){
                        SML[InstPtr]="11"+arr[i][2];
                        i=300;
                    }
                }
                InstPtr++;
                break;
            case 2:
                cout<<"end"<<endl;
                SML[InstPtr]="4300";
                InstPtr++;
                i=com.size();
                break;
            case 3:
                cout<<"literal"<<endl;
                arr[line][0]=com[i];
                arr[line][1]="N";
                arr[line][2]=to_string(DatCtr);
                DatCtr--;
                break;
            case 4:
                cout<<"variable"<<endl;
                arr[line][0]=com[i];
                arr[line][1]="V";
                arr[line][2]=to_string(DatCtr);
                DatCtr--;
                break;
            case 5:
                cout<<"empty"<<endl;
                return 0;
            case 6:
                cout<<"goto"<<endl;
                if(com[0]<com[2]){
                    SML[InstPtr]="40";
                    stringstream(com[2])>>got[gotoCtr][0];
                    got[gotoCtr][1]=InstPtr;
                    gotoCtr++;
                }else{
                    for(i=0;i<300;i++){
                        if(com[2]==arr[i][0]){
                            if(arr[i][2].size()==1){
                                SML[InstPtr]="400"+arr[i][2];
                                i=300;
                            }else{
                                SML[InstPtr]="40"+arr[i][2];
                                i=300;
                            }
                        }
                    }   
                }
                InstPtr++;
                i=com.size();
                break;
            case 7:
                cout<<"if"<<endl;
                ifHandler(com, SML, InstPtr, got, gotoCtr, arr, DatCtr);
                cout<<"Made it through the if handler"<<endl;
                i=com.size();
                break;
        }
    }   
}



int main(){                  
    int currentDataCtr=99;   //Position for storing data
    int currentInstPtr=0;    //Position for storing commands
    int currentSymCtr=0;     //Position in the symbol table
    int gotoPlace[100][2]={0};
    int gotoCtr=0;
    array<string,100> SML;
    string baseCommand;
    string name;
    cout<<"Please enter the name of the file you would like compiled, \nnote it must be in the same folder as this program. (Example: test.txt)"<<endl;
    getline(cin,name);
    string ofile;
    cout<<"\nPlease enter the name of the file you would like the symbol table entered into, \nnote it will be in the same folder as the program. (Example: out.txt)"<<endl;
    getline(cin,ofile);
    string mfile;
    cout<<"\n Please enter the name of hte file you would like the machine code stored in, \nnote it will be in the same folder as the program. (Example: SMLCode.txt)"<<endl;
    getline(cin,mfile);
    ifstream baseFile(name);   //opens the file
    string dataTable[300][3];  //creates the data table (which is arbitrarily sized)
    dataTable[0][0]="Symbol";  //These 3 just create titles because titles are nice
    dataTable[0][1]="Type";
    dataTable[0][2]="Location";
    ofstream machFile(mfile);  //creates the outfile for the machine code
    while(getline(baseFile,baseCommand)){   //Pulls the lines from the infile and performs all methods on it
        vector<string> command=parse(baseCommand);
        cout<<command[1]<<endl;
        int condition=maneuver(dataTable,command,currentSymCtr,currentDataCtr,currentInstPtr,SML,gotoPlace,gotoCtr);
        if (currentDataCtr<=currentInstPtr){  //Checks to make sure data and commands dont ovelap
            cout<<"This code is too long, and is running into issues of overlapping in memory."<<endl;
            exit(EXIT_FAILURE);
        }
        if(condition==1){  //Handles end
            break;
        }
    }
    baseFile.close();
    ofstream outFile(ofile);// all of this just prints the data table into a file
    outFile<<dataTable[0][0]<<" "<<dataTable[0][1]<<" "<<dataTable[0][2]<<endl;
    for (int i=1;i<=currentSymCtr;i++){
        for(int it=0;it<3;it++){
            outFile<<endl;
        }
    }
    gotoFix(SML,dataTable,gotoPlace);
    for (int i=0;i<currentInstPtr;i++){
        machFile<<SML[i]<<endl;
    }
    machFile.close();
    outFile.close();
    return 0;
}

Included below is the second revision, which is the one I would prefer to continue using, it however does not get nearly as far as the first does. It is however much shorter, and easier to read so.

#include<iostream>
#include<array>
#include<string>
#include<fstream>
#include<sstream>
#include<vector>
#include<typeinfo>
#include<ctype.h>
#include<stdio.h>
#include<stdlib.h>
using namespace std;




//Parse lines to create commands
vector<string> parse(string &line){   //Takes the line and separates all of it's elements
    string parser="";                 //A placeholder string used to store each word into a vector
    vector<string> parsed;            //The Return vector
    char space = ' ';                
    for(int i=0; i<line.size();i++){   //If the character is not a space it is added into parser
        if (line[i]!=space){
            parser+=line[i];
        }else {                        //If the character is a space, parser is added into the vector, and is then reset
            parsed.push_back(parser);
            parser="";
        }
        if(i==(line.size()-1)){        //When the last character is reached, parser needs to be added into the vector, or it would be left out entirely
            parsed.push_back(parser);
        }
    }
    return parsed;
}





//Command to parse conditions (and maybe math one day)
vector <char> spacer(string &input) {
    vector <char> var;
    for(int i = 0; i < input.size(); i++) {
        var.push_back(input[i]);
        var.push_back(' ');
    }
    return var;
}




//Performs gotos
int gotos(int gotoNum, int type, int (&gotoArr)[100][2], int &gotoCtr, int lineNum, array<string,100> &SML, int &InstPtr, string (&dataTable)[300][3]){
    if(lineNum<gotoNum){
        SML[InstPtr]=to_string(type);
        gotoArr[gotoCtr][0]=gotoNum;
        gotoArr[gotoCtr][1]=InstPtr;
        gotoCtr++;
    }else{
        for(int i=0;i<300;i++){
            if(to_string(gotoNum)==dataTable[i][0]){
                if(dataTable[i][2].size()==1){
                    SML[InstPtr]=to_string(type)+"0"+dataTable[i][2];
                    i=300;
                }else{
                    SML[InstPtr]=to_string(type)+dataTable[i][2];
                    i=300;
                }
            }
        }   
    }
    InstPtr++;
}





//Performs conditional statements for the sml creater
int condi(array<string,100> &SML, int &InstPtr, string (&dataTable)[300][3], string item, string type){
    for(int it=0;it<300;it++){
        if(dataTable[it][0]==item){
            if(dataTable[it][2].size()>1){
                SML[InstPtr]=type+dataTable[it][2];
            }else{
                SML[InstPtr]=type+"0"+dataTable[it][2];
            }
            InstPtr++;
            break;
        }
    }       
}




//Perform the commands
int enact(string (&dataTable)[300][3],vector<string> &com,int &symCtr, int &dataCtr, int &InstPtr,array<string,100> &SML, int (&gotoPlace)[100][2], int &gotoCtr){
    if(com[0]==""){
        return 1;
    }
    dataTable[symCtr][0]=com[0];
    dataTable[symCtr][1]="L";
    dataTable[symCtr][2]=to_string(InstPtr);
    symCtr++;
    for(int i=0;i<com.size();i++){
        if(com[i]=="rem"){
            i=com.size();
        }else if(com[i]=="input"){
            SML[InstPtr]="10"+to_string(dataCtr);
            InstPtr++;
        }else if(com[i]=="print"){
            for(int it=0;it<300;it++){
                if(com[i+1]==dataTable[it][0]){
                    SML[InstPtr]="11"+dataTable[it][3];
                    InstPtr++;
                    i=300;
                }
            }
        }else if(com[i]=="end"){
            SML[InstPtr]="4300";
            InstPtr++;
        }else if(com[i]=="goto"){
            gotos(stoi(com[i+1]), 40, gotoPlace, gotoCtr, stoi(com[0]), SML, InstPtr, dataTable);
            i=300;
        }else if(com[i]=="if"){
            vector<char> command=spacer(com[i+1]);
            int caser;
            int loc;
            for (int it=0;it<command.size();it++){
                if(command[it]=='!'){
                    loc=it;
                    caser=1;
                    it=command.size();
                }else if(command[it]=='='){
                    loc=it;
                    caser=2;
                    it=command.size();
                }else if(command[it]=='<'){
                    loc=it;
                    if(command[it+2]=='='){
                        caser=5;
                    }else{
                        caser=3;
                    }
                    it=command.size();
                }else if(command[it]=='>'){
                    loc=it;
                    if(command[it+2]=='='){
                        caser=6;
                    }else{
                        caser=4;
                    }
                    it=command.size();
                }
            }
            switch(caser){
                case 1:
                    condi(SML,InstPtr,dataTable,string(1,command[loc-2]),"20");
                    condi(SML,InstPtr,dataTable,string(1,command[loc+4]),"31");
                    gotos(stoi(com[i+3]), 42, gotoPlace, gotoCtr, stoi(com[0]), SML, InstPtr, dataTable);
                    condi(SML,InstPtr,dataTable,string(1,command[loc+4]),"20");
                    condi(SML,InstPtr,dataTable,string(1,command[loc-2]),"31");
                    gotos(stoi(com[i+3]), 42, gotoPlace, gotoCtr, stoi(com[0]), SML, InstPtr, dataTable);
                    break;
                case 2:
                    condi(SML,InstPtr,dataTable,string(1,command[loc-2]),"20");
                    condi(SML,InstPtr,dataTable,string(1,command[loc+4]),"31");
                    gotos(stoi(com[i+3]), 41, gotoPlace, gotoCtr, stoi(com[0]), SML, InstPtr, dataTable);
                    break;
                case 3:
                    condi(SML,InstPtr,dataTable,string(1,command[loc-2]),"20");
                    condi(SML,InstPtr,dataTable,string(1,command[loc+2]),"31");
                    gotos(stoi(com[i+3]), 42, gotoPlace, gotoCtr, stoi(com[0]), SML, InstPtr, dataTable);
                    break;
                case 4:
                    condi(SML,InstPtr,dataTable,string(1,command[loc+4]),"20");
                    condi(SML,InstPtr,dataTable,string(1,command[loc-2]),"31");
                    gotos(stoi(com[i+3]), 42, gotoPlace, gotoCtr, stoi(com[0]), SML, InstPtr, dataTable);
                    break;
                case 5:
                    condi(SML,InstPtr,dataTable,string(1,command[loc-2]),"20");
                    condi(SML,InstPtr,dataTable,string(1,command[loc+2]),"31");
                    gotos(stoi(com[i+3]), 42, gotoPlace, gotoCtr, stoi(com[0]), SML, InstPtr, dataTable);
                    gotos(stoi(com[i+3]), 41, gotoPlace, gotoCtr, stoi(com[0]), SML, InstPtr, dataTable);
                    break;
                case 6:
                    condi(SML,InstPtr,dataTable,string(1,command[loc+4]),"20");
                    condi(SML,InstPtr,dataTable,string(1,command[loc-2]),"31");
                    gotos(stoi(com[i+3]), 42, gotoPlace, gotoCtr, stoi(com[0]), SML, InstPtr, dataTable);
                    gotos(stoi(com[i+3]), 41, gotoPlace, gotoCtr, stoi(com[0]), SML, InstPtr, dataTable);
                    break;
            }
            i=com.size();
        }else{
            if(isdigit(com[i][0])){
                dataTable[symCtr][0]=com[i];
                dataTable[symCtr][1]="N";
                dataTable[symCtr][2]=to_string(InstPtr);
                symCtr++;
            }else{
                dataTable[symCtr][0]=com[i];
                dataTable[symCtr][1]="V ";
                dataTable[symCtr][2]=to_string(InstPtr);
                symCtr++;
            }
        }   
    }
}





int main(){
    //This is all establishment variables
    int CurrentDataCtr=99;
    int currentInstPtr=0;
    int currentSymCtr=1;
    int gotoCtr=0;
    int gotoPlace[100][2]={0};
    array<string,100> SML;
    string baseCommand;
    string name;
    string ofile;
    string mfile;
    
    //This is getting the names of the files to open
    cout<<"Please enter the name of the file you would like compiled, \nnote it must be in the same folder as this program. (Example: test.txt)"<<endl;
    getline(cin,name);
    cout<<"\nPlease enter the name of the file you would like the symbol table entered into, \nnote it will be in the same folder as the program. (Example: out.txt)"<<endl;
    getline(cin,ofile);
    cout<<"\n Please enter the name of hte file you would like the machine code stored in, \nnote it will be in the same folder as the program. (Example: SMLCode.txt)"<<endl;
    getline(cin,mfile);
    
    //Lets open up the files
    ifstream baseFile(name);
    ofstream outFile(ofile);
    ofstream SMLFile(mfile);
    
    //Establish that Data Table
    string dataTable[300][3];
    dataTable[0][0]="Symbol";
    dataTable[0][1]="Type";
    dataTable[0][2]="Location";
    
    //Initial Processing - Grabbing lines and operating on them
    while(getline(baseFile,baseCommand)){
        vector<string> command=parse(baseCommand);
        int condition=enact(dataTable,command,currentSymCtr,CurrentDataCtr,currentInstPtr,SML,gotoPlace,gotoCtr);
        if (CurrentDataCtr<=currentInstPtr){  //Checks to make sure data and commands dont ovelap
            cout<<"This code is too long, and is running into issues of overlapping in memory."<<endl;
            exit(EXIT_FAILURE);
        }
        if(condition==1){  //Handles end
            break;
        }
    }
    
    baseFile.close();
    
    //Print the data table to the outfile
    outFile<<dataTable[0][0]<<" "<<dataTable[0][1]<<" "<<dataTable[0][2]<<endl;
    for (int i=1;i<=currentSymCtr;i++){
        for(int it=0;it<3;it++){
            outFile<<dataTable[i][0]<<"      "<<dataTable[i][1]<<"      "<<dataTable[i][2]<<"      "<<endl;
        }
    }
    outFile.close();
    
    //Fix any gotos that need remaking
    for(int i=0; i<sizeof(gotoPlace);i++){
        for(int it=0; it<sizeof(dataTable);it++){
            if(dataTable[it][0]==""){
                break;
            }
            if(dataTable[it][0]==to_string(gotoPlace[i][0])){
                if(dataTable[it][2].size()<2){
                    SML[gotoPlace[i][1]]+="0"+dataTable[it][2];
                }else{
                    SML[gotoPlace[i][1]]+=dataTable[it][2];
                }
            }
        }
    }
    
    //Finally print the SML file
    for (int i=0;i<currentInstPtr;i++){
        SMLFile<<SML[i]<<endl;
    }
    SMLFile.close();
    
    return 0;
}

I'm sorry if it seems like my indentation is inconsistent, I copied from dev and pasted into code snippet, which SO did not like and I had to go through and manually indent every line

Finally included is the test file which I currently have titled test.txt. This is the code that will be run through the compiler.

10 rem why must this code hurt me so
20 input x
30 input y
40 if (x!=y) goto 60
50 goto 80
60 print x
70 print y
80 end

So I have no clue what is wrong with it. Any help offered would be greatly appreciated. Thanks y'all

Is std::move overkill in this situation?

Hi StackOverflow community, I was wondering if using the std::move in this regard is overkill or computationally more expensive than simply copying it? I would really like to know.

class Student
{
    private: 
        std::string _studentName;
        int _studentGrade;
    public:
        Student() : _studentName("No Name"), _studentGrade(0) {}

        std::string Name() const { return _studentName; }
        void Name(std::string x) { _studentName = std::move(x); }

        int Grade() const { return _studentGrade; }
        void Grade(int x) { _studentGrade = std::move(x); }
};

Reference collapsing rules not applying as expected?

I am refreshing my memory on how perfect forwarding works in C++. I realize that a call to std::forward is forced to provide an explicit template parameter for a reason (i. e. when dealing with rvalue references that are actually lvalues), however when doing a sanity check on actual code, I was surprised by this (somewhat related) scenario:

#include <iostream>
#include <utility>
#include <type_traits>

template<class T>
T&& fwd(T& t) {
    return static_cast<T&&>(t);
}

template<class T>
T&& fwd(T&& t) {
    return static_cast<T&&>(t);
}

int main()
{
    int lnum = 3;
    if (std::is_rvalue_reference<decltype(fwd(lnum))>::value)
        std::cout << "It's rref." << std::endl;           // this get's printed on screen 
    else
        std::cout << "It's lref." << std::endl;

    return 0;
}

If I understand reference collapsing correctly (and I believe I do), type deduction should go like this:

int& && fwd(int& & t) {                        
    return static_cast<int& &&>(t);         
}

leading to

int& fwd(int& t) {                        
    return static_cast<int&>(t);         
}

Clearly that's not the case. What am I missing here?

Calling Octave interpreter from C++ - Problems compiling and running example

I'm trying to implement calling octave from C, as per the example shown in this answer Call GNU Octave functions in C?

I'm trying this in Nebeans on Linux.

I've created the files calloctave.cc, calloctave.h, main.c and myfunction.m as per the example. Pointed the links and includes to the correct places (in my case /usr/include/octave-5.2.0/octave/ and /usr/lib64/octave/5.2.0 ). Ive chosen C++11 as the standard. In the code, there are no errors highlighted and it seems to find everything it needs, and nothing is highlighted as missing.

When I try to compile it, I just get a series of errors as follows....

cd '/home/arwel/NetBeansProjects/callOctave_new'
/bin/gmake -f Makefile CONF=Debug
"/bin/gmake" -f nbproject/Makefile-Debug.mk QMAKE= SUBPROJECTS= .build-conf
gmake[1]: Entering directory `/home/arwel/NetBeansProjects/callOctave_new'
"/bin/gmake"  -f nbproject/Makefile-Debug.mk dist/Debug/GNU-Linux/libcallOctave_new.so
gmake[2]: Entering directory `/home/arwel/NetBeansProjects/callOctave_new'
mkdir -p build/Debug/GNU-Linux
rm -f "build/Debug/GNU-Linux/calloctave.o.d"
g++    -c -g -I/usr/include/octave-5.2.0/octave -include /usr/include/octave-5.2.0/octave/mex.h -std=c++11 -fPIC  -MMD -MP -MF "build/Debug/GNU-Linux/calloctave.o.d" -o build/Debug/GNU-Linux/calloctave.o calloctave.cc
In file included from /usr/include/octave-5.2.0/octave/Cell.h:33:0,
                 from /usr/include/octave-5.2.0/octave/gtk-manager.h:32,
                 from /usr/include/octave-5.2.0/octave/interpreter.h:36,
                 from calloctave.cc:7:
/usr/include/octave-5.2.0/octave/ov.h:52:7: error: using typedef-name ‘mxArray’ after ‘class’
 class mxArray;
       ^
In file included from <command-line>:0:0:
/usr/include/octave-5.2.0/octave/mex.h:55:14: note: ‘mxArray’ has a previous declaration here
 typedef void mxArray;
              ^
In file included from /usr/include/octave-5.2.0/octave/ov.h:62:0,
                 from /usr/include/octave-5.2.0/octave/Cell.h:33,
                 from /usr/include/octave-5.2.0/octave/gtk-manager.h:32,
                 from /usr/include/octave-5.2.0/octave/interpreter.h:36,
                 from calloctave.cc:7:
/usr/include/octave-5.2.0/octave/ov-base.h:57:7: error: using typedef-name ‘mxArray’ after ‘class’
 class mxArray;
       ^
In file included from <command-line>:0:0:
/usr/include/octave-5.2.0/octave/mex.h:55:14: note: ‘mxArray’ has a previous declaration here
 typedef void mxArray;
              ^
calloctave.cc: In function ‘int mexCallOctave(int, mxArray**, int, mxArray**, const char*)’:
calloctave.cc:26:15: error: ‘mxArray’ is not a class, namespace, or enumeration
     args(i) = mxArray::as_octave_value (argin[i]);
               ^
calloctave.cc:42:41: error: invalid use of ‘mxArray {aka void}’
       argout[i] = new mxArray (retval(i));
                                         ^
calloctave.cc: In function ‘void free_arg_list(int, mxArray**)’:
calloctave.cc:56:29: warning: deleting ‘mxArray* {aka void*}’ is undefined [enabled by default]
             delete arglist[i];
                             ^
gmake[2]: *** [build/Debug/GNU-Linux/calloctave.o] Error 1
gmake[2]: Leaving directory `/home/arwel/NetBeansProjects/callOctave_new'
gmake[1]: *** [.build-conf] Error 2
gmake[1]: Leaving directory `/home/arwel/NetBeansProjects/callOctave_new'
gmake: *** [.build-impl] Error 2

BUILD FAILED (exit value 2, total time: 1s)

It seems to be not understanding the mex interface in some way. I'm not very knowledgeable about c/c++, so am at a loss as to how to proceed here. What could be causing these errors and how might I resolve them??

Cheers, Arwel