mercredi 31 mars 2021

Weird error for implicit constructor on std::array implementation

#include "array.hpp"

int main() {
    constexpr array<int, 5> a1 = { { 2, 4, 6, 8 } };
}

Here is my code ^

I searched up, and it was said for an implicit constructor to do { { blah, blah, blah } } like this, but still didn't work. I also just did a uniform brace initialization syntax (a1 = { 2, 4, 6, 8 }) but didn't work.

Error:

main.cpp: In function ‘int main()’:
main.cpp:5:57: error: could not convert ‘2’ from ‘<brace-enclosed initializer list>’ to ‘const xstl::array<int, 5>’
    5 |     constexpr xstl::array<int, 5> a1 = { { 2, 4, 6, 8 } };
      |                                                         ^
      |                                                         |
      |                                                         <brace-enclosed initializer list>
main.cpp:6:57: error: could not convert ‘1’ from ‘<brace-enclosed initializer list>’ to ‘const xstl::array<int, 5>’
    6 |     constexpr xstl::array<int, 5> a2 = { { 1, 3, 5, 7 } };
      |                                                         ^
      |                                                         |
      |                                                         <brace-enclosed initializer list>

I don't understand the error because the constructor is implicit?

Why is this aggregate erroring? Why is the std::array implementation working while this implementation does not?

Here is the implementation, not too much:

#ifndef HEADER_ARRAY_HPP
#define HEADER_ARRAY_HPP

#include <cstddef>
#include <iterator>
#include <stdexcept>

template <class T, std::size_t N>
struct array {
    using value_type = T;
    using size_type = std::size_t;
    using difference_type = std::ptrdiff_t;
    using reference = value_type&;
    using const_reference = const value_type&;
    using pointer = value_type*;
    using const_pointer = const value_type*;
    using iterator = value_type*;
    using const_iterator = const value_type*;
    using reverse_iterator = std::reverse_iterator<iterator>;
    using const_reverse_iterator = std::reverse_iterator<const_iterator>;

    const_reference at(size_type pos) const {
        return pos < size() ? Data[pos] : throw std::out_of_range("");
    }

    const_reference operator[](size_type pos) const {
        return Data[pos];
    }

    reference front() {
        return *begin();
    }

    const_reference front() const {
        return *begin();
    }

    reference back() {
        return *std::prev(end());
    }

    const_reference back() const {
        return *std::prev(end());
    }

    T *data() noexcept {
        return Data;
    }

    const T *data() const noexcept {
        return Data;
    }

    iterator begin() noexcept {
        return Data;
    }

    const_iterator begin() const noexcept {
        return Data;
    }

    const_iterator cbegin() const noexcept {
        return Data;
    }

    iterator end() noexcept {
        return Data + size();
    }

    const_iterator end() const noexcept {
        return Data + size();
    }

    const_iterator cend() const noexcept {
        return Data + size();
    }

    reverse_iterator rbegin() noexcept {
        return reverse_iterator(end());
    }

    const_reverse_iterator rbegin() const noexcept {
        return const_reverse_iterator(end());
    }

    const_reverse_iterator crbegin() const noexcept {
        return const_reverse_iterator(end());
    }

    reverse_iterator rend() noexcept {
        return reverse_iterator(begin());
    }

    const_reverse_iterator rend() const noexcept {
        return const_reverse_iterator(begin());
    }

    const_reverse_iterator crend() const noexcept {
        return const_reverse_iterator(begin());
    }

    constexpr bool empty() const noexcept {
        return begin() == end();
    }

    constexpr size_type size() const noexcept {
        return N;
    }

    constexpr size_type max_size() const noexcept {
        return N;
    }

    void fill(const T& value) {
        size_type i = 0;

        for (; i < size(); i++) {
            Data[i] = value;
        }
    }

    void swap(array& other) noexcept {
        size_type i;

        for (i = 0; i < other.size(); i++) {
            other.Data[i] = Data[i];
        }

        for (i = 0; i < size(); i++) {
            Data[i] = other.Data[i];
        }
    }

private:
    T Data[N];
};

#endif // HEADER_ARRAY_HPP

How to ignore word in a certain position in lines being read?

My code first opens the file and gets each line from it, each line taking the form:

HEX_NUM CHAR HEX_NUM

The code I have is

stringstream s( line );
s >> std::hex >> addr >> letter >> std::hex >> target ; 

However, I would like to only get the CHAR section (without having the create the variables addr and target). How can I rewrite the 2nd line of my code to do so?

getting a segfault when I try to deep copy `unique_ptr`s

Why can't I return a unique_ptr from a clone function? I thought I could do this.

I have a base class for different mathematical functions called transform. I have a container of pointers to this type because I am using polymorphism. For example, all these derived classes have a different implementation of log_jacobian that is useful for statistical algorithms.

I am using unique_ptrs to this transform class, and so I have made a (pure virtual) clone function that makes new unique_ptr pointing to a deep copy of the same mathematical transform object. This new object is of the same type that derives from transform<float_t>, but it's a separate because you can't have two unique_ptrs pointing to the same thing.

template<typename float_t>
class transform{
...
virtual std::unique_ptr<transform<float_t>> clone() const = 0;
...
};

My transform_container class holds a few of these at a time. After all, most statistical models have more than one parameter.

template<typename float_t, size_t numelem>
class transform_container{
private:

    using array_ptrs = std::array<std::unique_ptr<transform<float_t>>, numelem>;
    array_ptrs m_ts;
    unsigned m_add_idx;
...
    auto get_transforms() const -> array_ptrs;
};

I'm not sure why the deep copy function get_transforms isn't working, though. It is used to make copies, and to access individual transformations from the container. I get a segfault when I run some tests. If I run it in gdb, it explicitly tells me the line with a comment after it is bad.

template<typename float_t, size_t numelem>
auto transform_container<float_t,numelem>::get_transforms() const -> array_ptrs
{
    array_ptrs deep_cpy;
    for(size_t i = 0; i < numelem; ++i){
        deep_cpy[i] = m_ts[i]->clone(); // this line
    }
    return deep_cpy;
}

I've also tried std::moveing it into deep_cpy[i] and using unique_ptr::reset, but to no avail.

Edit:

here are some other relevant methods: a method that adds transforms to transform_container, and the factory method for the individual transform:

template<typename float_t>
std::unique_ptr<transform<float_t> > transform<float_t>::create(trans_type tt)
{
    if(tt == trans_type::TT_null){
        
        return std::unique_ptr<transform<float_t> >(new null_trans<float_t> );
    
    }else if(tt == trans_type::TT_twice_fisher){
        
        return std::unique_ptr<transform<float_t> >(new twice_fisher_trans<float_t> );
    
    }else if(tt == trans_type::TT_logit){
        
        return std::unique_ptr<transform<float_t> >(new logit_trans<float_t> );
    
    }else if(tt == trans_type::TT_log){

        return std::unique_ptr<transform<float_t> >(new log_trans<float_t> );
    
    }else{

        throw std::invalid_argument("that transform type was not accounted for");
    
    }
}

template<typename float_t, size_t numelem>
void transform_container<float_t, numelem>::add_transform(trans_type tt)
{
    m_ts[m_add_idx] = transform<float_t>::create(tt);
    m_add_idx++;
}

Template parametric type Allocator in C++

I have the following toy code that works:

#include <cstdlib>
#include <vector>

template <typename T>
struct Dummy {
        using value_type = T;
        using size_type = size_t;
        using difference_type = ptrdiff_t;
        using pointer = value_type*;
        using const_pointer = const value_type*;
        using reference = value_type&;
        using const_reference = const value_type&;

        Dummy() = default;
        Dummy(const Dummy&) = default;
        
        pointer allocate(size_type n, const void* hint = 0) {
                (void)hint;
                return static_cast<pointer>(aligned_alloc(128, n * sizeof(T)));
        }

        void deallocate(void* p, size_type) {
                if (p)
                        free(p);
        }
};

int main()
{
        
        std::vector<int, Dummy<int, 16>> v;
        
        
        for (size_t i = 1; i < 5000; ++i)
                v.push_back(i);
        
        
        return 0;
}

Now I would like to templetize (not to put in the constructor) the alignment. I try to add to the template a integer parameter

template <typename T, size_t align>
struct Dummy {
        using value_type = T;
        using size_type = size_t;
        using difference_type = ptrdiff_t;
        using pointer = value_type*;
        using const_pointer = const value_type*;
        using reference = value_type&;
        using const_reference = const value_type&;

        Dummy() = default;
        Dummy(const Dummy&) = default;

        pointer allocate(size_type n, const void* hint = 0) {
                (void)hint;
                return static_cast<pointer>(aligned_alloc(align, n * sizeof(T)));
        }

        void deallocate(void* p, size_type) {
                if (p)
                        free(p);
        }
};

int main()
{
        
        std::vector<int, Dummy<int, 128>> v;
        
        
        for (size_t i = 1; i < 5000; ++i)
                v.push_back(i);
        
        
        return 0;
}

I'm getting a lot of compilation error both with g++ and clang++: for instance

/usr/include/c++/10.2.0/bits/alloc_traits.h:78:11: error: no type named 'type' in 'struct std::__allocator_traits_base::__rebind<Dummy<int, 128>, int, void>'
   78 |     using __alloc_rebind
      |           ^~~~~~~~~~~~~~
In file included from /usr/include/c++/10.2.0/vector:67,
                 from aligned.cpp:4:
/usr/include/c++/10.2.0/bits/stl_vector.h: In instantiation of 'class std::vector<int, Dummy<int, 128> >':
aligned.cpp:62:43:   required from here
/usr/include/c++/10.2.0/bits/stl_vector.h:474:20: error: '_M_allocate' has not been declared in 'std::_Base<int, Dummy<int, 128> >'
  474 |       using _Base::_M_allocate;
      |                    ^~~~~~~~~~~
/usr/include/c++/10.2.0/bits/stl_vector.h:475:20: error: '_M_deallocate' has not been declared in 'std::_Base<int, Dummy<int, 128> >'
  475 |       using _Base::_M_deallocate;

I do not understand what is going on. I notice that even if I do not use align in the class the compiler complaints the same way. If instead I put an unused typename inside the template everything is compiling fine. Can you help me?

Using C++ to read a file on a remote Linux-type server

I am building a small network of Raspberry Pi's using Raspian with samba file sharing. I want each to be able to read/write small text files to the others, to provide a very simple method of process co-ordination. I am a testing the method with one Pi with a single shared file and can read/write to it from an Ubuntu laptop, using its desktop file manager. I am trying to do the same programmatically:

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

void read_file () {
    string line;
    
    ifstream myfile;
    myfile.open("\\\\192.168.1.78\\home\\pi\\new2.txt");
    if (myfile.is_open()){
        cout << "file is open" << endl;
            getline(myfile, line);
            cout<< line << endl;
    } else {
        perror("Error");
    }   
    myfile.close();
}

int main(){
    read_file();
}

The error message is 'No such file or directory'. I'm guessing this is either a permissions problem I've not seen (the remote file is shared as 777) or the way I'm referencing the server and folder. I've tried numerous combinations to no avail.

Any suggestions?

Compiler error when creating an object using templated constructor

I am seeing a compiler error when I try to create an object of type 'F'. The constructor takes a std::array as input but something is going wrong with the call to the relevant constructor. The minimal code and compiler output are shown below:

#include <iostream>
#include <array>

using namespace std;


template < class T >
class F
{
    public:
        typedef T* iter;
        typedef const T* const_iter;
        
        F() : s_(0), c_(0) {}
        
        template < unsigned U >
        F( std::array<T, U>& arr ) : begin_(arr.begin()), end_(arr.end()), s_(0), c_(U) {}
        
    private:
        T* begin_;
        T* end_;
        std::size_t s_;
        std::size_t c_;
        
        F( const F& );
        F& operator=( const F& );
};

int main()
{
   cout << "Hello World" << endl; 
   
   std::array<int16_t, 45> arrayTemp;
   F<int16_t> arr1(arrayTemp); //This line causes the error
   
   
   return 0;
}

Compiler output (https://www.tutorialspoint.com/compile_cpp11_online.php, gcc v 7.1.1):

$g++ -std=c++11 -o main *.cpp
main.cpp: In function ‘int main()’:
main.cpp:34:29: error: no matching function for call to ‘F<short int>::F(std::array<short int, 45>&)’
    F<int16_t> arr1(arrayTemp);
                             ^
main.cpp:25:9: note: candidate: F<T>::F(const F<T>&) [with T = short int]
         F( const F& );
         ^
main.cpp:25:9: note:   no known conversion for argument 1 from ‘std::array<short int, 45>’ to ‘const F<short int>&’
main.cpp:17:9: note: candidate: template<unsigned int U> F<T>::F(std::array<T, U>&)
         F( std::array<T, U>& arr ) : begin_(arr.begin()), end_(arr.end()), s_(0), c_(U) {}
         ^
main.cpp:17:9: note:   template argument deduction/substitution failed:
main.cpp:34:29: note:   mismatched types ‘unsigned int’ and ‘long unsigned int’
    F<int16_t> arr1(arrayTemp);
                             ^
main.cpp:14:9: note: candidate: F<T>::F() [with T = short int]
         F() : s_(0), c_(0) {}
         ^
main.cpp:14:9: note:   candidate expects 0 arguments, 1 provided

how to find if M is actually an output of 2power(2n) + 1 in C program

I have a tricky requirement in project asking to write funtion which returns a value 1(0 otherwise). if given an integer representable a (2^2n)+1. n being any non-negative integer . int find_pow_2n_1(int M);

for e.g: return 1, when M=5 since 5 is output when n=1 -> (2^1*2)+1 .

I am trying to evaluate the equation but it results in log funtion , not able to find any kind of hint while browsing in google as well .

Could I use the Overloaded 'new' operator with original 'new ' together?

I have wrote a cpp as follow to overload the new operator.

    void* operator new(size_t size)
{
    //return malloc(size);
    return MemoryMgr::Instance().allocMem(size); 
}


void operator delete(void* p)
{
    MemoryMgr::Instance().freeMem(p);
}

void* operator new[](size_t size)
{
    return MemoryMgr::Instance().allocMem(size);
}


void operator delete[](void* p)
{
    MemoryMgr::Instance().freeMem(p);
}


void* mem_alloc(size_t size)
{
    return MemoryMgr::Instance().allocMem(size);
}

void mem_free(void* p)
{
    free(p);
}

However, in the main function, sometime I want to ues original new. But the computer always calls the overloaded new. Then I have tried the ::new.But it doesn't make sense. Which way that I can use both overloaded new and original new ? Put the void* operator new in a specialized class which need to be overload new function?

mardi 30 mars 2021

Does std::move helps with objects on stack?

I just saw a college doing this optimization today:

enter image description here

i.e., change this:

std::string somestring =  "somestring";
std::map<std::string, int> myglobalmap;

std::string myfunction( const std::string& mystring, int myint )
{
    myglobalmap.insert( std::pair<std::string, int>( mystring, myint ) );
}
myfunction(somestring, 10)

To:

std::string somestring =  "somestring";
std::map<std::string, int> myglobalmap;

std::string myfunction( std::string mystring, int myint )
{
    myglobalmap[ std::move(mystring) ] = myint;
}
myfunction(somestring, 10)

He claimed that passing the value mystring by copy instead of passing it as a constant reference would be faster because the move operation would be only performed with objects on the stack. But I could not see why this would help. I searched about the move operator and I found out it does not move anything, it just makes my expression to return a reference.

Then, if this is true, passing the value by copy would not be slower than passing it by reference and calling std::move or does calling std::move help with objects on the stack in this case? If I understand correctly, std::move should only help with objects on the heap. Then, calling it with something on the stack should not help or it does?

Related questions:

  1. What is std::move(), and when should it be used?
  2. Is it possible to std::move local stack variables?

std::thread member object crashes on destruction in terminate

I have a program where I want to run one of my classes in a separate thread with a higher priority than the rest of the program and I want it to update the GUI as it processes so I'm using std::thread.

GUI.h

#include <thread>

class GUI
{
private:
   Worker worker;

   std::thread workerThread;

public:
   GUI ();
   ~GUI ();

   void runWorker ();
}

GUI.cpp

GUI::GUI ()
{
}

GUI::~GUI()
{
}

void GUI::runWorker()
{
   workerThread = std::thread (&Worker::run, worker);
}

Worker.h

class Worker
{
public:
   void run ();
}

Worker.cpp

void Worker::run ()
{
   unsigned int numItems = 70;

   for (unsigned int i = 0 ; i < numItems ; i++)
   {
      try
      {
         processItem (i);
      }
      catch (exception &e)
      {
         std::cout << "Error processing item " << i << std::endl;

         break;
      }
   }
}

My problem is whether Worker::run finishes cleanly or if there is an exception it will end and when I try to call the destructor for GUI it crashes in std::terminate in std::thread.

Is this a problem because the std::thread no longer exists because the Worker has already finished? How can I keep the GUI destructor from calling the std::thread destructor if Worker::run has already finished?

method for downcasting to child class with type deduction

The crux of the issue is I want to create a vector of base pointers to reference children objects. However I'm having issues accessing the methods of the children. I've seen examples of downcasting online but I don't feel it's the best thing for me since I want to keep my code generic. Please look below for a sample of what I'm trying to accomplish.

class Base
{
public:
    stuffx;
private:
    stuffy;
}

template<typename U>
class Child : public Base
{
public:
    Child(
          std::function<U()> getterFunc,
          std::function<void(U)> setterFunc
          ):
          mgetter(getterFunc),
          msetter(setterFunc)
    {
    }
    std::function<U()>& getGFunction() const {return m_getter;}
    std::function<void(U)>& getSFunction() const {return m_setter;}

private:

    observableValues() {}
    std::function<U()> m_getter;
    std::function<void(U)> m_setter;
}

int main()
{
    std::vector<std::shared_ptr<Base>> Dummy = {std::make_shared<Child<int>> (std::bind(..),     std::bind(...)),
                                                std::make_shared<Child<string>> (std::bind(..),     std::bind(...)) };
    Dummy.at(0)->getGFunction(); // this throws an error as out of scope.
    (dynamic_cast<Child<int>>(Dummy.at(0))->getGFunction(); // this is ok
}

In this example above my vector is of size 2 which is manageable but my goal is to serialize c++ classes to a psql server and may have to handle vectors of size 30+. My next question is is there a way to automate this in a for loop taking into the account the type deduction that may need to be performed for typename U.

int main()
{
    std::vector<std::shared_ptr<Base>> Dummy = {std::make_shared<Child<int>> (std::bind(..),     std::bind(...)),
                                                std::make_shared<Child<string>> (std::bind(..),     std::bind(...)) };
     std::vector<std::shared_ptr<Base>>::const_iterator it_base = Dummy.begin();
     for (; it_base != Dummy.end(); ++it_base)
     {
         //insert method here for downcasting
     }
}

Should I write noexcept only to constructors and move operators?

There is a quite (very) popular question about the usage of noexcept, but it's from 8 years ago, and other popular answers are just as old. Seeing some code from other people in different projects, it seems to me that noexcept didn't become a very common thing for many developers to write.

Besides move constructor and move assignment operator, the benefit of using noexcept doesn't seems clear enough to think about for every function ("should I add noexcept here or not?").

Has somebody found a good usage of this specifier, and can share their experience?

Trying to throw a range error if array index is out of bounds (C++)

I am trying to get my program to throw a stdexcept range_error if the array index my function is accessing is out of bounds. The type passed in is of size_t because the memory location in the stack may be signed or unsigned. Here is what I have tried:

MyClass::MyClass(){ // default constr
    size = 10;
    ptr = new int[size];
} 

int MyClass::at(size_t position) const
{
    try
    {
        return ptr[pos];
    }
    catch (const std::range_error&)
    {
        cout << "Range Error" << endl;
    }
    
}

int main() {
    // Test exceptions
    MyClass a;
    throw_(a.at(0), range_error);
}

If anyone can please help correct my function so it throws a range_error when the index is out of bounds, that would be greatly appreciated!

Problems including OpenSSL for eclipse

I am trying to include the recent version (1.1.1) of OpenSSL in eclipse. I am looking to use some crypto related functions from OpenSSL in my code. So I unzipped the folder and added the 'include' folder of OpenSSL to settings->path (just as I do for any other include folder). However, when I try to compile, it gives me an error "opensslconf.h does not exist". So when I go to the include folder, I see that although there is a file named opensslconf.h, it is actually a .IN file, so essentially, it is opensslconf.h.in, which is why the compiler is not able to recognize it. Also, simply changing the file type to .h wont work because it has some scripting which is used in .IN files and those will give errors while compiling. Is there a way around this issue? Thanks so much in advance.

basic_streambuf

We have a file which is present in a data store (S3) which contains data in the form of byte[] (uploaded using Java language).

Now when i download the file, the data i get is in the form of std::basic_streambuf (Ideally it should also be having bytes). Now i want to send this data to another API which takes uint8_t* as the input.

What is the way to do so? Is it making any sense to even do that?

I tried this:


// Assume streambuf is:
std::streambuf *buf;

std::stringstream ss;
ss << buf;

// Solution1
const std::string output1 = ss.str(); 
cout<<output1;
// This prints the whole data with some weird characters (i think weird characters are valid because data is in byte form). Upon converting output1 to uint8_t*, the final data contains only 20 characters/bytes.

// Solution2
uint8_t* finalString;
ss >> finalString;
cout<<finalString;
// This prints only initial 20 characters/bytes and the remaining part is skipped.

So with both Solution1 and Solution2, ultimate goal of getting uint8_t* of full data could not be achieved. What is the suggested way to do so?

shared pointer to a base class where child is a template class

The crux of the issue is I want to create a vector of base pointers to reference children objects. However I'm having issues accessing the methods of the children. I've seen examples of downcasting online but I don't feel it's the best thing for me since I want to keep my code generic. Please look below for a sample of what I'm trying to accomplish.

class Base
{
public:
    stuffx;
private:
    stuffy;
}

template<typename U>
class Child : public Base
{
public:
    Child(
          std::function<U()> getterFunc,
          std::function<void(U)> setterFunc
          ):
          mgetter(getterFunc),
          msetter(setterFunc)
    {
    }
    std::function<U()>& getGFunction() const {return m_getter;}
    std::function<void(U)>& getSFunction() const {return m_setter;}

private:

    observableValues() {}
    std::function<U()> m_getter;
    std::function<void(U)> m_setter;
}

int main()
{
    std::vector<std::shared_ptr<Base>> Dummy = {std::make_shared<Child<int>> (std::bind(..), std::bind(...)),
                                                std::make_shared<Child<string>> (std::bind(..), std::bind(...)) };
    Dummy.at(0)->getGFunction(); // this throws an error as out of scope.
}

Is there a way to get access to those public methods in C++11 without downcasting and specifying the type U when doing so?

unordered_map is not able to initialise in working C++?

Question: Given an array of strings strs, group the anagrams together. You can return the answer in any order.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Example 1:

Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]

Code:

class Solution
{
public:
    vector<vector<string>> groupAnagrams(vector<string> &strs)
    {
        unordered_map <unordered_multiset <char>, vector<string>> mp1;
        for (c : strs)
        {
            unordered_multiset<char> ms1;
            for (char h : c)
                m1.insert(h);
            mp1[ms1].push_back(c);
        }
        vector<vector<string>> res;
        for (auto c : mp1)
            res.push_back(c.second);
        return res;
    }
};

Error:

Line 6: Char 67: error: call to implicitly-deleted default constructor of 'unordered_map<unordered_multiset<char>, vector<std::string>>' (aka 'unordered_map<unordered_multiset<char>, vector<basic_string<char>>>')
        unordered_map <unordered_multiset <char>, vector<string>> mp1;
                                                                  ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/unordered_map.h:141:7: note: explicitly defaulted function was implicitly deleted here
      unordered_map() = default;
      ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/unordered_map.h:105:18: note: default constructor of 'unordered_map<std::unordered_multiset<char, std::hash<char>, std::equal_to<char>, std::allocator<char>>, std::vector<std::__cxx11::basic_string<char>, std::allocator<std::__cxx11::basic_string<char>>>, std::hash<std::unordered_multiset<char, std::hash<char>, std::equal_to<char>, std::allocator<char>>>, std::equal_to<std::unordered_multiset<char, std::hash<char>, std::equal_to<char>, std::allocator<char>>>, std::allocator<std::pair<const std::unordered_multiset<char, std::hash<char>, std::equal_to<char>, std::allocator<char>>, std::vector<std::__cxx11::basic_string<char>, std::allocator<std::__cxx11::basic_string<char>>>>>>' is implicitly deleted because field '_M_h' has a deleted default constructor
      _Hashtable _M_h;
                 ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/hashtable.h:414:7: note: explicitly defaulted function was implicitly deleted here
      _Hashtable() = default;
      ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/hashtable.h:174:7: note: default constructor of '_Hashtable<std::unordered_multiset<char, std::hash<char>, std::equal_to<char>, std::allocator<char>>, std::pair<const std::unordered_multiset<char, std::hash<char>, std::equal_to<char>, std::allocator<char>>, std::vector<std::__cxx11::basic_string<char>, std::allocator<std::__cxx11::basic_string<char>>>>, std::allocator<std::pair<const std::unordered_multiset<char, std::hash<char>, std::equal_to<char>, std::allocator<char>>, std::vector<std::__cxx11::basic_string<char>, std::allocator<std::__cxx11::basic_string<char>>>>>, std::__detail::_Select1st, std::equal_to<std::unordered_multiset<char, std::hash<char>, std::equal_to<char>, std::allocator<char>>>, std::hash<std::unordered_multiset<char, std::hash<char>, std::equal_to<char>, std::allocator<char>>>, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, std::__detail::_Prime_rehash_policy, std::__detail::_Hashtable_traits<true, false, true>>' is implicitly deleted because base class '__detail::_Hashtable_base<unordered_multiset<char, hash<char>, equal_to<char>, allocator<char>>, pair<const unordered_multiset<char, hash<char>, equal_to<char>, allocator<char>>, vector<basic_string<char>, allocator<basic_string<char>>>>, _Select1st, equal_to<unordered_multiset<char, hash<char>, equal_to<char>, allocator<char>>>, hash<unordered_multiset<char, hash<char>, equal_to<char>, allocator<char>>>, _Mod_range_hashing, _Default_ranged_hash, _Hashtable_traits<true, false, true>>' has a deleted default constructor
    : public __detail::_Hashtable_base<_Key, _Value, _ExtractKey, _Equal,
      ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/hashtable_policy.h:1822:5: note: explicitly defaulted function was implicitly deleted here
    _Hashtable_base() = default;
    ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/hashtable_policy.h:1771:5: note: default constructor of '_Hashtable_base<std::unordered_multiset<char, std::hash<char>, std::equal_to<char>, std::allocator<char>>, std::pair<const std::unordered_multiset<char, std::hash<char>, std::equal_to<char>, std::allocator<char>>, std::vector<std::__cxx11::basic_string<char>, std::allocator<std::__cxx11::basic_string<char>>>>, std::__detail::_Select1st, std::equal_to<std::unordered_multiset<char, std::hash<char>, std::equal_to<char>, std::allocator<char>>>, std::hash<std::unordered_multiset<char, std::hash<char>, std::equal_to<char>, std::allocator<char>>>, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, std::__detail::_Hashtable_traits<true, false, true>>' is implicitly deleted because base class '_Hash_code_base<std::unordered_multiset<char, std::hash<char>, std::equal_to<char>, std::allocator<char>>, std::pair<const std::unordered_multiset<char, std::hash<char>, std::equal_to<char>, std::allocator<char>>, std::vector<std::__cxx11::basic_string<char>, std::allocator<std::__cxx11::basic_string<char>>>>, std::__detail::_Select1st, std::hash<std::unordered_multiset<char, std::hash<char>, std::equal_to<char>, std::allocator<char>>>, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, _Hashtable_traits<true, false, true>::__hash_cached::value>' has a deleted default constructor
  : public _Hash_code_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash,
    ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/hashtable_policy.h:1373:7: note: explicitly defaulted function was implicitly deleted here
      _Hash_code_base() = default;
      ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/hashtable_policy.h:1349:7: note: default constructor of '_Hash_code_base<std::unordered_multiset<char, std::hash<char>, std::equal_to<char>, std::allocator<char>>, std::pair<const std::unordered_multiset<char, std::hash<char>, std::equal_to<char>, std::allocator<char>>, std::vector<std::__cxx11::basic_string<char>, std::allocator<std::__cxx11::basic_string<char>>>>, std::__detail::_Select1st, std::hash<std::unordered_multiset<char, std::hash<char>, std::equal_to<char>, std::allocator<char>>>, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, true>' is implicitly deleted because base class '_Hashtable_ebo_helper<1, std::hash<std::unordered_multiset<char, std::hash<char>, std::equal_to<char>, std::allocator<char>>>>' has a deleted default constructor
      private _Hashtable_ebo_helper<1, _H1>,
      ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/hashtable_policy.h:1096:7: note: explicitly defaulted function was implicitly deleted here
      _Hashtable_ebo_helper() = default;
      ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/hashtable_policy.h:1094:7: note: default constructor of '_Hashtable_ebo_helper<1, std::hash<std::unordered_multiset<char, std::hash<char>, std::equal_to<char>, std::allocator<char>>>, true>' is implicitly deleted because base class 'std::hash<std::unordered_multiset<char, std::hash<char>, std::equal_to<char>, std::allocator<char>>>' has a deleted default constructor
    : private _Tp
      ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/functional_hash.h:101:19: note: default constructor of 'hash<std::unordered_multiset<char, std::hash<char>, std::equal_to<char>, std::allocator<char>>>' is implicitly deleted because base class '__hash_enum<std::unordered_multiset<char, std::hash<char>, std::equal_to<char>, std::allocator<char>>>' has no default constructor
    struct hash : __hash_enum<_Tp>
                  ^

Not able to use to_string in Code Blocks IDE [closed]

string s= to_string(x);

I am trying to convert int to string by using Code Blocks IDE 16.01. Previously I checked the option of using C++ 11 from the settings but it is still showing error of "multiple definition of vsnprintf" Can someone help me how to resolve the issue? enter image description here

How to get error from popen/system script?

I would like to be able to enable the bash script in a C ++ program and catch any error number from it. Exactly what I mean is the "pon" script that manages pppd. Below I am pasting its contents:

#!/bin/sh

PPP_ON_BOOT=/etc/ppp/ppp_on_boot

case "$1" in
  -*) echo "
Usage: pon [provider] [arguments]

If pon is invoked without arguments, $PPP_ON_BOOT file will be
run, presuming it exists and is executable. Otherwise, a PPP connection
will be started using settings from /etc/ppp/peers/provider.
If you specify one argument, a PPP connection will be started using
settings from the appropriate file in the /etc/ppp/peers/ directory, and
any additional arguments supplied will be passed as extra arguments to
pppd.
"
      exit 0
      ;;
esac

if [ -z "$1" -a -x "$PPP_ON_BOOT" ]; then
  exec "$PPP_ON_BOOT"
fi

if [ -z "$1" -a ! -f /etc/ppp/peers/provider ]; then
  echo "
Please configure /etc/ppp/peers/provider or use a command line argument to
use another file in /etc/ppp/peers/ directory.
"
  exit 1
fi

if [ "$1" -a ! -f "/etc/ppp/peers/$1" ]; then
  echo "
The file /etc/ppp/peers/$1 does not exist.
"
  exit 1
fi

exec /usr/sbin/pppd call ${@:-provider}

It starts the pppd daemon which, according to the documentation (https://linux.die.net/man/8/pppd), returns a series of errors, such as:

1 Pppd has detached, or otherwise the connection was successfully established and terminated at the peer's request.
2 An immediately fatal error of some kind occurred, such as an essential system call failing, or running out of virtual memory.
3 An error was detected in processing the options given, such as two mutually exclusive options being used.
4 Pppd is not setuid-root and the invoking user is not root. 

I would like my application to run the "pon" script and then if there is an error, hook it to an int variable. Then, a separate function with the switch converts the error into a message.

How could I do this on Linux? Will "popen" or "system" be better? Do I have to add in the "pon" script to read the value from the pppd error so that my application can get it?

lundi 29 mars 2021

use unique_ptr to wrap and unwrap void*

My goal is to create unique_ptr<void*> where void* can point to any object type. This gives me a way to use unique_ptr to point to state object that shares the same signature. But below code doesn't seem to match my expectation where p.get() should be equal to v and s1 address. I suspect it has to do the line that try to wrap a unqiue_ptr on top of s1 to own it. But address has changed.

struct State1 
{
public:
  std::string name;
  std::string address;
};

int main() {

  auto s1 = new State1;
  s1->name = "name";
  std::cout<<"s1 address: "<<s1<<"\n";
  auto v = (void*)s1;
  std::cout<<"v address: "<<v<<"\n";
  auto p = std::make_unique<void*>(s1);
  std::cout<<"p.get address: "<<p.get()<<"\n";
  auto r =  static_cast<State1*>((void*)p.get());
  std::cout<<"r address: "<<r<<"\n";
}

s1 address: 0x55dcf389aeb0
v address: 0x55dcf389aeb0
p.get address: 0x55dcf389b310
r address: 0x55dcf389b310

Best options for replacing std::string. - Is there a macro that can do this?

I currently have a header file. That does has the following signature

void foo::GetInfo(const std::string, std::string& str);

Now this signature needs to change to

void foo::GetInfo(const char*, char* str);

Now In my code there are bunch of scattered files that use this header file like this

std::string result;
inst->GetInfo(SomeString, result); //This will not work now

What I am looking for is a macro. A macro that I can wrap this statement in. Basically something that will do this to the above statement that fails

char* ptemp;
inst->GetInfo(SomeString.c_str(),ptemp);
result =std::string(ptemp);
delete* ptemp;

so basically a cleaner way of doing all the above. Preferably something I can just wrap the unworking string in

MagicMacro(inst->GetInfo(SomeString, result));

I am really not looking for exactly a macro, but something that might assist in cleaning up this entire code or atleast make it easier for me to do the change and less verbose. I am open to directions.

How to pass a lambda to a template paramater

I'm trying to define a function func, which returns a std::string.

template<typename T = std::string, template<typename> typename F = decltype([](const T &t){return t;})>
std::string func(const T &t){
    F f;
    return f(t);
}

As you see, what I'm trying to do is to pass a lambda as the template paramater so that I can call the function func like this:

func<int, decltype([](int a){return std::to_string(a);})>(2);

Also, I set the values by default for the template parameters so that I can call it like this:

func<>("abc");

However, the code above gave me an error:

<source>:39:54: error: expected unqualified-id before 'decltype'
   39 | template<typename T, template<typename> typename F = decltype([](const T &t){return t;})>
      |                                                      ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<source>:39:54: error: invalid default argument for a template template parameter
<source>:39:54: error: expected '>' before 'decltype'

BTW, the version of my C++ is C++11.

How to do template pack expansion with C++11 attribute-list?

According to [temp.variadic#5.8]:

Pack expansions can occur in the following contexts:

  • In an attribute-list ([dcl.attr.grammar]); the pattern is an attribute.

which means we can do a pack expansion on attribute-list.

But I didn’t find any examples about it, and cppreference only showed a piece of code for it:

void [[attributes...]] function()

Under what circumstances do we want to do this? And how to do this? Can someone give an example?

error: request for member ‘..’ in ‘..’, which is of non-class type ‘..’

I started a simple big integer library project, and decided to take it up again. But I can get over this error I am getting.

template <typename T>
bigint(T a)
{
        // Constructor for bigint passed
        // Let's call this 'A'
        if (std::is_same<T, bigint>::value)
        {
            this -> n = a.n;
        }

        // Check if passed argument is a float
        else if (std::is_same<T, float>::value or std::is_same<T, double>::value)
        {
            // Type-caste to lose fractional part
            this -> n = std::to_string((long long) a);
        }

        // Check if passed argument is a string
        else if (std::is_same<T, const char*>::value or std::is_same<T, std::string>::value)
        {
            this -> n = a;
        }



        // Straight cast for integers
        // Let's call this 'B'
        else
        {
            this -> n = std::to_string(a);
        }
}

Now when I call the constructor for an int or any other data-type, the first bigint constructor A is called, when B should be called, even though the types are different.

>>> bigint a(100);
bigint.h:42:18: error: request for member ‘n’ in ‘a’, which is of non-class type ‘int’
   42 |    this -> n = a.n;
      |                ~~^

What will decrease the performance of multithread except lock and the cost of thread's create and destory?

I wrote a program which use std::thread::hardware_concurrency to get how much threads my computer could support.Then I divide the size of array by N and get N blocks. And I create N threads to calculate the sum of the block.Here is the code

#include <algorithm>
#include <chrono>
#include <functional>
#include <iostream>
#include <numeric>
#include <thread>
#include <vector>
#include <stdlib.h>

int64_t thread_cost_time = 0;



template <typename Iterator, typename T> struct accumulate_block {
  void operator()(Iterator first, Iterator last, T &result) {
    using namespace std::chrono;
    auto start = std::chrono::high_resolution_clock::now();
    result = std::accumulate(first, last, result);
    
    auto stop = std::chrono::high_resolution_clock::now();
    auto thread_time =
        std::chrono::duration_cast<microseconds>(stop - start).count();
    thread_cost_time = std::max(thread_time, thread_cost_time);
  }
};

template <typename Iterator, typename T>
T parallel_accumulate(Iterator first, Iterator last, T &init, uint64_t num) {

  uint64_t length = std::distance(first, last);
  const uint64_t min_per_thread = 25;

  // it will assign 12 to hard_ware_threads in my pc
  const uint64_t hardware_threads = std::thread::hardware_concurrency();
  const uint64_t max_threads = (length + min_per_thread - 1) / (min_per_thread);

  // const uint64_t  num_threads = std::min(hardware_threads != 0 ?
  // hardware_threads : 2,
  //                                         max_threads);

  const uint64_t num_threads = num;

  const uint64_t block_size = length / num_threads;

  std::vector<T> results(num_threads);
  std::vector<std::thread> threads(num_threads - 1);
  Iterator block_start = first;
  for (uint64_t i = 0; i < num_threads - 1; i++) {
    Iterator block_end = block_start;
    std::advance(block_end, block_size);

    // calculate the sum of block
    threads[i] = std::thread{accumulate_block<Iterator, T>(), block_start,
                             block_end, std::ref(results[i])};
    block_start = block_end;
  }
  accumulate_block<Iterator, T>()(block_start, last, results[num_threads - 1]);
  std::for_each(threads.begin(), threads.end(),
                std::mem_fn(&std::thread::join));

  return std::accumulate(results.begin(), results.end(), init);
}




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

  //    constexpr const uint64_t sz = 1000000000;
  for (int number = 2; number < 32; number++) {
    int64_t parr = 0;
    int64_t single = 0;
    int64_t thread_trivial = 0;
    std::cout
        << "--------------------------------------------------------------"
        << std::endl;
    std::cout << "---------------------thread: " << number
              << "-----------------------" << std::endl;
    int iter_times = 10;
    for (int iter = 0; iter < iter_times; iter++) {
      thread_cost_time = 0;
      constexpr const uint64_t sz = 100000000 ;
      std::vector<uint64_t> arr;
      for (uint32_t i = 0; i < sz; i++) {
        arr.emplace_back(i);
      }

      using namespace std::chrono;

      auto start = std::chrono::high_resolution_clock::now();
      uint64_t init = 0;
      parallel_accumulate<decltype(arr.begin()), uint64_t>(
                       arr.begin(), arr.end(), std::ref(init), number);
      auto stop = std::chrono::high_resolution_clock::now();

      parr += std::chrono::duration_cast<microseconds>(stop - start).count();

      thread_trivial +=
          std::chrono::duration_cast<microseconds>(stop - start).count() -
          thread_cost_time;
      uint64_t init_ = 0;
      uint64_t arr_sz = arr.size();
      // uint64_t  block_sz = arr.size() / 2;
      start = std::chrono::high_resolution_clock::now();
      std::accumulate(arr.begin(), arr.end(), init_);
      // std::cout << init_ << std::endl;
      stop = std::chrono::high_resolution_clock::now();
      single += std::chrono::duration_cast<microseconds>(stop - start).count();

    }
    std::cout << "parallel " << parr / iter_times<< std::endl;
    std::cout << "single thread " << single / iter_times<< std::endl;
    std::cout << "parr is "
              << static_cast<double>(single) / static_cast<double>(parr)
              << "X fast" << std::endl;
    std::cout << "thread create and destory time " << thread_trivial / iter_times
              << std::endl;
  }
}

I record the time of multithread and single thread.

I can only achieve at most 6.57x faster than use only one thread, even though std::thread::hardware_concurrency tell me I have 12 threads could run simultaneously.

There were no contention of lock in this program.I also record the time of create and destory the thread, even if I minus it , I still cannot achieve 12X faster.

I think maybe thread schedule will make multithreads slow, but I have 12 threads, It shouldn't achieve only 6.57x faster. I think maybe multithreads will decrease the hit ratio of cache,but I'm not quite sure. So how can I achieve 12X faster than use only one thread?

Here is my static of my program

threads parallel single faster
2 324868 633777 1.95
3 218584 633777 2.87
4 167169 633777 3.77
5 136542 633777 4.64
6 113207 633777 5.48
7 147324 633777 4.27
8 136768 633777 4.67

You could run my code to get the data from 2 threads to 31 threads

How to check if a std::function is set and valid?

I have an std::function which is being set like below:

typedef std::function<void(bool some_state)> TheListener;
void ListenTo(TheListener the_listener) {
    m_the_listener = the_listener;
}

How do I check if the std::function is set?

private:
    void SomePrivateMethod() {
        // How do I check here that m_the_listener is set by calling ListenTo ?
        m_the_listener();
    }

Is it enough to check if (m_the_listener) before calling m_the_listener() ?

begniners tutorial foe ARM compute library, how to execute, what are the inputs

some basic examples to run on hikey960 boards, how to understand the flow of the library ARM compute Library

C++: how to redefine getline() when using two overloads of it?

I need to use two types of getline in my program.
First:

template<> std::istream &std::getline<char, std::char_traits<char>, std::allocator<char>>(std::istream &__is, std::__cxx11::string &__str, char __delim)
+4 overloads

Read a line from an rvalue stream into a string.

which I use for In a while condition.

getline(strstrm, field,',')

where:

string line, field, temp;
stringstream strstrm(line);

But now When I try to use this getline:

getline(rowTemp, lineTemp);

I get a error. Here:

string lineTemp, wordTemp;
vector<string> rowTemp;

I have added the statement:

using namespace std;

I am using the following header files

#include<iostream>
#include<string>
#include<limits>
#include<fstream>
#include<iomanip>
#include<conio.h>
#include<vector>
#include<algorithm>

My error is

getline
+6 overloads

Read a line from stream into a string.

Parameters:
__is – Input stream.
__str – Buffer to store into.

Returns:
Reference to the input stream. Stores characters from is into __str until '

no instance of overloaded function "getline" matches the argument list -- argument types are: (std::vector<std::__cxx11::string, std::allocator<std::__cxx11::string>>, std::__cxx11::string)C/C++(304)

My entire code can be seen Here

I am kind of new to the c++. I would appreciate if someone could point me in the correct direction. Thank You.

dimanche 28 mars 2021

Access an index of a map from a pointer

I currently have this

struct test
{
 std::map<int, UINT64> ratio;
}

where pContext is a pointer to test

int group = 1;
auto a = (*pContext).ratio[group]; <---Error

In the above I get the following error

Severity    Code    Description Project File    Line    Suppression State
Error   C2678   binary '[': no operator found which takes a left-hand operand of type 'const std::map<int,UINT64,std::less<int>,std::allocator<std::pair<const int,UINT64>>>' (or there is no acceptable conversion)

Any suggesstion on how I can fix this ?

How do I parse comma-delimited string in C++ with some elements being quoted with commas?

I have a comma-delimited string that I want to store in a string vector. The string and vectors are:

string s = "1, 10, 'abc', 'test, 1';
vector<string> v;

Ideally I want the strings 'abc' and 'test, 1' to be stored without the single quotes as below, but I can live with storing them with single quotes:

v[0] = "1";
v[1] = "10";
v[2] = "abc";
v[3] = "test, 1";

Recursive function doesn't return the vector

I'm trying to create a list which contains 10 unique random numbers between 1 and 20 by using a recursive function. Here is the code.

Compiler: GNU g++ 10.2.0 on Windows

Compiler flags: -DDEBUG=9 -ansi -pedantic -Wall -std=c++11

#include <iostream>
#include <vector>
#include <algorithm>
#include <time.h>
using namespace std;

vector<int> random (int size, int range, int randnum, vector<int> randlist ) {
  if (size < 1) {
    cout << "returning...(size=" << size << ")" << endl;
    return randlist;
  }
  else {
    if (any_of(randlist.begin(), randlist.end(),[randnum](int elt) {return randnum == elt;})){
      cout << "repeating number: " << randnum << endl;
      random(size, range, rand() % range + 1, randlist);
      return randlist;
  }
    else {
      cout << "size " << size << " randnum " << randnum << endl;
      randlist.push_back(randnum);
      random(size-1, range, rand() % range + 1, randlist);
      return randlist; }
  }
}


int main (int argc, char *argv[]) {
  srand (time(NULL));
  vector<int> dummy{}; 
  vector<int> uniqrandnums = random(10, 20, (rand() % 20) + 1, dummy );
  cout << "here is my unique random numbers list: " ;
  for_each(uniqrandnums.begin(),uniqrandnums.end(), [](int n){cout << n << ' ';});
  }

To keep track of the unique random numbers, I've added 2 cout lines inside the recursive function random. The recursive function seems to operate correctly but it can't return back the resulting vector<int list randlist correctly; it seems to return a list with just the first random number it found.

Note: Reckoning that the function would finally return from here:

  if (size < 1) {
    cout << "returning...(size=" << size << ")" << endl;
    return randlist;
  }

I haven't initially added the last 2 return randlist; lines inside the recursive function but as is, it gave compilation warning control reaches end of non-void function [-Wreturn-type] That's why I've added those 2 return statements but it made just the warnings go away and it didn't help operate correctly.

Question: How to arrange the code so the recursive function random returns the full list in a correct manner?

Unknown error in inserting values in multimap

I have the following code, where I try to insert values into a multimap of 2 strings, but I keep getting an error that I cannot understand. I've been trying to solve this for hours.

The whole point of the program is to sort the lines of a dictionary based on the automatic sorting of the multimap insertion.

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

#include <iostream>
#include <fstream>
#include <vector>
#include <map>
#include <string>
#include <algorithm>
#include <iomanip>
#include <sstream>

// Prototypes
int indexDict(std::multimap<std::string, std::string>& dict);


int main()
{
    std::multimap<std::string, std::string> dict;
    
    if(indexDict(dict) == 0)
        return 0;


}


int indexDict(std::multimap<std::string, std::string>& dict)
{
    std::ifstream inputFile{ "output.txt", std::ios::in };
    std::string currentDictEntry{};
    size_t currentLine{};

    if (!inputFile)
    {
        std::cerr << "input.txt FILE NOT FOUND in the current directory" << std::endl;
        system("pause");
        return 0;
    }

    while (std::getline(inputFile, currentDictEntry))
    {
        //std::cout << currentDictEntry << std::endl; // TO DELETE

        std::string currentWord{};
        size_t delimiterPos = currentDictEntry.find('\t', 0);

        if (delimiterPos == std::string::npos)
            std::cerr << "ERROR. Delimiter \"<b>\" not found in line " << currentLine << std::endl;
        else
        {
            //std::cout << "pos of \\t = " << delimiterPos << std::endl; // TO DELETE
            for (char& ch : currentDictEntry)
            {
                if (ch != '\t')
                {
                    currentWord += ch;
                }
                else
                    break;

            }
            std::cout << currentWord /* << '|' */ << std::endl; // TO DELETE

            auto value = currentDictEntry.substr(delimiterPos, std::string::npos);

            std::cout << "size= " << value.size() << '|' << value << std::endl;

            dict.insert( currentWord, currentWord/*, value*/ );
        }

        if (currentLine == 50) return 0; // TO DELETE


        currentLine++;
    }

    return 1;
}
        if (currentLine == 50) return 0; // TO DELETE


        currentLine++;
    }

    return 1;
}

The error I keep getting is:

unary '++': '_Iter' does not define this operator or a conversion to a type acceptable to the predefined operator

illegal indirection

Error: aggregate has incomplete type and cannot be defined

I am writing a program for bank and I m getting this error when I compile it. I am not including my whole code but the part I think is responsible:

#include<iostream>
#include<string>
#include<limits>
#include<fstream>
#include<iomanip>

using std::ios_base;
using std::ostringstream;
using std::ios;
using std::fstream;
using std::ifstream;
using std::ofstream;
using std::stoi;
using std::to_string;
using std::string;
using std::cout;
using std::cin;
using std::endl;
using std::getline;

class yourbankaccount
{
private:
    string accountNumber;
    // Name of the customer.
    string name;
    // Date of birth
    int day;
    int month;
    int year;
    // Get Age
    int age;
    // Get Gender
    string gender;
    long accountBalance = 0;
public:
    friend int getInt(string info, int length);
    friend string getStr(string info, int length);
    yourbankaccount(){}
    void setAccountNumber(string number){
        accountNumber = number;
    }
    string shareAccountNumber(){
        return accountNumber;
    }
    // Get date
    void getDate(){
        int d, m, y;
        cout << "Now please enter your Date Of Birth(DD/MM/YYYY):"<<endl;
        d = getInt("Day(DD)", 2);
        m = getInt("Month(MM)", 2);
        y = getInt("Year(YYYY)", 4);
        day = d; month = m; year = y;
    }
    // Return Date
    string sendDate(){
        string Date = to_string(day) + "/" + to_string(month) + "/" + to_string(year);
        return Date;
    }
    // Method to add details.
    void getCustomerDetails(){
        bool gotGen = false;
        string n; int a; unsigned int p; char g;
        cout << "Please fill in the following details: ";
        name = getStr("Name of Account holder", 45);
        cout << "Enter your birthday in given format: ";
        getDate();
        age = getInt("your Age", 2);
        do
        {
            gender = getStr("your Gender(only M for Male, F for Female, O for Other)", 1);
            if (stringToUpper(gender)  != "M" || 
                stringToUpper(gender) != "F" || 
                stringToUpper(gender) != "O"){
                    "Please enter only M or F or O!";
            }else{
                gotGen = true;
            }
        } while (gotGen);
    } 
    string shareName(){
        return name;
    }
    string shareDOB(){
        return sendDate();
    }
    int shareAge(){
        return age;
    }
    string shareGender(){
        return gender;
    }
    void setAccountBalance(long bal){
        accountBalance = bal;
    }
    long shareAccountBalance(){
        return accountBalance;
    }
    ~yourbankaccount(){}
};

and I am declaring the object here:

void createAccount(){
    ofstream addAccount;
    yourbankaccount Account;
    cout << "Thank You for Choosing Your Bank.";
    cout << "Please provide The folling details.";
    Account.setAccountNumber(calNewAccNumber());
    Account.getCustomerDetails();
    Account.setAccountBalance(500);
    int pin = getInt("a pin for the account", 4);
    string file ="accounts/open.csv";
    addAccount.open(file, ios::out | ios::app);
    if (addAccount.is_open())
    {
        addAccount << Account.shareAccountNumber()
        << "," << pin << "," << "\"" << Account.shareName() << "\"" << "," 
        << Account.shareDOB() <<"," << Account.shareAge()
        << "," << Account.shareGender() << Account.shareAccountBalance()<<"\n";
    }

    cout << "Your Account has been created Sucessfully." <<
            "Please note your number as it will be required for logging in\n";
    cout << "Account number is:" << Account.shareAccountNumber() << "\n";
}

I get this error when I compile it:

Executing task: C/C++: g++.exe build active file ver(1) <

Starting build... D:\Programs\mingw_w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\bin\g++.exe -g D:\BSC_IT\sem_2\OOPS\CA2\YourBank\yourbank.cpp -o D:\BSC_IT\sem_2\OOPS\CA2\YourBank\yourbank.exe

D:\BSC_IT\sem_2\OOPS\CA2\YourBank\yourbank.cpp: In function 'void createAccount()':
D:\BSC_IT\sem_2\OOPS\CA2\YourBank\yourbank.cpp:139:21: error: aggregate 'yourbankaccount Account' has incomplete type and cannot be defined
    yourbankaccount Account;
                     ^~~~~~~

Build finished with error(s). The terminal process terminated with exit code: -1.

Terminal will be reused by tasks, press any key to close it.

Getting "Segmentation fault" in the following code

While learning the implementation of Graphs, i came across thi code on GFG. When I tried to compile it on local compiler i got this error.

    for( int i = 0 ; i < v ; ++i){
        cout<<"the adjacency list for vertex "<<v;
        for( auto j : adj[i]){
            cout<<"->"<<j;
        }
        cout<<endl ;
    }
}

samedi 27 mars 2021

is default constructor is better than user defined in c++11 if its exactly the same

struct widget
{
  widget()=default; // better than widget(){} ?

  inline widget& operator=(const widget&);
};

why is using default constructor here better? more specifically, how is the compiler-generated constructor more efficient than the one we provide, if we provide exactly the same constructor?

c++ fatal error no input files, compilation terminated c++11 not found

I'm trying to build simple shared library for gazebo tutorials. In their website, CMakeLists file should be like this

cmake_minimum_required(VERSION 2.8 FATAL_ERROR)
find_package(gazebo REQUIRED)
include_directories(${GAZEBO_INCLUDE_DIRS})
link_directories(${GAZEBO_LIBRARY_DIRS})
list(APPEND CMAKE_CXX_FLAGS "${GAZEBO_CXX_FLAGS}")
add_library(hello_world SHARED hello_world.cc)
target_link_libraries(hello_world ${GAZEBO_LIBRARIES})

And They clearly mention the following

New in gazebo6: c++11 flags are now required for all downstream software to compile against gazebo. This is done with the following line: set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${GAZEBO_CXX_FLAGS}")

Adding the preceding line in the above CMakeLists yields this error:

c++: fatal error: no input files
compilation terminated. 
/bin/sh: 1: -std=c++11: not found

Removing the line, the compilation proceeds without problem. Any suggestions? My machine:

Ubuntu 20.04.2 LTS, 
cmake version 3.16.3, 
g++ 9.3

Can someone tell me what's wrong with my cpp code?

I'm trying to return a vector from evenBodd function instead I get this - invalid operands to binary expression ('std::ostream' (aka 'int') and 'const char [2]'

I'm new to cpp so any help would be appreciated.

Code:

vector<int> eveBodd(vector<int> arr){
vector<int> even, odd;
for(int i=0; i<arr.size(); ++i){
    if(arr[i]%2 == 0){
        even.push_back(arr[i]);
    }
    else{
        odd.push_back(arr[i]);
    }
}
even.insert(even.end(), odd.begin(), odd.end());
return even;
}


int main() {
vector<int> arr{1,2,3,4,5,6,7,8,10};
cout << eveBodd(arr) << "\n";
return 0;
}

Code Image Code

Why triggers this noexcept operator an "overloads have similar conversions" error for MSVC but not for Clang and GCC

I have the following code

template <typename V>
struct S {
    V i_;
    S() : i_(0) {}
    template<typename T>
    operator T() const noexcept
    (noexcept(static_cast<T>(i_) - 1)) // comment out this line to make it work in MSVC
    {
        return static_cast<T>(i_) - 1;
    }
};
struct R {
    int i_;
    R(int i) : i_(i) {}
    operator int() const { return i_; }
    int operator-(R const& o) const { return i_ - o.i_; }
};

bool operator==(R const& l, int r)
{
    return l.i_ == r;
}
bool operator==(S<int> l, int r)
{
    return static_cast<int>(l) == static_cast<int>(r);
}

int main() {
    return S<int>() == 3;
}

which compiles fine on Clang and GCC for C++11 and above but complains about

'R::operator -': 2 overloads have similar conversions
note: could be 'int R::operator -(const R &) const'
note: or       'built-in C++ operator-(int, int)'
note: while trying to match the argument list '(T, int)' with [ T=R ]

in MSVC.

What's puzzling me is that removing the noexcept operator on the template operator T() on struct S makes the error disappear. Its expression is the exact same as the one in the body of the method it marks noexcept and I'd expect that the method body would cause the same error but it doesn't. This makes me suspect that I don't understand the noexcept operator at all.

Who is right here and why?

Here's a godbolt.

fileops.c no such file or directory while using fsream

I am trying to build a student management system. This is my code

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

fstream obj;

struct Student{
    string name,father,mother;
    int cls,roll;
    void GET(){
      cout<<"\nEnter Name:-"; cin.ignore(); getline(cin,name);
      cout<<"Enter Father:-"; cin.ignore(); getline(cin,father);
      cout<<"Enter Mother:-"; cin.ignore(); getline(cin,mother);
      cout<<"Enter Class:-"; cin>>cls;
      cout<<"Enter Roll:-"; cin>>roll;
    }
    void write(){ obj.write((char*)this,sizeof(*this)); }
    void Disp(){
      cout<<"\nName:-"<<name<<endl;
      cout<<"Father's Name:-"<<father<<endl;
      cout<<"Mother's name:-"<<mother<<endl;
      cout<<"Class:-"<<cls<<endl;
      cout<<"Roll:-"<<roll<<endl;
    }
};

void ReadFile();

int main(){
  try{
    int n; char ch; Student *ST;
    cout<<"What do you want?"<<endl<<"1. Enter data"<<endl<<"2. Read Data"<<endl;
    cin>>ch;
    switch(ch){
      case '1':{
        cout<<"Enter Number of Students="; cin>>n;
        if(n>0) obj.open("Student2.dat",ios::app|ios::binary);
        for(int i=0;i<n;i++){
          ST=new Student;
          ST->GET();
          ST->write();
          delete ST;
        }
        obj.close(); cout<<"Writing objects successfull";
        break;
      }
      case '2':{ ReadFile(); break; }
      default: { string error="Unlisted command not supported"; throw error; }
    }
  } catch(string err){
    cout<<endl<<err<<endl;
  }
  return 0;
}

void ReadFile(){
  int sum=0;
  ifstream ifobj("Student2.dat",ios::in|ios::binary);
  string error;
  Student x;
  if(ifobj){
    while(!ifobj.eof()){
      ifobj.read((char*)&x,sizeof(x));
      x.Disp();
    }
     ifobj.close();
  }
  else{
    error="Student data file not found";
    throw error;
  }
}

When I try to compile, it works fine. When I try to read my objects from the file, it gives me this error:-

Segmentation fault (core dumped)

Here's what I got by debugging and backtracing the a.out file by running the command gdb a.out core

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7c5b88c in _IO_new_file_xsputn (n=13, data=0x55d6945e68d0, f=<optimized out>) at fileops.c:1219
1219    fileops.c: No such file or directory.
(gdb) backtrace
#0  0x00007ffff7c5b88c in _IO_new_file_xsputn (n=13, data=0x55d6945e68d0, f=<optimized out>) at fileops.c:1219
#1  _IO_new_file_xsputn (f=0x7ffff7db56a0 <_IO_2_1_stdout_>, data=0x55d6945e68d0, n=13) at fileops.c:1197
#2  0x00007ffff7c4f541 in __GI__IO_fwrite (buf=0x55d6945e68d0, size=1, count=13, fp=0x7ffff7db56a0 <_IO_2_1_stdout_>) at libioP.h:948
#3  0x00007ffff7f09784 in std::basic_ostream<char, std::char_traits<char> >& std::__ostream_insert<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*, long) () from /lib/x86_64-linux-gnu/libstdc++.so.6
#4  0x0000555555556c8f in Student::Disp (this=0x7fffffffdc60) at Student.cpp:21
#5  0x0000555555556995 in ReadFile () at Student.cpp:79
#6  0x000055555555674f in main () at Student.cpp:63

I guess the main culprit is ifstream::read() function, because the fstream::write() function works fine. I have verified it by comparing the Student object size and the file size of Student2.dat.

It would be helpful if someone can tell me what's going on here. I am familiar with c++ but I have recently switched to Ubuntu

Class does not persist vector of objects after addition

My code is as shown below:

main.cpp

#include <bits/stdc++.h>
#include "Customer.h"
#include "MenuCreator.h"
#include "FoodItem.h"

MenuCreator m1;

void createCustomer() {
    Customer c1("mrg", "m@gmail.com", "9654357", "+91");
}

void createRestaurantItem(Restaurant &rest) {
    rest.addItems(FoodItem("t1"));
    rest.addItems(FoodItem("D1"));
}

void createMenu() {
    m1.createMenu("sg");
    Category c1;
    c1.setName("Non-veg");
    m1.addCategory(c1);
    Restaurant r1;
    r1.setName("ABC");
    r1.setDescription("Test Restaurant");
    createRestaurantItem(r1);
    c1.addRestaurants(r1);
}

vector<Restaurant> getRestaurantsForCategory(string category) {
    return m1.getRestaurantsForCategories(category);
}


int main() {
    createCustomer();
    createMenu();
    for (auto r: getRestaurantsForCategory("Non-veg")) {
        r.printItems();
    }
    return 0;
}

MenuCreator.h

#include <bits/stdc++.h>
#include "Menu.h"

using namespace std;

class MenuCreator {

public:

    void createMenu(string name) {
        Menu m1;
        m1.setName(name);
        menu = m1;
    }

    void addCategory(const Category &categ) {
        categories.push_back(categ);
    }

    const Menu &getMenu() const {
        return menu;
    }

    const vector<Category> &getCategories() const {
        return categories;
    }

    void addRestaurantForCategory(string name, const Restaurant restaurant) {
        for(auto categ: categories) {
            if (categ.getName() == name) {
                categ.addRestaurants(restaurant);
            }
        }
    }

    const vector<Restaurant> &getRestaurantsForCategories(string category) {
        for(auto categ: categories) {
            if(categ.getName() == category) return categ.getRestaurants();
        }
    }

private:
    Menu menu;
    vector<Category> categories;
};

Menu.h

#include<bits/stdc++.h>
#include "Category.h"

using namespace std;

class Menu {
public:
    const string &getName() const {
        return name;
    }

    void setName(const string &name) {
        Menu::name = name;
    }

private:
    string name;
    string description;
    vector<Category> categories;
};

Category.h

using namespace std;

class Category {
public:
    const string &getName() const {
        return name;
    }

    void setName(const string &name) {
        Category::name = name;
    }

    const string &getDescription() const {
        return description;
    }

    void setDescription(const string &description) {
        Category::description = description;
    }

    const vector<Restaurant> &getRestaurants() const {
        return restaurants;
    }

    void setRestaurants(const vector<Restaurant> &restaurants) {
        Category::restaurants = restaurants;
    }

    void addRestaurants(const Restaurant &rt) {
        Category::restaurants.push_back(rt);
    }

private:
    string name;
    string description;
    vector<Restaurant> restaurants;
};

FoodItem.h

#include <bits/stdc++.h>
#include <vector>
#include "FoodItem.h"

using namespace std;

class Restaurant {
public:

    Restaurant() {
        this->id = gen_random(12);
    }

    virtual ~Restaurant() {

    }

    const string &getName() const {
        return name;
    }

    void setName(const string &name) {
        Restaurant::name = name;
    }

    const string &getDescription() const {
        return description;
    }

    void setDescription(const string &description) {
        Restaurant::description = description;
    }

    double getLat() const {
        return lat;
    }

    void setLat(double lat) {
        Restaurant::lat = lat;
    }

    double getLang() const {
        return lang;
    }

    void setLang(double lang) {
        Restaurant::lang = lang;
    }

    const string &getImageUrl() const {
        return imageUrl;
    }

    void setImageUrl(const string &imageUrl) {
        Restaurant::imageUrl = imageUrl;
    }

    const string &getVideoUrl() const {
        return videoUrl;
    }

    void setVideoUrl(const string &videoUrl) {
        Restaurant::videoUrl = videoUrl;
    }

    const vector<FoodItem> &getItems() const {
        return items;
    }

    void setItems(const vector<FoodItem> &items) {
        Restaurant::items = items;
    }

    void addItems(const FoodItem &item) {
        this->items.push_back(item);
    }

    string gen_random(const int len) {
        string tmp_s;
        static const char alphanum[] =
                "0123456789"
                "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                "abcdefghijklmnopqrstuvwxyz";
        srand( (unsigned) time(NULL) * getpid());
        tmp_s.reserve(len);
        for (int i = 0; i < len; ++i)
            tmp_s += alphanum[rand() % (sizeof(alphanum) - 1)];
        return tmp_s;

    }

    const string &getId() const {
        return id;
    }

    void printItems() {
        for(auto it: items) {
            cout<<"item: "<<it.getName()<<endl;
        }
    }


private:
    string id;
    string name;
    string description;
    double lat;
    double lang;
    string imageUrl;
    string videoUrl;
    string createdAt;
    string updatedAt;
    vector<FoodItem> items;
};

Restaurant.h

#include <bits/stdc++.h>
#include <vector>
#include "FoodItem.h"

using namespace std;

class Restaurant {
public:

    Restaurant() {
        this->id = gen_random(12);
    }

    virtual ~Restaurant() {

    }

    const string &getName() const {
        return name;
    }

    void setName(const string &name) {
        Restaurant::name = name;
    }

    const string &getDescription() const {
        return description;
    }

    void setDescription(const string &description) {
        Restaurant::description = description;
    }

    double getLat() const {
        return lat;
    }

    void setLat(double lat) {
        Restaurant::lat = lat;
    }

    double getLang() const {
        return lang;
    }

    void setLang(double lang) {
        Restaurant::lang = lang;
    }

    const string &getImageUrl() const {
        return imageUrl;
    }

    void setImageUrl(const string &imageUrl) {
        Restaurant::imageUrl = imageUrl;
    }

    const string &getVideoUrl() const {
        return videoUrl;
    }

    void setVideoUrl(const string &videoUrl) {
        Restaurant::videoUrl = videoUrl;
    }

    const vector<FoodItem> &getItems() const {
        return items;
    }

    void setItems(const vector<FoodItem> &items) {
        Restaurant::items = items;
    }

    void addItems(const FoodItem &item) {
        this->items.push_back(item);
    }

    string gen_random(const int len) {
        string tmp_s;
        static const char alphanum[] =
                "0123456789"
                "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                "abcdefghijklmnopqrstuvwxyz";
        srand( (unsigned) time(NULL) * getpid());
        tmp_s.reserve(len);
        for (int i = 0; i < len; ++i)
            tmp_s += alphanum[rand() % (sizeof(alphanum) - 1)];
        return tmp_s;

    }

    const string &getId() const {
        return id;
    }

    void printItems() {
        for(auto it: items) {
            cout<<"item: "<<it.getName()<<endl;
        }
    }


private:
    string id;
    string name;
    string description;
    double lat;
    double lang;
    string imageUrl;
    string videoUrl;
    string createdAt;
    string updatedAt;
    vector<FoodItem> items;
};

The problem is inside int main function r.printItems() is not printing anything. What am I missing here ?

How to set format of std::scientific

I want to print 12345.0 as 0.1235e+05. But the below code gives 1.23450e+04. Is there a way to control the format of std::scientific?

#include <iostream>
#include <string>
#include <sstream>


int main()
{
    double a = 12345.0;

    std::stringstream s;

    s.precision(3);

    s << std::scientific;

    s << a;

    std::cout << s.str() << std::endl;

    return 0;
}

The output is

1.235e+04

I also tried the code here Print exponential notation with one leading zero with C++ but there is a problem about rounding. If I set precision to 4 it does not round and gives 0.1234E5 however it should have been 0.1235E5.

Any solution to this?

How can i grow weight of OBJECT randomly between 0.1-0.5% of it's current weight C++

So i have class platypus and function EAT which grows weight of platypus .i want weight to grow randomly between 0.1--0.5 % of platypus current weight. For example if i have platypus which weighs 10 kg i want EAT function to grow it's weight by 10*random between(0.1%--0.5%). PLEASE HELP

sleep_until() and steady_clock loop drifting from real time in macOS

Good evening everyone, I'm trying to learn concurrency using the C++ Concurrency Book by Anthony Williams. Having read the first 2 chapters I thought about coding a simple metronome working in its own thread:

#include <iostream>
#include <thread>
#include <chrono>
#include <vector>

class Metro
{
public:
    // beats per minute
    Metro(int bpm_in);
    void start();

private:
    // In milliseconds
    int mPeriod;
    std::vector<std::thread> mThreads;

private:
    void loop();
};

Metro::Metro(int bpm_in):
    mPeriod(60000/bpm_in)
{}

void Metro::start()
{
    mThreads.push_back(std::thread(&Metro::loop, this));
    mThreads.back().detach();
}

void Metro::loop()
{
    auto x = std::chrono::steady_clock::now();
    while(true)
    {
        x += std::chrono::milliseconds(mPeriod);
        std::cout << "\a" << std::flush;
        std::this_thread::sleep_until(x);
    }
}

Now, this code seems to work properly, except for the time interval: the period (assuming bpm = 60 => mPeriod = 1000ms) is more than 1100ms. I read that sleep_until is not guaranteed to wake the process up exactly at the correct time (cppreference.com), but the lack of precision should not change the average period time, only delay the single "tic" inside the time grid, am I understanding it correctly? I assumed that storing the steady_clock::now() time only the first time and then using only the increment would be the correct way not to add drifting time at every cycle. Nevertheless, I also tried to change the x var update in the while loop to

x = std::chrono::steady_clock::now() + std::chrono::milliseconds(mPeriod);

but the period increases even more. I also tried using std::chrono::system_clock and high_resolution_clock, but the period didn't improve. Also, I think the properties I'm interested in for this application are monotonicity and steadiness, which steady_clock has. My question is: is there anything completely wrong I did in my code? Am I missing something concerning how to use std::chrono clocks and sleep_until? Or is this kind of method inherently not precise?

I've started analyzing the period by simply comparing it against some known metronomes (Logic Pro, Ableton Live, some mobile apps) and then recorded the output sound to have a better measurement. Maybe the sound buffer has some delay on itself, but same problem happens when making the program output a char. Also, the problem I'm concerned about is the drifting, not the single tic being a bit out of time.

I'm compiling from macos 10.15 terminal with g++ --std=c++11 -pthread and running it on Intel i7 4770hq.

How to set format of std::scientific

I want to print 12345.0 as 0.12345e+05. But the below code gives 1.23450e+04. Is there a way to control the format of std::scientific?

#include <iostream>
#include <string>
#include <sstream>

using namespace std;


int main()
{
    double a = 12345.0;

    std::stringstream s;

    s.precision(5);

    s << scientific;

    s << a;

    cout << s.str() << endl;

    return 0;
}

The output is

1.23450e+04

Why am I experiencing data loss when trying to copy files using fstream in C++?

I'm working on a small project in C++ which is all about copying an image file. So far, I can't seem to prevent data loss from happening. All images copied experience up to 2% of data loss (corruption). Is there a flaw in my code or is it something about image codecs that I'm not aware of? Also, is there a more efficient way to do this? The code is down below.

Thanks in advance.

#include <iostream>
#include <cstdlib>
#include <fstream>
#include <vector>
#define FILE_SRC "IMAGE1.jpg" // name of file to be copied
#define FILE_DES "IMAGE2.jpg" // name of file clone
using namespace std;
void copy_file()
{
    puts("Press Any Key to Begin.");  if (cin.ignore()) { ; }
    
    vector <unsigned char> fileData; // data from source file will be temporarily stored in vector
    fstream targetFile;
    unsigned char targetByte;
    
// START : copies data from source file and stores in vector
    targetFile.open(FILE_SRC, ios::in | ios::binary);
    while (targetFile >> targetByte)
    {
        fileData.push_back(targetByte);
    }
    targetFile.close();
// END : copies data from source file and stores in vector

    puts("File Loaded.");
    
// START : checks if destination file already exists , if not , create new
    targetFile.open(FILE_DES);
    if (targetFile.fail())
    {
        targetFile.close();
        targetFile.open(FILE_DES,ios::out);
    }
    targetFile.close();
// END : checks if destination file already exists , if not , create new

    targetFile.open(FILE_DES, ios::app | ios::binary);
    
// START : writes data from vector to destination file
    for (unsigned int i = 0; i < fileData.size(); i++)
    {
        targetFile << fileData.at(i);
    }
    targetFile.close();
// END : writes data from vector to destination file

    puts("File Copied.");
}
int main()
{
    copy_file();
    return 0;
}

2D Vectors push_back

I'm trying to push_back numbers into a 2D vector that's composed of 1 row and 1 column.

    vector< vector <int>>array;
    array.push_back(vector<int>(3)); 
    array[0].push_back(2);
    cout << array[0][0] << endl;

I expected this to return 3, but it returns 0. Why's that?

vendredi 26 mars 2021

How do i get maximum value from private salary variable?

This is my class named employee, how do I go about getting the maximum value from the salary variable, since the variable is private and can only be accessed using setter getter functions, should I compare the getter functions to get maximum value? Help required!!Also, what can I change in the end condition voidsal() to get my answer?

#include<iostream>
#include<string>
using namespace std;
class employee{
    private:
        string name;
        string designation;
        int age;
        int salary;
    public:
        void set_name(string n)
        {
            name=n;
        }
        string get_name()
        {
            return name;
        }
        void set_des(string d)
        {
            designation=d;
        }
        string get_des()
        {
            return designation;
        }
        void set_age(int a)
        {
            age=a;
        }
        int get_age()
        {
            return age;
        }
        void set_sal(int s)
        {
            salary=s;
        }
        int get_sal()
        {
            return salary;
        }
        int Max=0;
        void sal(){
        for(int j=0;j<5;j++)
        {
            if(salary[Max]<=salary[j])
            {
                Max=j;
            }
        }
    }
};  
    
     ```


Why " throw" will dsiplay a warning?

#include <iostream>
#include <sstream>

using std::string;
using std::cout;
using std::endl;
using std::ostringstream;

class illegalParameterValue {

private:
    string message;
public:
    illegalParameterValue() : message("Illegal parameter value") {}
    explicit illegalParameterValue(const char* theMessage) {message = theMessage;}
    void outputMessage() {cout << message << endl;}

};

int main() {

    ostringstream s;
    s << "index = " << 1 << " size = " << 2;
    throw illegalParameterValue(s.str().c_str());

    return 0;
}

I just use some code like this, but the "throw" will remind some warnings which called "Clang-Tidy: Throwing an exception whose type 'illegalParameterValue' is not derived from 'std::exception'", how can I solve this problem?

Why does push_back fail for unique_ptr of string vectors?

The code below has a segmentation fault. When there is not a unique_ptr involved everything works fine.

int main() {
  auto vect = std::unique_ptr<std::vector<std::string>>();
  vect->push_back("abc");  // Segmentation Fault.
  vect->emplace_back("abc");  // Segmentation Fault.
  return 0;
}

In case this matters, I'm compiling using g++ 10.2 on Ubunutu.

How do you initialise a std::unique_ptr to a reference

With raw pointers I can do:

int x = 10;
int* y = &x;

x = 20;
std::cout << *y; //prints 20

However, Im struggling to emulate the same behaviour with std::unique_ptr. Ive tried:

int x = 10;

std::unique_ptr<int> y = std::make_unique(&x); //doesnt compile
std::unique_ptr<int> y = std::make_unique<int>(&x); //doesnt compile
std::unique_ptr<int&> y = std::make_unique(x); //doesnt compile
std::unique_ptr<int> y = std::make_unique<int&>(&x); //doesnt compile

std::unique_ptr<int> y = std::make_unique<int>(x); //compiles but prints y = 10, which is not the desired behaviour

Im sure there is a way, so any help is appreciated. Thanks.

Compiling error | cannot compile cpp program due to compiler parser

Short Description
I am trying to compile a short lambda to convert a giving input to string format. My overall class uses a template, i.e template <typename T>. I want to overload << to print-out an object which can be of any type; i.e, int, string, etc.

For example, let's say that my object is {int age: 12, int* left: null, int* right: null}, I should be able to print something like "{value: "12", left: undefined, right: undefined}". In addition, if object = {string comment: "Distance learning....", int* left: undefined, int* right: undefined}, I should print out, "{value: "Distance learning....", left: undefined, right: undefined}". Below is a copy of the lambda function mark-up to convert from any data-type to a string.

std::function<std::string(T)> toString; //declares the blueprint for the lambda function, notice that I am returning a string, and expecting an object of type T, which can be of any type since i'm using a template. 
    toString = [](T value) -> std::string { //Begins the the body of the function
      if (typeid(std::string).name() == typeid(T).name())
      { // not the best way to do this, but here I am checking that the input is already a string, in which case I do not need to convert or anything. 
        return value; //if the input 'value' is already a string, simply return it. 
      }
      //do some stuff to convert the date into a string

      return; // return the final 'value' in string format. 
    };

~Sorry in advance if my comments were confusing.

Problem
The idea works on paper, however, the problem happens when I have a data-type that is not of type string. Let's say that T == int, walking through the code, the if statement will be skipped, assuming that my condition is set-up correctly, and I should move down. This means that I will not return an int when the function blueprint says that I will return a string.

However, when the compiler goes through my code, it reads it and thinks that I am trying to send-back an int when the function is supposed to send back a string and it throws an error. "no viable conversion from returned value of type 'int' to function return type 'std::string'"

for example,

//Let T = int, value = 12, so the below parameter equals, int value, which holds the value of 12. 

    toString = [](T value) -> std::string {
      if (typeid(std::string).name() == typeid(T).name())
      { //should failed since typeid(int).name != typeid(std::string).name
        return value;
      }
      //do some stuff to convert the date into a string

      return; // return the final 'value' in string format. 
    };
//However, when the compiler parses the code, it thinks that I am trying to return value, which is of type int. But the function is supposed to return a string.

//In reality, this should not happen since my if statement will take care of it. 

Does anyone know a work around for this or any idea on how to fix my logic?

C++ Override Destructor and ownership transfer of a member variable

I am not very proficient in C++. So I'll explain my problem as clearly as possible and when you are answering,please do some explanation.

So my problem involves 2 classes(A and B) with another class in a framework which I don't have access to. A has a pointer to B and B has a pointer to the A (raw pointers). The following show the interactions between the 2 classes.

class A {
  public:
    void method(){
      this->b_ = new B(this);
      SomeServiceClass::doSomething(std::unique_ptr<B>(this->b_));
    }

  private:
    B *b_;
}

class B {
  public:
    B(A *a){
      this->a_ = a;
    }
    someOtherMethod(){
    }

  private:
    A *a;
}

So what really happens is, A creates first, and inside a method() of A , I create B and pass the B as a unique_ptr to some other method implemented in another class of a framework(which I don't have access). So that way I transfer ownership of B to that other class. But during the lifetime of A, I want to access B's other methods. That is why I keep a raw pointer to B in the class A. (I could have used a shared_ptr instead but that SomeServiceClass::doSomething requires a unique_ptr). But my question is at the time A is destroyed. Should I override the destructor of A and assign this->b_ = null ? Or maybe delete ? Thanks in advance

c++ multiple template template parameter

I'm reading some references online and I'm confused about template template argument. In particular I do not understand how the inner template parameter are passed according to their position. Perhaps an example will help to understand what is my confusion

What I was trying to do is the following. I have

template <typename A, typename B, typename DepA, typename DepB>
class aClass {
   ...
};

What I exect is that DepA must have A as template argument and DepB, B. In this way I would like to recast

aClass<int, double, std::vector<int>, std::deque<double>>

simply to

aClass<int, double, std::vector, std::deque>

What should I write in my template definition?

Inserting elements in a range

I'm reading C++ Primer (5th edition) and in 9.9.3 it mentions inserting in-range elements.

It is clearly stated in the book that it will cause a runtime error if the range of the copy is the same as the target container.

// it'll cause a runtime error
vec.insert(vec.cbegin(), vec.cbegin(), vec.cend());

But it works in my computer, Why?

Why "ostream_iterator" will have a warning? [closed]

void arrayList<T>::output(ostream &out) const {

    copy(element, element + listSize, ostream_iterator<T>(cout, " "));

}

I just use this old code to print some digital, but this code always has a warning which calls "Use of function template name with no prior declaration in function call with explicit template arguments is a C++20 extension"

Using std::iota to fill an alphabet vector

In this code I'm filling the vector alpha with letters from 'a' to 'z':

std::vector<char> alpha(26);
std::iota(alpha.begin(), alpha.end(), 'a');

I'm assuming this will not work with all character encodings, can anyone confirm? Or deny?

c++ grandchild does not see the data of an abstract grandparent [duplicate]

The following C++ code does not compile:

class Val
{
protected:
    int n;
public:
    Val() : n(0) {}
    Val(int nn) : n(nn) {}

    virtual int blah() const = 0;
};

template <class T>
class subVal : public Val
{
public:
    subVal() : Val() {}

    int blah() const { return n; }
};

template <class T>
class subsubVal : public subVal<T>
{
public:
    subsubVal() : subVal<T>() {}

    int blah() const { return n; } // this is the "faulty" line

    int blahblah() const { return n; }
};



subsubVal<int> ssv;   // declare an instance, to confirm that it can be done

The compiler (VisualStudio) says "C2065 'n' undeclared identifier".

If I replace the line marked "faulty" with

int blah() const { return Val::n; } // replacement line

then it compiles ok.

The failure is, I think, related to the fact that Val here is an abstract class, since another way to get successful compilation is to comment out the pure virtual function declaration of blah() in class Val. Note that the grandchild method blahblah() does not generate a compiler error. I think also it is something to do with the templating, in that the code compiles if one removes the templating (but of course I want to template in the full project; this is just a snippet to illustrate the point). Note also that the child has no problem in seeing the data value n in the parent. It is just the grandchild that does not see it unaided.

I am hoping first for an answer that clarifies the logic (since my code that did not compile looks logical to me), and then for a solution better than sticking lots of horrible 'Classname::' identifiers all over the code of the grandchild. (In practice those identifiers will have longer names and will greatly reduce the naturalness and readableness of the code).