jeudi 30 juin 2022

How can I pass member function with parameters to a function that resides in other files?

Just giving an example here to understand what I actually need to do.

#include "otherfile.hpp"
class Example{
   void exampleFun(int arg);
   void exampleFun2(string arg1, int arg2 );
   void sendMemberFun();
};

void Example::sendMemberFun()
{
    receiveMemberFun(_______);   // receiveMemberFun is in other file.
}

I need to pass exampleFun and exampleFun2 member functions to receiveMemberFun. Could anyone explain how receiveMemberFun can be constructed to receive these 2 functions? and what are the possible arguments?

parallelizing C++ code with MPI_send and MPI_recv

I have a parallel code, but I don't understand if it works correctly in parallel. I have two vectors A and B whose elements are matrices defined with a proper class. Since the matrices in the vectors are not primitive type I can't send these vectors to other ranks through MPI_Scatter, so I have to use MPI_Send and MPI_Recv. Also, rank 0 has only a coordination role: it sends to the other ranks the blocks they should work with and collects the results at the end, but it does not participate to the computation.

The solution of the exercise is the following:

// rank 0 sends the blocks to the other ranks, which compute the local
// block products, then receive the partial results and prints the global
// vector
if (rank == 0)
{
    // send data
    for (unsigned j = 0; j < N_blocks; ++j) {
        int dest = j / local_N_blocks + 1;
        // send number of rows
        unsigned n = A[j].rows();
        MPI_Send(&n, 1, MPI_UNSIGNED, dest, 1, MPI_COMM_WORLD);
        // send blocks
        MPI_Send(A[j].data(), n*n, MPI_DOUBLE, dest, 2, MPI_COMM_WORLD);
        MPI_Send(B[j].data(), n*n, MPI_DOUBLE, dest, 3, MPI_COMM_WORLD);}
    {"for loop for rank 0 to receive the results from others ranks"}
    
    // all the other ranks receive the blocks and compute the local block
    // products, then send the results to rank 0
    else
    {
        // local vector
        std::vector<dense_matrix> local_C(local_N_blocks);
        // receive data and compute products
        for (unsigned j = 0; j < local_N_blocks; ++j) {
            // receive number of rows
            unsigned n;
            MPI_Recv(&n, 1, MPI_UNSIGNED, 0, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
            // initialize blocks
            dense_matrix local_A(n,n); dense_matrix local_B(n,n);
            // receive blocks
            MPI_Recv(local_A.data(), n*n, MPI_DOUBLE, 0, 2, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
            MPI_Recv(local_B.data(), n*n, MPI_DOUBLE, 0, 3, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
            // compute product
            local_C[j] = local_A * local_B; }
        {"for loop for ranks != 0 to send the results to rank 0"}
    }

In my opinion, if local_N_blocks= N_blocks / (size - 1); is different from 1, the variable dest doesn't change value at every loop iteration. So, after the first iteration of the "sending loop", the second time that rank 0 faces

MPI_Send(A[j].data(), n*n, MPI_DOUBLE, dest, 2, MPI_COMM_WORLD);
MPI_Send(B[j].data(), n*n, MPI_DOUBLE, dest, 3, MPI_COMM_WORLD);

it has to wait that the operation local_C[j] = local_A * local_B of the previous j has been completed so the code doesn't seem to me well parallelized. What do you think?

Dissable stack canary using gcc does not work when using "-static"

I have a question. I try to perform a ROP attack. My system is a 64 bit Kali linux which is running on a virtual machine. During my research I found out, that I am not able to overwrite the eip as long as "stack canary" is activated. The problem is, that stack canary is only disabled when the file is linked dynamic. When it is linked dynamic the problem is that there are not enough gadgets to use to perform a rop attack. when I linked it with the -static option there are enough gadgets but stack canary is activated. Now I have the question if there is any possibility to linked a file with the -static command and disable stack canary?

I run this on a Linux kali 5.16.0-kali7-amd64 #1 SMP PREEMPT Debian 5.16.18-1kali1 (2022-04-01) x86_64 GNU/Linux

The command is: gcc -mpreferred-stack-boundary=2 -fno-stack-protector -std=c++11 -z execstack -no-pie -m32 -save-temps -static main.cpp -o main -lstdc++

Doing it like this does not deactivate the stack canary.

Leaving the "-static" command deactivates the stack canary and I have no idea why.

mardi 28 juin 2022

Does std::move leave stack fragmented or is the stack rearranged after moving an object to the caller?

I have read several answers and and many articles about move semantic so it is simply a static cast to rvalue reference, this question is about its influence on the stack, so is the stack left fragmanted after move? or is it rearranged somehow? as the stack moved objects are not subject to stack unwinding. The following snippet runs fine:

#include <memory>
#include <cassert>

struct A {
    int x = 0;
};

struct B {
    A a;
};

void SetB(B& b) {
    A a1{6}; //pushing into the stack.
    A a2{7}; //pushing into the stack.
    b.a = std::move(a2);
}

int main()
{
    B b;
    SetB(b);
    assert( b.a.x == 7);
}

a2 is defined in SetB stack frame but still available after SetB is finished and the contorl back to main. However; a1 is not despite it is closer to main stack frame?

How do I efficiently select ports in multi process C++ linux servers?

I am using Amazon Gamelift to manage a c++ game server in an Amazon Linux 2 environment. This service will launch multiple instances of the same game server on the same machine at nearly the same time. These processes then report back when they are ready and what port they are bound to. What is the best way to attempt to bind to ports in the same range. For instance, I may choose to use between 1900 and 2100, but I may need 100 processes started up. How do I avoid a ton of collisions as these processes try to all bind to different ports at nearly the same time?

lundi 27 juin 2022

c++ complains about __VA_ARGS__

The following code has been compiled with gcc-5.4.0 with no issues:

% gcc -W -Wall a.c
...

#include <stdio.h>
#include <stdarg.h>

static int debug_flag;
static void debug(const char *fmt, ...)
{
   va_list ap;

   va_start(ap, fmt);
   vfprintf(stderr, fmt, ap);
   va_end(ap);
}

#define DEBUG(...)               \
   do {                 \
      if (debug_flag) {       \
         debug("DEBUG:"__VA_ARGS__);  \
      }              \
   } while(0)

int main(void)
{
   int dummy = 10;
   debug_flag = 1;
   DEBUG("debug msg dummy=%d\n", dummy);
   return 0;
}

However compiling this with g++ has interesting effects:

% g++ -W -Wall -std=c++11 a.c
a.c: In function ‘int main()’:
a.c:18:10: error: unable to find string literal operator ‘operator""__VA_ARGS__’ with ‘const char [8]’, ‘long unsigned int’ arguments
    debug("DEBUG: "__VA_ARGS__); \

% g++ -W -Wall -std=c++0x
<same error>

% g++ -W -Wall -std=c++03
<no errors>

Changing debug("DEBUG:"__VA_ARGS__); to debug("DEBUG:" __VA_ARGS__); i.e. space before __VA_ARGS__ enables to compile with all three -std= options.

What is the reason for such behaviour? Thanks.

using remove method of std::list in a loop is creating segmentation fault

I am using remove() of std::list to remove elements in a for loop. But it is creating segmentation fault. I am not using iterators. Program is given below.

#include <iostream>
#include <list>

using namespace std;

int main() {
    list <int> li = {1, 2, 3, 4, 5};
    
    for(auto x : li)
    {
        if (x == 4) {
            li.remove(x);
        }
    }

    return 0;
}

In case of iterators, I understand that iterators are invalidated if we remove an element and we need to take care of incrementing iterator properly. But here I am not using iterators and I am using remove() which doesn't return any. Can any one please let me know if we can't use remove in a loop or if there is any issue with the code.

How to store full name with whitespace in array c++? [duplicate]

I want to store the full name in array with whitespace but when I type the name, the run to exit. Can you guys help me?

int main()
{
int user1, user2;
char name[100][10000];
int num[10000];
int temp;
cout << "Number of students: "; cin >> user1; cout << "\n";
for(int i = 0; i < user1; i++)
{
    cout << "Students No." << i + 1; 
    cout << "\nName: "; cin >> name[i];
    cout << "Num: "; cin >> num[i];
    cout << "\n";
}

Trying to make my program more efficient in terms of vectors, but I'm not sure how to go about it? [closed]

Here is my github link for the code to look at: https://gist.github.com/rarelambo21/e385c6dd228d7dc949fe689999d203b1

To give some context, I am working on some side projects in taking some of my old lab classes and trying to program them in other languages. Originally this program was for C# but I decided to code it in C++ and use vectors.

How the program works, is that it ask the user to some questions. The user can enter questions, answers and difficulty into the quiz, remove them, modify them and take the quiz as well. Option 6 is a debug feature I added to make sure everything is being added into the vector right. In the original lab, it used array list or list in C#, which is why I chose vectors.

My question is mainly for the function "removeQuestion()." That was my first time using vectors to thing length, and I wasn't sure if this was the most optimal way to remove vectors from the stack. I did it in this way because I wanted to remove a specific vector from the stack and out of all the options this was the way that made sense to me. If there is a better way I would like someone to point me in the right direction.

Also, I wanted to know why this line of code didn't work for the vector: question.erase(question[rIndex])

But why does this line work for vectors: question[rIndex] = inputQ

Also if there are other pointers that you can point out in my program that can make me a better programmer please feel free to inform me. This is my first time trying things out on my own so, I'm sure I made some mistakes or could have done things better in some way form or fashion.

PS, I added a lot of comments especially in the beginning of certain functions because someone told me that it is a good practice to comments things like that for the purposes of yourself and other going back and viewing your code. Are the comments a it too much, or it is a good mix?

Thank you.

dimanche 26 juin 2022

c++11: how to produce "spurious failures" upon compare_exchange_weak?

Is there a way that we can write some code to produce a "spurious failures" for the "weak" version of compare_exchange? While the same code should work well for compare_exchange_strong?

I wish to see the real difference between the "weak" and "strong" version of 2 apis, any sample for it?

Thanks a lot!

std::stringstream segfaullts and >> operator doesn't work as intended [closed]

I am reading pairs of words from a file and inserting them in some Data structures to measure perfomance. I initially had this piece of code and everything was working great.

for (std::string line; std::getline(file, line);) {
  std::stringstream iss(line);
  while (iss >> s) {
     //insert etc
  }
}

However to boost perfomance I moved the stringstream outside the loop and used .str() to set the contents to avoid constructor-destructor calls in each line. Now my stringstream reads everything fine but the inner while loop stops running after exactly 1 std::line. In the following code std::getline() reads the contents correctly,and also iss.str() has the contents from the line correctly,but the inner loop stops running and I get a segfault in the end. Any ideas? Heres the code

std::stringstream iss;
std::string s;
for (std::string line; std::getline(file, line);) {
  iss.str(std::move(line));
  std::cout << "ss: " << iss.str() << '\n'; // Has contents
  while (iss >> s) { // doesn't run in the 2nd iteration of for-loop
    std::cout << "s: " << s << '\n';
    token = Edit(s);
    if (token.empty() || tmp.empty()) continue;
    pf = PairFrequency(tmp, token);
    Insert();
    tmp = token;
  }
}

Error: expected constructor, destructor, or type conversion before '(' token C++

today i was trying a library for C++ but when i runned the file he gave me an error saying that i had to use -std=c++11 compiler option for start. so i did it. but after that he gaves another error in a file called hashtable_policy.h i can't paste the entire code because its long 2000 lines but i paste che position where it say there is the error

namespace std {}_GLIBCXX_VISIBILITY (default)
{
_GLIBCXX_BEGIN_NAMESPACE_VERSION

  template<typename _Key, typename _Value, typename _Alloc,
       typename _ExtractKey, typename _Equal,
       typename _H1, typename _H2, typename _Hash,
       typename _RehashPolicy, typename _Traits>
    class _Hashtable;

_GLIBCXX_END_NAMESPACE_VERSION
...

and that's the error

Compiling single file...
--------
- Filename: %CppIncludeDir2%\c++\bits\hashtable_policy.h
- Compiler Name: TDM-GCC 4.9.2 64-bit Release

Processing header file...
--------
- C Compiler: %BinDir0%\g++.exe
- Command: g++.exe "%CppIncludeDir2%\c++\bits\hashtable_policy.h" -std=c++11 -I"%CppIncludeDir0%" -I"%CppIncludeDir1%" -I"%CppIncludeDir2%" -L"%LibDir0%" -L"%LibDir1%" -L"%CppIncludeDir2%\PyreNet" -static-libgcc
%CppIncludeDir2%\c++\bits\hashtable_policy.h:34:37: error: expected constructor, destructor, or type conversion before '(' token
 namespace std {}_GLIBCXX_VISIBILITY (default)
                                     ^


Compilation results...
--------
- Errors: 1
- Warnings: 0
- Output Filename: %CppIncludeDir2%\c++\bits\hashtable_policy.h.gch
- Output Size: 1,09009170532227 MiB
- Compilation Time: 0,16s

the error is interested to the line 34 Here you can find the full code https://pastebin.com/bY46ebSq

Question about std::make_pair & std::atomic_bool

Why this code snippet does not compile with gcc 4.9.0, whereas it works well with gcc 12.1.

The same code snippet is compiled with the same option.

Here is the code snippet:

#include<atomic>
#include<thread>
#include<map>
#include<vector>
#include<iostream>

class Demo{
public:
Demo()
{
    mp_.insert(std::make_pair(1, true));
    mp_.insert(std::make_pair(2, true));
    mp_.insert(std::make_pair(3, true));
}

int Get(const int& integer, bool& flag)
{
    const auto itr = mp_.find(integer);
    if( itr == mp_.end())
    {
        return -1;
    }
    else
    {
        flag = itr->second;
        return 0;
    }
}
int Set(const int& integer, const bool& flag)
{
    const auto itr = mp_.find(integer);
    if( itr == mp_.end())
    {
        return -1;
    }
    else
    {
        itr->second = flag;
        return 0;
    }
}

private:
std::map<int, std::atomic<bool>> mp_;
};

int main()
{
    Demo demo;

    std::vector<std::thread> vec;

    vec.push_back(std::thread([&demo](){
        //while(true)
        {
            for(int i=0; i<9; i++)
            {
                bool cur_flag = false;
                if(demo.Get(i, cur_flag) == 0)
                {
                    demo.Set(i, !cur_flag);
                }
                std::this_thread::sleep_for(std::chrono::milliseconds(1000));
            }
        }
    }));

    vec.push_back(std::thread([&demo](){
        while(true)
        {
            for(int i=0; i<9; i++)
            {
                bool cur_flag = false;
                if(demo.Get(i, cur_flag)==0)
                {
                    std::cout << "(" << i << "," << cur_flag <<")" << std::endl;
                }
                std::this_thread::sleep_for(std::chrono::milliseconds(10));
            }
        }
    })
    );

    for(auto& thread:vec)
    {
        thread.join();
    }
}

Here is what gcc 4.9.0 complains:

<source>: In constructor 'Demo::Demo()':
<source>:11:39: error: no matching function for call to 'std::map<int, std::atomic<bool> >::insert(std::pair<int, bool>)'
     mp_.insert(std::make_pair(1, true));
                                       ^
<source>:11:39: note: candidates are:
In file included from /opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/map:61:0,
                 from <source>:3:
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:629:7: note: std::pair<typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_Select1st<std::pair<const _Key, _Tp> >, _Compare, typename __gnu_cxx::__alloc_traits<_Allocator>::rebind<std::pair<const _Key, _Tp> >::other>::iterator, bool> std::map<_Key, _Tp, _Compare, _Alloc>::insert(const value_type&) [with _Key = int; _Tp = std::atomic<bool>; _Compare = std::less<int>; _Alloc = std::allocator<std::pair<const int, std::atomic<bool> > >; typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_Select1st<std::pair<const _Key, _Tp> >, _Compare, typename __gnu_cxx::__alloc_traits<_Allocator>::rebind<std::pair<const _Key, _Tp> >::other>::iterator = std::_Rb_tree_iterator<std::pair<const int, std::atomic<bool> > >; std::map<_Key, _Tp, _Compare, _Alloc>::value_type = std::pair<const int, std::atomic<bool> >]
       insert(const value_type& __x)
       ^
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:629:7: note:   no known conversion for argument 1 from 'std::pair<int, bool>' to 'const value_type& {aka const std::pair<const int, std::atomic<bool> >&}'
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:637:9: note: template<class _Pair, class> std::pair<typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_Select1st<std::pair<const _Key, _Tp> >, _Compare, typename __gnu_cxx::__alloc_traits<_Allocator>::rebind<std::pair<const _Key, _Tp> >::other>::iterator, bool> std::map<_Key, _Tp, _Compare, _Alloc>::insert(_Pair&&) [with _Pair = _Pair; <template-parameter-2-2> = <template-parameter-1-2>; _Key = int; _Tp = std::atomic<bool>; _Compare = std::less<int>; _Alloc = std::allocator<std::pair<const int, std::atomic<bool> > >]
         insert(_Pair&& __x)
         ^
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:637:9: note:   template argument deduction/substitution failed:
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:633:32: error: no type named 'type' in 'struct std::enable_if<false, void>'
       template<typename _Pair, typename = typename
                                ^
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:650:7: note: void std::map<_Key, _Tp, _Compare, _Alloc>::insert(std::initializer_list<std::pair<const _Key, _Tp> >) [with _Key = int; _Tp = std::atomic<bool>; _Compare = std::less<int>; _Alloc = std::allocator<std::pair<const int, std::atomic<bool> > >]
       insert(std::initializer_list<value_type> __list)
       ^
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:650:7: note:   no known conversion for argument 1 from 'std::pair<int, bool>' to 'std::initializer_list<std::pair<const int, std::atomic<bool> > >'
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:679:7: note: std::map<_Key, _Tp, _Compare, _Alloc>::iterator std::map<_Key, _Tp, _Compare, _Alloc>::insert(std::map<_Key, _Tp, _Compare, _Alloc>::const_iterator, const value_type&) [with _Key = int; _Tp = std::atomic<bool>; _Compare = std::less<int>; _Alloc = std::allocator<std::pair<const int, std::atomic<bool> > >; std::map<_Key, _Tp, _Compare, _Alloc>::iterator = std::_Rb_tree_iterator<std::pair<const int, std::atomic<bool> > >; std::map<_Key, _Tp, _Compare, _Alloc>::const_iterator = std::_Rb_tree_const_iterator<std::pair<const int, std::atomic<bool> > >; std::map<_Key, _Tp, _Compare, _Alloc>::value_type = std::pair<const int, std::atomic<bool> >]
       insert(const_iterator __position, const value_type& __x)
       ^
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:679:7: note:   candidate expects 2 arguments, 1 provided
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:690:9: note: template<class _Pair, class> std::map<_Key, _Tp, _Compare, _Alloc>::iterator std::map<_Key, _Tp, _Compare, _Alloc>::insert(std::map<_Key, _Tp, _Compare, _Alloc>::const_iterator, _Pair&&) [with _Pair = _Pair; <template-parameter-2-2> = <template-parameter-1-2>; _Key = int; _Tp = std::atomic<bool>; _Compare = std::less<int>; _Alloc = std::allocator<std::pair<const int, std::atomic<bool> > >]
         insert(const_iterator __position, _Pair&& __x)
         ^
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:690:9: note:   template argument deduction/substitution failed:
<source>:11:39: note:   cannot convert 'std::make_pair<int, bool>((* &1), (* & true))' (type 'std::pair<int, bool>') to type 'std::map<int, std::atomic<bool> >::const_iterator {aka std::_Rb_tree_const_iterator<std::pair<const int, std::atomic<bool> > >}'
     mp_.insert(std::make_pair(1, true));
                                       ^
In file included from /opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/map:61:0,
                 from <source>:3:
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:705:9: note: template<class _InputIterator> void std::map<_Key, _Tp, _Compare, _Alloc>::insert(_InputIterator, _InputIterator) [with _InputIterator = _InputIterator; _Key = int; _Tp = std::atomic<bool>; _Compare = std::less<int>; _Alloc = std::allocator<std::pair<const int, std::atomic<bool> > >]
         insert(_InputIterator __first, _InputIterator __last)
         ^
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:705:9: note:   template argument deduction/substitution failed:
<source>:11:39: note:   candidate expects 2 arguments, 1 provided
     mp_.insert(std::make_pair(1, true));
                                       ^
<source>:12:39: error: no matching function for call to 'std::map<int, std::atomic<bool> >::insert(std::pair<int, bool>)'
     mp_.insert(std::make_pair(2, true));
                                       ^
<source>:12:39: note: candidates are:
In file included from /opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/map:61:0,
                 from <source>:3:
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:629:7: note: std::pair<typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_Select1st<std::pair<const _Key, _Tp> >, _Compare, typename __gnu_cxx::__alloc_traits<_Allocator>::rebind<std::pair<const _Key, _Tp> >::other>::iterator, bool> std::map<_Key, _Tp, _Compare, _Alloc>::insert(const value_type&) [with _Key = int; _Tp = std::atomic<bool>; _Compare = std::less<int>; _Alloc = std::allocator<std::pair<const int, std::atomic<bool> > >; typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_Select1st<std::pair<const _Key, _Tp> >, _Compare, typename __gnu_cxx::__alloc_traits<_Allocator>::rebind<std::pair<const _Key, _Tp> >::other>::iterator = std::_Rb_tree_iterator<std::pair<const int, std::atomic<bool> > >; std::map<_Key, _Tp, _Compare, _Alloc>::value_type = std::pair<const int, std::atomic<bool> >]
       insert(const value_type& __x)
       ^
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:629:7: note:   no known conversion for argument 1 from 'std::pair<int, bool>' to 'const value_type& {aka const std::pair<const int, std::atomic<bool> >&}'
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:637:9: note: template<class _Pair, class> std::pair<typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_Select1st<std::pair<const _Key, _Tp> >, _Compare, typename __gnu_cxx::__alloc_traits<_Allocator>::rebind<std::pair<const _Key, _Tp> >::other>::iterator, bool> std::map<_Key, _Tp, _Compare, _Alloc>::insert(_Pair&&) [with _Pair = _Pair; <template-parameter-2-2> = <template-parameter-1-2>; _Key = int; _Tp = std::atomic<bool>; _Compare = std::less<int>; _Alloc = std::allocator<std::pair<const int, std::atomic<bool> > >]
         insert(_Pair&& __x)
         ^
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:637:9: note:   template argument deduction/substitution failed:
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:633:32: error: no type named 'type' in 'struct std::enable_if<false, void>'
       template<typename _Pair, typename = typename
                                ^
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:650:7: note: void std::map<_Key, _Tp, _Compare, _Alloc>::insert(std::initializer_list<std::pair<const _Key, _Tp> >) [with _Key = int; _Tp = std::atomic<bool>; _Compare = std::less<int>; _Alloc = std::allocator<std::pair<const int, std::atomic<bool> > >]
       insert(std::initializer_list<value_type> __list)
       ^
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:650:7: note:   no known conversion for argument 1 from 'std::pair<int, bool>' to 'std::initializer_list<std::pair<const int, std::atomic<bool> > >'
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:679:7: note: std::map<_Key, _Tp, _Compare, _Alloc>::iterator std::map<_Key, _Tp, _Compare, _Alloc>::insert(std::map<_Key, _Tp, _Compare, _Alloc>::const_iterator, const value_type&) [with _Key = int; _Tp = std::atomic<bool>; _Compare = std::less<int>; _Alloc = std::allocator<std::pair<const int, std::atomic<bool> > >; std::map<_Key, _Tp, _Compare, _Alloc>::iterator = std::_Rb_tree_iterator<std::pair<const int, std::atomic<bool> > >; std::map<_Key, _Tp, _Compare, _Alloc>::const_iterator = std::_Rb_tree_const_iterator<std::pair<const int, std::atomic<bool> > >; std::map<_Key, _Tp, _Compare, _Alloc>::value_type = std::pair<const int, std::atomic<bool> >]
       insert(const_iterator __position, const value_type& __x)
       ^
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:679:7: note:   candidate expects 2 arguments, 1 provided
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:690:9: note: template<class _Pair, class> std::map<_Key, _Tp, _Compare, _Alloc>::iterator std::map<_Key, _Tp, _Compare, _Alloc>::insert(std::map<_Key, _Tp, _Compare, _Alloc>::const_iterator, _Pair&&) [with _Pair = _Pair; <template-parameter-2-2> = <template-parameter-1-2>; _Key = int; _Tp = std::atomic<bool>; _Compare = std::less<int>; _Alloc = std::allocator<std::pair<const int, std::atomic<bool> > >]
         insert(const_iterator __position, _Pair&& __x)
         ^
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:690:9: note:   template argument deduction/substitution failed:
<source>:12:39: note:   cannot convert 'std::make_pair<int, bool>((* &2), (* & true))' (type 'std::pair<int, bool>') to type 'std::map<int, std::atomic<bool> >::const_iterator {aka std::_Rb_tree_const_iterator<std::pair<const int, std::atomic<bool> > >}'
     mp_.insert(std::make_pair(2, true));
                                       ^
In file included from /opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/map:61:0,
                 from <source>:3:
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:705:9: note: template<class _InputIterator> void std::map<_Key, _Tp, _Compare, _Alloc>::insert(_InputIterator, _InputIterator) [with _InputIterator = _InputIterator; _Key = int; _Tp = std::atomic<bool>; _Compare = std::less<int>; _Alloc = std::allocator<std::pair<const int, std::atomic<bool> > >]
         insert(_InputIterator __first, _InputIterator __last)
         ^
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:705:9: note:   template argument deduction/substitution failed:
<source>:12:39: note:   candidate expects 2 arguments, 1 provided
     mp_.insert(std::make_pair(2, true));
                                       ^
<source>:13:39: error: no matching function for call to 'std::map<int, std::atomic<bool> >::insert(std::pair<int, bool>)'
     mp_.insert(std::make_pair(3, true));
                                       ^
<source>:13:39: note: candidates are:
In file included from /opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/map:61:0,
                 from <source>:3:
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:629:7: note: std::pair<typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_Select1st<std::pair<const _Key, _Tp> >, _Compare, typename __gnu_cxx::__alloc_traits<_Allocator>::rebind<std::pair<const _Key, _Tp> >::other>::iterator, bool> std::map<_Key, _Tp, _Compare, _Alloc>::insert(const value_type&) [with _Key = int; _Tp = std::atomic<bool>; _Compare = std::less<int>; _Alloc = std::allocator<std::pair<const int, std::atomic<bool> > >; typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_Select1st<std::pair<const _Key, _Tp> >, _Compare, typename __gnu_cxx::__alloc_traits<_Allocator>::rebind<std::pair<const _Key, _Tp> >::other>::iterator = std::_Rb_tree_iterator<std::pair<const int, std::atomic<bool> > >; std::map<_Key, _Tp, _Compare, _Alloc>::value_type = std::pair<const int, std::atomic<bool> >]
       insert(const value_type& __x)
       ^
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:629:7: note:   no known conversion for argument 1 from 'std::pair<int, bool>' to 'const value_type& {aka const std::pair<const int, std::atomic<bool> >&}'
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:637:9: note: template<class _Pair, class> std::pair<typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_Select1st<std::pair<const _Key, _Tp> >, _Compare, typename __gnu_cxx::__alloc_traits<_Allocator>::rebind<std::pair<const _Key, _Tp> >::other>::iterator, bool> std::map<_Key, _Tp, _Compare, _Alloc>::insert(_Pair&&) [with _Pair = _Pair; <template-parameter-2-2> = <template-parameter-1-2>; _Key = int; _Tp = std::atomic<bool>; _Compare = std::less<int>; _Alloc = std::allocator<std::pair<const int, std::atomic<bool> > >]
         insert(_Pair&& __x)
         ^
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:637:9: note:   template argument deduction/substitution failed:
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:633:32: error: no type named 'type' in 'struct std::enable_if<false, void>'
       template<typename _Pair, typename = typename
                                ^
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:650:7: note: void std::map<_Key, _Tp, _Compare, _Alloc>::insert(std::initializer_list<std::pair<const _Key, _Tp> >) [with _Key = int; _Tp = std::atomic<bool>; _Compare = std::less<int>; _Alloc = std::allocator<std::pair<const int, std::atomic<bool> > >]
       insert(std::initializer_list<value_type> __list)
       ^
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:650:7: note:   no known conversion for argument 1 from 'std::pair<int, bool>' to 'std::initializer_list<std::pair<const int, std::atomic<bool> > >'
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:679:7: note: std::map<_Key, _Tp, _Compare, _Alloc>::iterator std::map<_Key, _Tp, _Compare, _Alloc>::insert(std::map<_Key, _Tp, _Compare, _Alloc>::const_iterator, const value_type&) [with _Key = int; _Tp = std::atomic<bool>; _Compare = std::less<int>; _Alloc = std::allocator<std::pair<const int, std::atomic<bool> > >; std::map<_Key, _Tp, _Compare, _Alloc>::iterator = std::_Rb_tree_iterator<std::pair<const int, std::atomic<bool> > >; std::map<_Key, _Tp, _Compare, _Alloc>::const_iterator = std::_Rb_tree_const_iterator<std::pair<const int, std::atomic<bool> > >; std::map<_Key, _Tp, _Compare, _Alloc>::value_type = std::pair<const int, std::atomic<bool> >]
       insert(const_iterator __position, const value_type& __x)
       ^
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:679:7: note:   candidate expects 2 arguments, 1 provided
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:690:9: note: template<class _Pair, class> std::map<_Key, _Tp, _Compare, _Alloc>::iterator std::map<_Key, _Tp, _Compare, _Alloc>::insert(std::map<_Key, _Tp, _Compare, _Alloc>::const_iterator, _Pair&&) [with _Pair = _Pair; <template-parameter-2-2> = <template-parameter-1-2>; _Key = int; _Tp = std::atomic<bool>; _Compare = std::less<int>; _Alloc = std::allocator<std::pair<const int, std::atomic<bool> > >]
         insert(const_iterator __position, _Pair&& __x)
         ^
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:690:9: note:   template argument deduction/substitution failed:
<source>:13:39: note:   cannot convert 'std::make_pair<int, bool>((* &3), (* & true))' (type 'std::pair<int, bool>') to type 'std::map<int, std::atomic<bool> >::const_iterator {aka std::_Rb_tree_const_iterator<std::pair<const int, std::atomic<bool> > >}'
     mp_.insert(std::make_pair(3, true));
                                       ^
In file included from /opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/map:61:0,
                 from <source>:3:
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:705:9: note: template<class _InputIterator> void std::map<_Key, _Tp, _Compare, _Alloc>::insert(_InputIterator, _InputIterator) [with _InputIterator = _InputIterator; _Key = int; _Tp = std::atomic<bool>; _Compare = std::less<int>; _Alloc = std::allocator<std::pair<const int, std::atomic<bool> > >]
         insert(_InputIterator __first, _InputIterator __last)
         ^
/opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/bits/stl_map.h:705:9: note:   template argument deduction/substitution failed:
<source>:13:39: note:   candidate expects 2 arguments, 1 provided
     mp_.insert(std::make_pair(3, true));
                                       ^

Could somebody shed some light on the reason lies behind it?

Thread-safety about `std::map

In general, it's not thread-safe to access the same instance of std::map from different threads.

But is it could be thread-safe under such a condition:

  1. no more element would be added to the instance of std::map after it has been initialized
  2. the type of values of the std::map is std::atomic<T>

Here is the demo code:

#include<atomic>
#include<thread>
#include<map>
#include<vector>
#include<iostream>

class Demo{
public:
Demo()
{
    mp_.insert(std::make_pair(1, true));
    mp_.insert(std::make_pair(2, true));
    mp_.insert(std::make_pair(3, true));
}

int Get(const int& integer, bool& flag)
{
    const auto itr = mp_.find(integer);
    if( itr == mp_.end())
    {
        return -1;
    }
    else
    {
        flag = itr->second;
        return 0;
    }
}
int Set(const int& integer, const bool& flag)
{
    const auto itr = mp_.find(integer);
    if( itr == mp_.end())
    {
        return -1;
    }
    else
    {
        itr->second = flag;
        return 0;
    }
}

private:
std::map<int, std::atomic<bool>> mp_;
};

int main()
{
    Demo demo;

    std::vector<std::thread> vec;

    vec.push_back(std::thread([&demo](){
        while(true)
        {
            for(int i=0; i<9; i++)
            {
                bool cur_flag = false;
                if(demo.Get(i, cur_flag) == 0)
                {
                    demo.Set(i, !cur_flag);
                }
                std::this_thread::sleep_for(std::chrono::milliseconds(1000));
            }
        }
    }));

    vec.push_back(std::thread([&demo](){
        while(true)
        {
            for(int i=0; i<9; i++)
            {
                bool cur_flag = false;
                if(demo.Get(i, cur_flag)==0)
                {
                    std::cout << "(" << i << "," << cur_flag <<")" << std::endl;
                }
                std::this_thread::sleep_for(std::chrono::milliseconds(10));
            }
        }
    })
    );

    for(auto& thread:vec)
    {
        thread.join();
    }
}

samedi 25 juin 2022

error: no matching function for call to'arch::newsucc(). I tried everything,but nothing worked [duplicate]

I tried to call the function print and it worked.The function newsucc the only one who had this problem. I tried to rename it, and made the function at class national like this virtual void newsucc(int students, int succ) { }; and a lot of things but nothing worked the code about an exam at our country that could national exam, we should use class and inheritance in c++ the base class is national the child class are arch and IT

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

class National {
protected:
    string name;
    int students;
    int succ;

public:
    National()
    {
        name = "";
        students = 0;
        succ = 0;
    }
    National(string ex, int s, int su)
    {

        name = ex;
        students = s;
        succ = su;
    }
    National(National&N ) {

        this->name = N.name;
        this->students = N.students;
        this->succ = N.succ;

    }
    void print()
    {
        cout << "The results of the National Exam" << endl;

    }

    virtual void newsucc() { };

    ~National()
    {
        cout << "The End" << endl;
    }
};
class arch : public National {
public:
    arch(int _students, int _succ) :National("architecture engineering", _students, _succ)
    {
    }

    ~arch()
    {

    }
    void print() {

        cout << "The National Exam's result of the architecture engineering is" << endl;

    }
     void newsucc(int _students,int _succ)
    {
        cout << "The number of the Successful students" <<  (_students*_succ)/100 << endl;

    }
};
class IT : public National
{
public:
    IT (int _students, int _succ) : National("IT engineering", _students, _succ)
    {
    }

    ~IT()
    {

    }
    void print() {

        cout << "The National Exam's result of the IT engineering" << endl;

    }
    void newsucc(int _students,int _succ)
    {
        cout << "The number of the Successful students" <<  (_students*_succ)/100 << endl;
    }
};

int main()
{



    cout << "-----------------------------------" << endl;

    arch obj2 (300,65);
    obj2.newsucc();


    cout << "-----------------------------------" << endl;
    IT obj3 (500,40);
    obj3.newsucc();

}

static variable in variadic template function [duplicate]

I want to use a static variable in a function which accept variadic template to accept variable number of arguments. Since the function gets called recursively I expect the value of i to be incremented for each call. But the static variable is incremented only once rather than for each function call. Here is the program which demonstrate this behavior.

#include <iostream>
#include <string>

using namespace std::string_literals;

void printArgs() {}

template<typename T, typename... Ts>
void printArgs(T first, Ts... rest)
{
    static int32_t i{};
    ++i;
    std::cout << i << ". " << first << std::endl;
    printArgs(rest...);
}

int main()
{
    printArgs("hello cpp"s, "c++11", 'x', 1234, 0xab45, 0b010101);
}

Output

1. hello cpp
1. c++11
1. x
1. 1234
1. 43845
1. 21

If I make the static variable global by moving it outside the function definition, it gets incremented for each function invocation.

static int32_t i{};
template<typename T, typename... Ts>
void printArgs(T first, Ts... rest)
{
    ++i;
    std::cout << i << ". " << first << std::endl;
    printArgs(rest...);
}

output

1. hello cpp
2. c++11
3. x
4. 1234
5. 43845
6. 21

How the variadic templates function behave in this scenario? Does the compiler create a separate function for each function invocation?

Generate random float number in c++ between -1 and 1 [duplicate]

Is there a way that I can generate a random number between -1 and 1 in c++? I have been looking into this problem and didn't find a suitable solution.

c++11 is it safe to return an intializer_list value? [duplicate]

I've this simple function:

initializer_list<int> f(){return {1,2,3};}

g++ gives a warning saying:

warning: returning temporary initializer_list does not extend the lifetime of the underlying array [-Winit-list-lifetime]

Is there any risk to return an {1, 2, 3}? Thanks for explanations!

vendredi 24 juin 2022

c++11 promise object gets invalid, but its future object neither returns value nor throw exception

I've got this test code to see, if a promise object is out of lifecycle, what happen to its future object:

#include <chrono>
#include <future>
#include <iostream>
#include <thread>
using namespace std;

void getValue(future<int>& future) {
    cout << "sub process 1 \n";
    try {
        cout << "sub process 2 \n";
        int value = future.get();
        cout << "sub process 3\n";
        cout << value << endl;
    } catch (future_error &e) {
        cerr << e.code() << '\n' << e.what() << endl;
    } catch (exception e) {
        cerr << e.what() << endl;
    }
    cout << "sub process 4\n";
}
int main() {
    thread t;
    {
        promise<int> plocal;
        future<int> flocal = plocal.get_future();
        t = thread(getValue, ref(flocal));
    }
    t.join();
    return 0;
}

I expect that in getValue function, it either prints future::get result, or throws out runtime exception and prints exception info, because plocal has been destructed in "main".

Acturally, this program prints:

sub process 1
sub process 2

and ends.

How does atomic seq_cst memory order actually work?

For example, there are shared variables.

int val;
Cls obj;

An atomic bool variable acts as an data indicator.

std::atomic_bool flag = false;

Thread 1 only set these variables.

while (flag == true) { /* Sleep */ }

val = ...;
obj = ...;

flag = true; /* Set flag to true after setting shared variables. */

Thread 2 only get these variables.

while (flag != true) { /* Sleep */ }

int local_val = val;
Cls local_obj = obj;

flag = false; /* Set flag to false after using shared variables. */

My questions are:

  1. For std::memory_order_seq_cst, which is default for std::atomic_bool, is it safe to set or get shared variables after while (...) {}?

  2. Using bool instead of std::atomic_bool is correct or not?

Simple way to display image without external library in C++

I have an image represented as a list of pixels (r, g, b, a) and would like to display it on the screen.

I look for a simple solution without external libraries (being aware of the many good answers involving those). On the other hand I don't care about "fancy" stuff like UI, double buffering, antialiasing, ...

Basically just a plane where pixels can be drawn to.

A Windows solution would be preferred, but if it's simple, Linux is also fine.

jeudi 23 juin 2022

How to tar dereferenced files in c++

I need to compress or tar referenced files using c++ but couldn't find any solution yet. Is there any way to tar dereferenced files in c++ with same function as --deref in shell?

What's the use of declare a named right reference in practice?

As named right reference is left variable. I don't know what's the sense of allowing declare right reference in practice like following code snippet.

Object &&ro = std::move(lo);

what is the purpose of the [] that follow after auto keyword? [duplicate]

Hi I came across this example

 auto [ptr, ec] { std::from_chars(str.data(), str.data() + str.size(), result) };

Can someone please explain the what is the syntax autp [ptr,ec] {} , this is something I am seeing for the first time. Is this new in C++ ?

Any link to the documentation will be very much appreciated.

Thanks

Can't seem to make the functions work on my code. Any tips? [closed]

Guys really frustrated here. Spent many hours on this but can't seem to figure it out. I have attached my code below and the instructions after it. I keep getting no matching function to call x,y,z.

    using namespace std;

    // Function Prototypes
    
    const int NUM_CHARACTERS=8;
    char password[NUM_CHARACTERS]={'K','9','$','o','7','t','t','u'};
    bool validCharacter(char ch); /*take char as param and returns true if alphanum
    or ($, *, ^ , %). Else false*/
    char getValidCharacter(); /* to enter an alphanum char  and
    only ($, *, ^ , %)and loops until a valid char. it returns valid char*/
    void displayPassword(char password[NUM_CHARACTERS]);/*takes pass array as param and displays in
     correct format.*/
    void ChangePassword(char password[NUM_CHARACTERS]);/* takes pass array as a param,
    it allows to enter in NUM_CHARACTERS characters.
    stores each value  in pass array.*/
    void displayValidPassword(char password[NUM_CHARACTERS]);/*displays
    whether password is valid or not*/
    void DisplayMenuOptions();// Displays menu
    int SelectValidMenuOption();// choose correct option
    bool all_checked= false;
    char temp[NUM_CHARACTERS];
    int count=0;
    int specials=0;
    bool validPassword= true;
    bool nosymb=false;
     char special[]={'$','*','^','%'};




int main() {
    const int NUM_CHARACTERS =8; // password limit
    int menuCh=0;

    do {
        switch (menuCh)
        {
            case 1:
                displayPassword();
                break;
            case 2:
                ChangePassword(), getValidCharacter(), displayPassword();
                break;
        }
        cout << " Welcome to the Password Program\n";
    } while (menuCh !=4);

    return 0;
}













void displayValidPassword(char password[NUM_CHARACTERS])
{
    // password valid if there's one special and 2 numeric character
    // loop to check
     for (int p=0; p<NUM_CHARACTERS;p++)
     {
         if(!isalnum(password[p]))
             specials++;
     }
     for (int q=0; q<NUM_CHARACTERS;q++)
         if(isdigit(password[q]))
             count++;

     if(!special) nosymb= true;

     if (nosymb= false && count>=2 && specials >0)
         validPassword=true;
}







void displayPassword(char password[NUM_CHARACTERS])
{
cout<< password [NUM_CHARACTERS]<< endl;
}


void ChangePassword(char password[NUM_CHARACTERS])
{
cout<<"Enter your new password\n";
cin>> temp[NUM_CHARACTERS];
temp[NUM_CHARACTERS]=password[NUM_CHARACTERS];
}









bool ValidCharacter(char ch)
{
    if (isalnum(ch) != 0 || isalnum(ch) != 0 || isalnum(ch) != 0 ||
        isalnum(ch) != 0)
        return true;


}

  char getValidCharacter(char ch)
 {
        //user enter's password
        cout<<"Enter password\n";
        cin>>ch;
       // input validation
    {
            if (ValidCharacter(ch) ) all_checked= true;
            // prompt user
             if(!all_checked)
             cout << "Try again with valid characters( only alphanumeric and $,*,^,%)\n";
             cin>>ch;

    }
    return ch;

}
























void DisplayMenuOptions()
{
    cout<<"1) Display Password\n"<<"2) Change the password\n"
    <<"3) Display whether or not the password is valid\n"
    <<"4) Quit\n";
}

int SelectValidMenuOption()
{
    int menuCh;
    // get choice from user
    DisplayMenuOptions();
    cout<<"Enter in your choice:";
    cin>>menuCh;
    while ((menuCh<=1) ||(menuCh>4)) //input validation loop
    {

        // get choice from user
        DisplayMenuOptions();
        cout<<"Enter in your choice:";
        cin>>menuCh;
    }
    return menuCh;

Using the following array:

// may be declared outside the main function const int NUM_CHARACTERS =8;

// may only be declared within the main function char password[NUM_CHARACTERS]={'K','9','$','o','7','t','t','u'};

Be sure to compile using g++ -std=c++11 Password.cpp

Write a C++ program to run a menu-driven program with the following choices:

  1. Display the password

  2. Change the password

  3. Display whether or not the password is valid

  4. Quit Make sure your program conforms to the following requirements:

    Follow the course coding standards outlined in Coding Standards_ (COP3363 Introduction to Programming in C++ for Majors).docx

    .

You will lose 1 point for each coding standard violation.

This program should be called Password.cpp
Include the basic header in your program Header for Assignments.docx 

. (5 points deduction is missing)
Your solution must be built to allow the size of the array to change in the future without requiring any changes to your functions. You will lose points if you do not satisfy this requirement.
Write a function called validCharacter that takes a character as a parameter returns true if the character is an alphanumeric character or one of the following symbols ($, *, ^ , %) and false otherwise. (5 points).

bool validCharacter(char ch)

Write a function called getValidCharacter that allows a user to enter in an alphanumeric character or the following symbols ($, *, ^ , %)  and loops until a valid character is entered. It returns the valid character. (5 points).

char getValidCharacter();

Write a function called displayPassword that takes the password array as a parameter and displays the password in the format in the sample run below. (15 points).

void displayPassword(char password[NUM_CHARACTERS]);

Write a function called ChangePassword that takes the password array as a parameter, it allows the user to enter in NUM_CHARACTERS characters. It then stores each value entered in the password array. (20 points).

void ChangePassword(char password[NUM_CHARACTERS]);

Write a function called displayValidPassword that takes the password array as a parameter, it displays whether or not the password is valid. A valid password contains at least 1 special and 2 numeric characters.(20 points).

//displays whether or not the password is valid void displayValidPassword(char password[NUM_CHARACTERS]);

mercredi 22 juin 2022

Pushing non dynamically allocated objects to a vector of pointers

I've been trying to figure out this issue while I was coding on Codeblocks but didn't have any luck.

So basically I have the following code inside a function:

Node * newNode;
newNode->data = num;
//root is defined somwhere at the top as 'Node * root';
root->adj.push_back(newNode);

and the following struct:

struct Node{
    int data;
    vector<Node*> adj;
};

When I do the push_back to the vector the program just cycles for 2-3 seconds and exits with a non-zero exit code. If I allocate the memory dynamically It seems to work correctly. Does the program somehow blow up when the pointer is not pointing to a specific block of memory?

Error LNK2019 when i try pass a vector into a constructor [duplicate]

I new in c++ and programming and programming in general. I'm trying to do my own Yahtzee game to train. But I can't understand why this error is happening...

My code:

#include <iostream>
#include "Jogador.h"
#include "Partida.h"

int main()
{
    int partidas = 1;
    Jogador j1("Mateus");
    std::cout << "Nome do jogador 1: " << j1.getNome() << std::endl;
    std::vector<Jogador> jogadores{};
    jogadores.push_back(j1);

    Partida partida(jogadores,partidas);

    return 0;
}

Class Partida.cpp

#include "Partida.h"
#include <vector>

Partida::Partida(std::vector<Jogador> jogadores, int partidas = 0)  {
    this->partidas = partidas;

    for (auto& jogador : jogadores)
    {
        this->jogadores.pop_back(jogador);
    }
    
};

Class Jogador.h

#pragma once
#include <iostream>
#include <string>
#include <vector>

class Jogador
{
    std::string nome;
    int pontuacao {0};
    int chances {3};
    std::vector<int> dados;
    std::vector<int> cartela {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

public:
    Jogador(std::string nome = " ") : nome(nome) {};
     
    ......
};

Erros:

Gravidade   Código  Projeto Descrição   Arquivo Linha   Estado de Supressão
Erro    LNK2019 Yahtzee símbolo externo não resolvido, "public: __cdecl Partida::Partida(class std::vector<class Jogador,class std::allocator<class Jogador> > &,int)" (??0Partida@@QEAA@AEAV?$vector@VJogador@@V?$allocator@VJogador@@@std@@@std@@H@Z), referenciado na função main    ..\repos\Yahtzee\Yahtzee\Main.obj   1   


Gravidade   Código  Projeto Descrição   Arquivo Linha   Estado de Supressão
Erro    LNK1120 Yahtzee 1 externo não resolvidos    ..\repos\Yahtzee\x64\Debug\Yahtzee.exe  1   

Could someone help me and explain to me why this error is happening??

Thanks!

converting to ‘A’ from initializer list would use explicit constructor ‘A::A(int)’

I am trying to migrate an old c++03 codebase to c++11. But I fails to understand what gcc is warning me about in the following case:

% g++ -std=c++03 t.cxx
% g++ -std=c++11 t.cxx
t.cxx: In function ‘int main()’:
t.cxx:8:21: warning: converting to ‘A’ from initializer list would use explicit constructor ‘A::A(int)’
    8 | int main() { B b = {}; }
      |                     ^
t.cxx:8:21: note: in C++11 and above a default constructor can be explicit

where

struct A {
  explicit A(int i = 42) {}
};
struct B {
  A a;
};

int main() {
  B b = {};
  return 0;
}

All I am trying to do is a basic zero initialization here. It seems to be legal for c++03 but I fail to understand how to express the equivalent in c++11.


For reference, I am using:

% g++ --version
g++ (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0

mardi 21 juin 2022

How to fix segmentation fault in C++ [closed]

I have one function Chekusers() which requires 4 argument, if I pass only 3 arguments so by default what value will be picked for 4th element. It is causing segmentation fault.

Function call:

Checkusers(u1, u2, u3):

Function definition:

int Checkusers(int u1, int u2, int u3, int u4) 
{
   FirstAndLastUsers(u1, u4); //here I am getting segmentation fault

}

I am using gdb compiler, i am not getting compile time error but it gives segmentation fault at run time. How to fix it.

type casting using constructors in C++

in the code below:

// implicit conversion of classes:
#include <iostream>
using namespace std;

class A {};

class B {
public:
  // conversion from A (constructor):
  B (const A& x) {}
  // conversion from A (assignment):
  B& operator= (const A& x) {return *this;}
  // conversion to A (type-cast operator)
  operator A() {return A();}
};

int main ()
{
  A foo;
  B bar = foo;    // calls constructor
  bar = foo;      // calls assignment
  foo = bar;      // calls type-cast operator
  return 0;
}

in the main function, foo is an object of type A. then in the next line when its written B bar = foo; what is converted to type B? after this line is the a an object of type B?

Using std::move when returning an object [duplicate]

If I have the following function:

MyObject Process(std::string par1, int par2){
     MyObject message;
     // Do some processing here
    return message;
}

Can this be implemented like this:

MyObject Process(std::string par1, int par2){
         MyObject message;
         // Do some processing here
        return std::move(message);
    }

And what is the difference between both? (I have the notion that the second one will not copy the object message but just move it, but since message function scope is finishing, what does this represent?

Use __gnu_parallel::sort() with nvcc

I am using Ubuntu 16.04 with NVCC 7.5 and GCC 5.4.0.

testFile.cu

#include <math.h>
#include <parallel/algorithm>
void main(){
    
      <some work is beeing donbe here>

      __gnu_parallel::sort(vector.begin(),vector.end(),<comparator function>);
}

I am getting the errors

/usr/include/c++/5/tr1/cmath(424): error: function "acosh(float)" has already been defined

/usr/include/c++/5/tr1/cmath(442): error: function "asinh(float)" has already been defined

/usr/include/c++/5/tr1/cmath(461): error: function "atanh(float)" has already been defined

/usr/include/c++/5/tr1/cmath(477): error: function "cbrt(float)" has already been defined

/usr/include/c++/5/tr1/cmath(495): error: function "copysign(float, float)" has already been defined

/usr/include/c++/5/tr1/cmath(516): error: function "erf(float)" has already been defined

/usr/include/c++/5/tr1/cmath(532): error: function "erfc(float)" has already been defined

/usr/include/c++/5/tr1/cmath(550): error: function "exp2(float)" has already been defined

/usr/include/c++/5/tr1/cmath(566): error: function "expm1(float)" has already been defined

/usr/include/c++/5/tr1/cmath(608): error: function "fdim(float, float)" has already been defined

Can anybody please let me know how __gnu_parallel::sort can be used with nvcc. Thanks in advance.

lundi 20 juin 2022

How to store command output and exitcode from terminal in a variable

From here I have the code that gives me the command line output and the exit code. Unfortunately I don't understand much of that operator overloading and if I try to rewrite it to the simple code I know (with global variables i.e.) I always get the wrong exit code status of 0.

So how can I modify the following code so I can store the output and the exit code status for future use?

#include <cstdio>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <array>


struct CommandResult {
    std::string output;
    int exitstatus;

    friend std::ostream &operator<<(std::ostream &os, const CommandResult &result) {
        os << "command exitstatus: " << result.exitstatus << " output: " << result.output;
        return os;
    }
    bool operator==(const CommandResult &rhs) const {
        return output == rhs.output &&
               exitstatus == rhs.exitstatus;
    }
    bool operator!=(const CommandResult &rhs) const {
        return !(rhs == *this);
    }
};


class Command {

public:
    /**
     * Execute system command and get STDOUT result.
     * Like system() but gives back exit status and stdout.
     * @param command system command to execute
     * @return CommandResult containing STDOUT (not stderr) output & exitstatus
     * of command. Empty if command failed (or has no output). If you want stderr,
     * use shell redirection (2&>1).
     */
    static CommandResult exec(const std::string &command) {
        int exitcode = 255;
        std::array<char, 1048576> buffer {};
        std::string result;
#ifdef _WIN32
#define popen _popen
#define pclose _pclose
#define WEXITSTATUS
#endif
        FILE *pipe = popen(command.c_str(), "r");
        if (pipe == nullptr) {
            throw std::runtime_error("popen() failed!");
        }
        try {
            std::size_t bytesread;
            while ((bytesread = fread(buffer.data(), sizeof(buffer.at(0)), sizeof(buffer), pipe)) != 0) {
                result += std::string(buffer.data(), bytesread);
            }
        } catch (...) {
            pclose(pipe);
            throw;
        }
        exitcode = WEXITSTATUS(pclose(pipe));
        return CommandResult{result, exitcode};
    }
};

int main ()
{
    std::cout << Command::exec("echo blablub") << std::endl;
}

Here is my code, the global variable is correct in the function but is overwritten afterwards.

#include <cstdio>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <array>

int exitcode = 555;

std::string exec(const std::string cmd) {
    
    int exitcode = 255;
    std::array<char, 128> buffer {};
    std::string result;
    
    
    #ifdef _WIN32
    #define popen _popen
    #define pclose _pclose
    #define WEXITSTATUS
    #endif
    
    
    FILE *pipe = popen(cmd.c_str(), "r");
    if (pipe == nullptr) {
        throw std::runtime_error("popen() failed!");
    }
    try {
        std::size_t bytesread;
        while ((bytesread = fread(buffer.data(), sizeof(buffer.at(0)), sizeof(buffer), pipe)) != 0) {
            result += std::string(buffer.data(), bytesread);
        }
    } catch (...) {
        pclose(pipe);
        throw;
    }    
    
    exitcode = WEXITSTATUS(pclose(pipe));
    std::cout<<exitcode<<'\n';
    return result;
}



int main (){
    exec("echo bla");
    std::cout<<exitcode<<'\n';
}

What's the relation between `std::cout` and `std::ostream`?

I saw the code snippet below somewhere.

#include <iostream>


int main()
{
    std::ostream& os = std::cout;

    os << "thanks a lot" << std::endl;
    return 0;
}

Since the aforementioned code snippet works well, it indicates that std::cout is derived from std::ostream. But I can't find any direct reference yet.

As per the document, which says that[emphasis mine]:

The global objects std::cout and std::wcout control output to a stream buffer of implementation-defined type (derived from std::streambuf), associated with the standard C output stream stdout.

The above quotation says that std::cout controls ouput to a type which derived from std::streambuf other than std::cout derived from std::streambuf.

And I only find the declaration of std::cout in a file named /usr/include/c++/7/iostream:

  extern ostream cout;      /// Linked to standard output

I can't find the implementation of std::cout.

using c++ overloaded operator function as member function?

From c++ how to program 10th edition by deitel


//Fig. 10.3: PhoneNumber.h
//PhoneNumber class definition
#ifndef PHONENUMBER_H
#define PHONENUMBER_H

#include <iostream>
#include <string>

class PhoneNumber
{
    friend std::ostream& operator<<(std::ostream&, const PhoneNumber&);
    friend std::istream& operator>>(std::istream&, PhoneNumber&);

private:
    std::string areaCode; //3-digit area code
    std::string exchange; //3-digit exchange
    std::string line; //4-digit line
};
#endif // PHONENUMBER_H
//Fig. 10.4: PhoneNumber.cpp
//Overloaded stream insertion and stream extraction operators
#include <iomanip>
#include "PhoneNumber.h"
using namespace std;

//overloaded stream insertion operator; cannot be a member function
//if we would like to invoke it with cout << somePhoneNumber;

ostream& operator<<(ostream& output, const PhoneNumber& number)
{
    output << "Area code: " << number.areaCode << "\nExchange: "
        << number.exchange << "\nLine: " << number.line << "\n"
        << "(" << number.areaCode << ") " << number.exchange << "-"
        << number.line << "\n";
    return output; //enables cout << a << b << c;
}

//overloaded stream extraction operator; cannot be a member function
//if we would like to invoke it with cin >> somePhoneNumber;
istream& operator>>(istream& input, PhoneNumber& number)
{
    input.ignore(); //skip (
    input >> setw(3) >> number.areaCode; //input area code
    input.ignore(2); //skip ) and space
    input >> setw(3) >> number.exchange; //input exchange
    input.ignore(); //skip dash (-)
    input >> setw(4) >> number.line; //input line
    return input; //enables cin >> a >> b >> c
}

//Fig. 10.5: fig10_5.cpp
//Demonstrating Class PhoneNumber's overloaded stream insertion
//and stream extraction operators.

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

using namespace std;

int main()
{
    PhoneNumber phone; //create object phone

    cout << "Enter phone number in the form (555) 555-5555:" << endl;

    //cin >> phone invokes operator>> by implicitly issuing
    //the non-member function call operator>>(cin, phone)
    cin >> phone;

    //cout << phone invokes operator<< bby implicitly issuing
    //the non-member function call operator<<(cout, phone)
    cout << phone << endl;
}

I understand from the book that the overloaded operator function for binary operator can be member function only when the left operand is an object of the class in which the function is a member because the member function can only be accessed by left operand which is the object of the class.

however I don't understand this part

" The overloaded stream insertion operator (<<) is used in an expression in which the left operand has type ostream&, as in cout << classObject. To use the operator in this manner where the right operand is an object of a user-defined class, it must be overloaded as a non-member function. To be a member function, operator << would have to be a member of class ostream. This is not possible for user-defined classes, since we are not allowed to modify C++ Standard Library classes. "

my question is

  1. whether the stream extraction and insertion operator is part of the ostream and istream respectively?
  2. what does the part highlighted in bold mean?

My guess is that we cannot add user defined function into the C++ Standard Library class but the part in bold makes me kind of confused. do we have to add the operator << as member of class ostream to make the overloaded operator function as member function of ostream?

I always thought that stream << and >> operator were part of ostream and istream respectively.

Correct me if I am wrong. thank you in advance.

How to solve the problem that the subclass inherits the base class and meanwhile the base class is a template parameter

#include <iostream>
 using namespace std;
 
 template <typename Child>
 struct Base
 {
     void interface()
     {
         static_cast<Child*>(this)->implementation();
     }
 };
 
 template<typename T,
     template<class T> class Base
 >
 struct Derived : Base<Derived >
 {
     void implementation(T t=0)
     {
          t = 0;
         cerr << "Derived implementation----" << t;
     }
 };



 int main()
 {
     Derived<int,Base<Derived>> d; //Base class as a template parameter is must  
     d.interface();  // Prints "Derived implementation"
 
     return 0;
 }

I hope Derived class inherits from a template parameter Base class,meanwhile hope the instance of Base class depend on Derived class, the Derived class have another template parameter T,I have tried many ways but can't solve it .

Base class as a template parameter is must

I have simplified the source code, but these conditions I describe are necessary.

Now I hope that under these conditions I describe, I can call the interface() sucessfully

Does anyone know where the problem is and how to fix it?

dimanche 19 juin 2022

Occasional SEGFAULT in my c++ code with flatbuffers

I'm working on my C++ project with flatbuffers. I started with google's online example and wrote a google test. However, this test sometimes failed with SEGFAULT.

Following are the code snippets.

// moster.fbs

namespace MyGame.Sample;

enum Color:byte { Red = 0, Green, Blue = 2 }

union Equipment { Weapon } // Optionally add more tables.

struct Vec3 {
  x:float;
  y:float;
  z:float;
}

table Monster {
  pos:Vec3; // Struct.
  mana:short = 150;
  hp:short = 100;
  name:string;
  friendly:bool = false (deprecated);
  inventory:[ubyte];  // Vector of scalars.
  color:Color = Blue; // Enum.
  weapons:[Weapon];   // Vector of tables.
  equipped:Equipment; // Union.
  path:[Vec3];        // Vector of structs.
}

table Weapon {
  name:string;
  damage:short;
}

root_type Monster;
// test.cpp
#include <fstream>
#include <string>

#include "gtest/gtest.h"
#include "monster_generated.h"

using namespace MyGame::Sample;

void WriteMonsterToFile(const std::string& filename)
{
  // Build up a serialized buffer algorithmically:
  flatbuffers::FlatBufferBuilder builder;

  // First, lets serialize some weapons for the Monster: A 'sword' and an 'axe'.
  auto weapon_one_name = builder.CreateString("Sword");
  short weapon_one_damage = 3;

  auto weapon_two_name = builder.CreateString("Axe");
  short weapon_two_damage = 5;

  // Use the `CreateWeapon` shortcut to create Weapons with all fields set.
  auto sword = CreateWeapon(builder, weapon_one_name, weapon_one_damage);
  auto axe = CreateWeapon(builder, weapon_two_name, weapon_two_damage);

  // Create a FlatBuffer's `vector` from the `std::vector`.
  std::vector<flatbuffers::Offset<Weapon>> weapons_vector;
  weapons_vector.push_back(sword);
  weapons_vector.push_back(axe);
  auto weapons = builder.CreateVector(weapons_vector);

  // Second, serialize the rest of the objects needed by the Monster.
  auto position = Vec3(1.0f, 2.0f, 3.0f);

  auto name = builder.CreateString("MyMonster");

  unsigned char inv_data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
  auto inventory = builder.CreateVector(inv_data, 10);

  // Shortcut for creating monster with all fields set:
  auto orc = CreateMonster(builder, &position, 150, 80, name, inventory,
                           Color_Red, weapons, Equipment_Weapon, axe.Union());

  builder.Finish(orc);  // Serialize the root of the object.

  // We now have a FlatBuffer we can store on disk or send over a network.
  std::ofstream outfile(filename, std::ios::binary);
  outfile.write((char*)builder.GetBufferPointer(), builder.GetSize());
  outfile.flush();
  outfile.close();
}

TEST(FlatbuffersTest, Monster)
{
  WriteMonsterToFile("monster.bin");

  // ** file/network code goes here :) **
  std::ifstream infile;
  infile.open("monster.bin", std::ios::binary | std::ios::in);
  infile.seekg(0, std::ios::end);
  int length = infile.tellg();
  infile.seekg(0, std::ios::beg);
  char* data = new char[length];
  infile.read(data, length);
  infile.close();

  // Get access to the root:
  auto monster = GetMonster(data);
  delete[] data;

  // Get and test some scalar types from the FlatBuffer.
  EXPECT_EQ(monster->hp(), 80);
  EXPECT_EQ(monster->mana(), 150);
  EXPECT_EQ(monster->name()->str(), "MyMonster");

  // Get and test a field of the FlatBuffer's `struct`.
  auto pos = monster->pos();
  EXPECT_EQ(pos->z(), 3.0f);

  // Get a test an element from the `inventory` FlatBuffer's `vector`.
  auto inv = monster->inventory();
  EXPECT_EQ(inv->Get(9), 9);

  // Get and test the `weapons` FlatBuffers's `vector`.
  std::string expected_weapon_names[] = {"Sword", "Axe"};
  short expected_weapon_damages[] = {3, 5};
  auto weps = monster->weapons();
  for (unsigned int i = 0; i < weps->size(); i++) {
    EXPECT_EQ(weps->Get(i)->name()->str(), expected_weapon_names[i]);
    EXPECT_EQ(weps->Get(i)->damage(), expected_weapon_damages[i]);
  }

  // Get and test the `Equipment` union (`equipped` field).
  EXPECT_EQ(monster->equipped_type(), Equipment_Weapon);
  auto equipped = static_cast<const Weapon*>(monster->equipped());
  EXPECT_EQ(equipped->name()->str(), "Axe");
  EXPECT_EQ(equipped->damage(), 5);
}

test output:

$ ctest --rerun-failed --output-on-failure
Test project /root/cpcos/build_linux64
    Start 3: FlatbuffersTest.Monster
1/1 Test #3: FlatbuffersTest.Monster ..........***Exception: SegFault  0.01 sec
Running main() from /home/conan/w/BuildSingleReference/.conan/data/gtest/1.11.0/_/_/build/7320405f83ec32d8556b524cdda87ee295bb7b84/source_subfolder/googletest/src/gtest_main.cc
Note: Google Test filter = FlatbuffersTest.Monster
[==========] Running 1 test from 1 test suite.
[----------] Global test environment set-up.
[----------] 1 test from FlatbuffersTest
[ RUN      ] FlatbuffersTest.Monster
/root/cpcos/tests/flatbuffers_gtest.cpp:71: Failure
Expected equality of these values:
  monster->hp()
    Which is: 100
  80


0% tests passed, 1 tests failed out of 1

Total Test time (real) =   0.04 sec

The following tests FAILED:
          3 - FlatbuffersTest.Monster (SEGFAULT)
Errors while running CTest

I compiled the code and ran it many times, strangely, it sometimes PASS while sometimes failed with SEGFAULT.

What did I do wrong? Thanks.

Searching using Ifstream

I've been recently trying to write a contacts list
but I keep facing some problems (sorry for poor english btw)
here's my code:

class contact{
private:
  std::string name;
  long int number;
public:
  void append();
  void search();
};

void contact::append(){
    std::cin.ignore();
    std::ofstream cnt;
    cnt.open("contacts.dat", std::ofstream::app);
    std::cout<<"Please enter the name\n";
    std::getline(std::cin, name);
    cnt << "Name: " << name << std::endl;
    
    bool flag=true;
    while(flag){
    std::cout<< "Enter the number:\n";
    std::cin >> number;
    if(std::cin.good()){
    try{
      if(number == 0){
    throw number;
      }
      else{
    cnt << "number: +98" << number <<"\n\n";
    flag=false;
    break;
      }
    }
    catch (...){
      std::cout<<"Unvalid entry\n\a";
    }
    }
    else{
      std::cout<<"unvalid entry, please enter an integer\a"<<std::endl;
      std::cin.clear();
      std::cin.ignore(10000, '\n');
    }
    }
    std::cout<<"Added Successfully";
      cnt.close();
}

void contact::search(){
  std::cin.ignore();
  std::ifstream sr;
  sr.open("contacts.dat");
  std::string search_name;
  bool found = false;
  std::cout<<"Enter a name for finding its phone number\n";
  std::getline(std::cin, search_name);
  while(sr>>number){
    sr>>name;
    if(name == search_name){
      std::cout<<"Name: "<<name<<std::endl;
      std::cout<<"Number: "<<number<<std::endl;
      found=true;
      break;
    }
  }
 if (found==false){
    std::cout<<search_name<<" not found";
  }
  sr.close();
}

int main(){
  contact cont;
  int choice;
     while (1) {
    std::cout << "Enter Your Choice\n";
    std::cout << "\t1. Add contact \n";
    std::cout << "\t2. Find contacts \n";
    std::cin >> choice;

    switch(choice){
    case 1:
      cont.append();
      break;
    case 2:{
      cont.search();
      }
    default:
      std::cout<<"\ninvalid Choice\n\a";
    }
     }
}

I already added some contacts to contacts.dat via the program.

contacts.dat:

Name: john
Number: +98911111111
Name: joe
Number: +98914523525
Name: example
Number: +98954645236

but when I try to run the code:

Enter Your Choice
        1. Add contact
        2. Display Contacts
2
Enter a name for finding its phone number
john
john not found

why is my custom UnorderedMap container iterator not working?

I am making my own hash map container for my school project and I cant get my iterators to work. This is what my container looks like:

#include <cstddef>
#include <list>
#include <string>
#include <utility>
#include <vector>

template<typename T, typename F>
class UnorderedMap {
  public:
  using key_type = T;
  using mapped_type = F;
  using value_type = std::pair<key_type, mapped_type>;
  using bucket_type = std::list<value_type>;

  UnorderedMap() {
    storage_.resize(storage_size_);
  }

  size_t hash(std::string word) {
    size_t sum = 5381;
    for(char c : word)
      sum = (sum << 4) + c;
    return sum % storage_size_;
  }

  void emplace(const key_type& key, mapped_type value) {
    size_t index = hash(key);
    auto& bucket = storage_[index];
    bucket.push_back(value_type(key, std::move(value)));
  }

  mapped_type& operator[](const key_type& key) {
    auto index = hash(key);
    auto& bucket = storage_[index];
    for(auto& e : bucket) {
      if(e.first == key) {
        return e.second;
      }
    }
    mapped_type temp;
    bucket.push_back(value_type(key, std::move(temp)));
    return bucket.back().second;
  }

  class iterator : public std::iterator<std::random_access_iterator_tag, value_type> {
    public:
    iterator(value_type* p) : p_{p} {} 

    private:
    value_type* p_;
  };

  iterator begin() {
    for(auto& e : storage_) {
      if(!e.empty())
        return e.front();
    }
  }

  iterator& end() {
  }

  private:
  std::vector<bucket_type> storage_;
  size_t storage_size_ = 1000;
};

The problem is with iterator begin(). It say that it can't convert e.front() to an iterator. Everything else is working fine.

samedi 18 juin 2022

Eigen replace first row in matrix error: mismatched types ‘const Eigen::ArrayBase

Trying to replace the first row of a matrix with some expression, similar to my MATLAB code:

%Matrix A defined and Ny

A(1,:)    = (-1).^(1:Ny+1).*(0:Ny).^2;
A(Ny+1,:) = (0:Ny).^2;

The C++ code I wrote is:

    static const int ny = 10; 

    Eigen::VectorXd i = VectorXd(ny+1); 
    std::iota(i.begin(), i.end(), 0);

//matrix A is also defined correctly here

    A.row(0) = pow(-1,(i))*(pow(i,2)); //error here
    std::cout << A.row(0) << "\n";  

can I get this done without having to rewrite it in a for loop, I am guessing that would require me changing the initialization of i

The full error message:

Test.cpp:329:25: error: no matching function for call to ‘pow(int, Eigen::VectorXd&)’
  329 |  dv1.row(0) = pow(-1,(a))*(pow(a,2));
      |     ^~~
/usr/include/c++/9/complex:1885:5: note:   template argument deduction/substitution failed:
Test.cpp:329:25: note:   ‘Eigen::VectorXd’ {aka ‘Eigen::Matrix<double, -1, 1>’} is not derived from ‘const std::complex<_Up>’
  329 |  dv1.row(0) = pow(-1,(a))*(pow(a,2));

/mnt/c/Users/J/Documents/eigen-3.4.0/eigen-3.4.0/Eigen/src/Core/GlobalFunctions.h:175:3: note:   template argument deduction/substitution failed:
Test.cpp:329:35: note:   mismatched types ‘const Eigen::ArrayBase<ExponentDerived>’ and ‘int’
  329 |  dv1.row(0) = pow(-1,(a))*(pow(a,2));

And it keeps repeating similar errors. I tried initializing i with Eigen::Matrix< double, 1, ny+1> instead but I get the same error. %%%%%%%%%%%%%%%%%%%%% Edit: Currently I have this C++ code working, but I would like to make use of the operators .row() and .col() :


    for (int i = 0; i < ny+1; i++){
        for (int j = 0; j < ny+1; j++){
        A(0,j) = -1. * pow(-1,(j))*(pow(j,2));
        A((ny),j) =  1. * pow(j,2);
        }
    }
    std::cout << A << "\n";

This replaces the first and last rows of the matrix A

Convert Forward Iterator to Input Iterator [closed]

I'm trying to get the distance of a partition point from beginning of the container. The below code demonstrate the issue which I'm facing:

#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
    std::vector<std::string> num_names { "one", "two", "six", "ten", "four", 
                    "five", "nine", "three", "seven", "eight"};
    auto partition_checker = [](auto s) { return s.size() == 3; };

    if(std::is_partitioned(num_names.cbegin(), num_names.cend(), partition_checker)) {
        std::cout << "num_names is partitioned." << std::endl;

        // Get the distance of partition point
        auto pos = std::partition_point(num_names.cbegin(), num_names.cend(), partition_checker);
        std::cout << "First string with size > 3: " << *pos
                  << " at " << std::distance(num_names.begin(), pos) + 1 << " from begining" << std::endl;
    } else {
        std::cout << "num_names is not partitioned" << std::endl;
    }
}

For the above code I get a compilation error:

 error: no matching function for call to 'distance(std::vector<std::__cxx11::basic_string<char> >::iterator, __gnu_cxx::__normal_iterator<const std::__cxx11::basic_string<char>*, std::vector<std::__cxx11::basic_string<char> > >&)'
                   << " at " << std::distance(num_names.begin(), pos) + 1 << std::endl;

partition_point algorithm returns a ForwardIterator while distance algorithm expect an InputIterator.

How can I get the distance using the iterator returned by partition_point?

strcmp() function not working fot the word "university"

So in this small project for my school I needed to build a word guessing game everything works fine except the string university which always gives output incorrect, I tried changing it to universit and it works but university doesn't work. I cant figure out what the problem is.

Also are there any other alternatives to strcmp()?

#include<iostream>
#include<string.h>
#include<stdlib.h>
#include<time.h>
using namespace std;
int main()
{   //at first we are basically going to give an intro to the gameseco
    cout << "   HANGMAN : GUESS THE WORD AND NOT DIE!!\n\n\n"; 

    cout << "   Welcome to the game player!!\n\n";
    cout << "   Rules: Guess the word by typing a letter based on given hints.\n";
    cout << "                  Multiple incorrect guesses will HANG YOU.\n\n";
    
    //here we add different words in the game for the guessing system using a 2 dimensional 
array
    char word[20][20]={"higher", "secondary", "first", "year", "cotton", "university" , "computer" , "science", "project", "hangman",};

    char newword[20], guess[10];
    bool again = 1;


    while(again == 1) {

        again = 0;
        srand(time(0));
        int x=0, wrong=0, z = (rand() % 10) + 0;
        strcpy(newword, word[z]); //so we used strcpy command to copy an element of the 2D array of randomly generated index to a new string


        cout << "Enter your guess. \nHINT: Word Length(indicated by underscores) = "; //hint no. one the gives us the exact lenth of word


        for(x=0; newword[x]!='\0'; x++){
            cout<< "-";
        }
        cout << "\nWord starts with: '" << newword[0] << "'";  //hint no. two which gives the player an idea what the word might be


        cout << "\n\n";


        for(wrong=1; wrong<=6; wrong++) //the loop here checks whether the input given by the user is correct or not
    {
            cin >> guess; // the input is taken here

            if(strcmp(guess , newword) == 0) //the input is compared with the word to be guessed 
            {                               //using the strcmp() function from the string.h library

            
                cout << "Correct!\n";       //if the guess is correct the program will print correct and correct and end

                break;                      //correct guess will terminate the loop

            }else if(wrong==1)
            {
                cout << "Opps! Wrong guess!\n\n";   //if player inputs wrong word a poll will appear for hanging the person

                cout << "I=-=\n";
                cout << "|\n";
                cout << "|\n";
                cout << "|\n";
                cout << "|\n";
                cout << "I\n";
            }else if(wrong==2)
            {
                cout << "Opps! Wrong guess again!\n\n";  //each wrong word will result in the appearance of of a hanging person

                cout << "I=-=\n";
                cout << "|  |\n";
                cout << "|\n";
                cout << "|\n";
                cout << "|\n";
                cout << "I\n";
            }else if(wrong==3)
            {
                cout << "Opps! Wrong guess again!\n\n";

                cout << "I=-=\n";
                cout << "|  |\n";
                cout << "|  O\n";
                cout << "|\n";
                cout << "|\n";
                cout << "I\n";
            }else if(wrong==4)
            {
                cout << "Opps! Wrong guess again!\n\n";

                cout << "I=-=\n";
                cout << "|  |\n";
                cout << "|  O\n";
                cout << "I--|--\n";
                cout << "|\n";
                cout << "I\n";
            }else if(wrong==5)
            {
                cout << "Opps! Wrong guess again!\n\n";

                cout << "I=-=\n";
                cout << "|  |\n";
                cout << "|  O\n";
                cout << "I--|--\n";
                cout << "|  o\n";
                cout << "I\n";
            }else if(wrong==6)
            {
                cout << "Opps! Wrong guess again!\nLast Chance!!\n\n";  //unfortunately the player couldn't guess the word

                cout << "I=-=\n";
                cout << "|  |\n";
                cout << "|  O\n";       //the hanging person compeletely appears and the program ends
                cout << "|--|--\n";
                cout << "|  o\n";
                cout << "I | |\n";
                cout << "YOU ARE DEAD HAHAHA!!!";
            }
        }
        cout << "Do you want to play again?\nPress 1 for yes, 0 for no."; //here it is asked if we want to play again

        cin >> again;
    }
    return 0;
}
    

C++ Classes: Member variables not updating when using a vector of objects [duplicate]

I have declared a vector array of objects called bn of class Particle. For testing purposes, I started with one object-element in the array.

Class member functions:

void Particle::p(float pos_x, float pos_y, float mass)
{
    m = mass;
    x = pos_x;
    y = pos_y;
    velx = 0;
    vely = 0;
    radius = calc_rad();
}
float Particle::calc_rad()
{
    radius = 10 * cbrt(m / density);

    return radius;
}
void Particle::move(float t)
{
    x += velx * t;
    y += vely * t;
}

Class declaration:

class Particle
{
public:
    float m;
    float x;
    float y;
    float velx;
    float vely;
    float radius;
    float density = 100;

    void p(float pos_x, float pos_y, float mass);
    float calc_rad();
    void move(float t);
};

main():

int main()
{   
    std::vector <Particle> bn(1);
    
    bn[0].p(500, 500, 1);
    
    float t = 1;
    int it = 0;

    for(int j = 0; j < 10; j++)
    { 
        for (Particle i : bn)
        {   
            i.velx = 1;
            i.vely = 1;
            i.move(t);
            std::cout << i.x << std::endl;
        }
        
    }
}

I want to update the member variables x and y of objects in bn. But the values are not changing. I tried declaring a single object without any vectors and it works fine. But I need an array of objects. Can someone tell me what the issue is or whether I'm missing something?

vendredi 17 juin 2022

How to convert for loop matrix multiplication using Eigen C++: incorrect results

I have the following for loop that works:

    static const int ny = 10; 
    std::vector<double> ygl(ny+1);

    double *dVGL; 
    dVGL = (double*) fftw_malloc(((ny+1)*(ny+1))*sizeof(double));
    memset(dVGL, 42, ((ny+1)*(ny+1))* sizeof(double));
    double *dummy1; 
    dummy1 = (double*) fftw_malloc(((ny+1)*(ny+1))*sizeof(double));
    memset(dummy1, 42, ((ny+1)*(ny+1))* sizeof(double));

    double *dummy2; 
    dummy2 = (double*) fftw_malloc(((ny+1)*(ny+1))*sizeof(double));
    memset(dummy2, 42, ((ny+1)*(ny+1))* sizeof(double));

    for (int i = 0; i < ny+1; i++){
        for (int j = 0; j < ny+1; j++){
            ygl[j] = -1. * cos(((j) * EIGEN_PI )/ny);
            dummy1[j + ny*i] =  1./(sqrt(1-pow(ygl[j],2))); 
            dummy2[j + ny*i] = 1. * (i);
            dVGL[j + ny*i] =  dummy1[j + ny*i] * sin(acos(ygl[j]) * (i)) * dummy2[j + ny*i];
        
        }
    }

The above works fine, now I convert to Eigen and I am getting off results:

    Eigen::Matrix< double, 1, ny+1> v1; 
    v1.setZero();
    std::iota(v1.begin(), v1.end(), 0);

    Eigen::Matrix< double, ny+1, ny+1> dummy1; 
    dummy1.setZero();

    Eigen::Matrix< double, ny+1, ny+1> dummy2; 
    dummy2.setZero();

for (int j = 0; j < ny+1; j++){
            v[j] = 1./(sqrt(1-pow(ygl[j],2)));
    }
    dummy1 = v.array().matrix().asDiagonal(); //this is correct
    dummy2 = v1.array().matrix().asDiagonal(); //this is correct

    Eigen::Matrix< double, ny+1, ny+1> dVGL; 
    dVGL.setZero();
for (int i = 0; i < ny+1; i++){
        for (int j = 0; j < ny+1; j++){
            ygl[j] = -1. * cos(((j) * EIGEN_PI )/ny);
            dVGL(j + ny*i) =   sin(acos(ygl[j]) * (i)); //this is correct
        }
    }
//##################################
dv1 = (dummy1) * (dVGL) * (dummy2); //this is incorrect, dVGL outside for loop is different from inside for loop!!
  

I have been wracking my brain for a week now over this I cannot seem to fix it. why is dVGL out side the for loop is different?? (off as if my rows and columns have length ny+1, but When I flatten my array I am using just ny.) why is that?

I feel like this should be a simple issue.

Getting error while trying to work with a multiset of pairs

I have no idea what is wrong and how to correct it. Here is the code:

#include<bits/stdc++.h>
using namespace std;

struct dashboard {

int sum = 0;
double count = 0;
int sumsq = 0;

//median
multiset<int, int> smaller, larger;

//mode
map<int, int> mp;
multiset<pair<int, int>> mt;

void balance()
{
    if(smaller.size()<larger.size())
    {
        int x = (*larger.begin());
        smaller.insert(x);
        larger.erase(larger.find(x));
    }

    if(larger.size()+1<smaller.size())
    {
        int x = (*smaller.rbegin());
        smaller.insert(x);
        smaller.erase(smaller.find(x));
    }
}

void insert(int x)
{
    //mean
    sum+=x;
    count++;

    //var
    sumsq+=x*x;

    //median
    if(smaller.empty())
    {
        smaller.insert(x);
    }
    else if(x <= (*smaller.rbegin()))
    {
        smaller.insert(x);
    }
    else 
    {
        larger.insert(x);
    }

    balance();

    //mode
    //if it is already present in the multiset
    if((mt.find( make_pair(mp[x], x))) != mt.end()){
        mt.erase( mt.find( make_pair(mp[x], x)));
    }
    mp[x]++;
    mt.insert( make_pair(mp[x],x));
}

void remove(int x)
{
    //mean
    sum-=x;
    count--;

    //var
    sumsq-=x*x;

    //median
    if(larger.find(x) != larger.end())
    {
        larger.erase(larger.find(x));
    }
    else
    {
        smaller.erase(smaller.find(x));
    }

    balance();

    //mode
    if(mt.find({mp[x],x}) != mt.end())
    {
        mt.erase(mt.find(make_pair(mp[x],x)));
    }
    mp[x]--;
    if(mp[x]>0) mt.insert(make_pair(mp[x], x));
}

double mean()
{
    return sum/count;
}

double var()
{
    return (sumsq/count) - (mean()*mean());
}

double median()
{
    if(smaller.size()==larger.size())
    {
        return ((*smaller.rbegin())+ (*larger.begin()))/2.0;
    }
    else 
    {
        return (*smaller.rbegin());
    }

}

int mode()
{
    return mt.rbegin()->second;
}

};

int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);

dashboard d;
d.insert(1);
d.insert(2);
d.insert(4);

return 0;
}

The error that I am getting is this :

In instantiation of ‘std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::find(const _Key&) [with _Key = int; _Val = int; _KeyOfValue = std::_Identity; _Compare = int; _Alloc = std::allocator; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator = std::_Rb_tree_iterator]’: /usr/include/c++/9/bits/stl_multiset.h:776:29: required from ‘std::multiset<_Key, _Compare, _Alloc>::iterator std::multiset<_Key, _Compare, _Alloc>::find(const key_type&) [with _Key = int; _Compare = int; _Alloc = std::allocator; std::multiset<_Key, _Compare, _Alloc>::iterator = std::_Rb_tree_const_iterator; std::multiset<_Key, _Compare, _Alloc>::key_type = int]’ main.cpp:35:30: required from here /usr/include/c++/9/bits/stl_tree.h:2564:8: error: expression cannot be used as a function 2563 | return (__j == end() | ~~~~~~~~~~~~~ 2564 | || _M_impl._M_key_compare(__k, | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 2565 | _S_key(__j._M_node))) ? end() : __j; | ~~~~~~~~~~~~~~~~~~~~~ /usr/include/c++/9/bits/stl_tree.h: In instantiation of ‘std::pair<std::_Rb_tree_node_base*, std::_Rb_tree_node_base*> std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_get_insert_equal_pos(const key_type&) [with _Key = int; _Val = int; _KeyOfValue = std::_Identity; _Compare = int; _Alloc = std::allocator; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::key_type = int]’: /usr/include/c++/9/bits/stl_tree.h:2180:4: required from ‘std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_insert_equal(_Arg&&) [with _Arg = const int&; _Key = int; _Val = int; _KeyOfValue = std::_Identity; _Compare = int; _Alloc = std::allocator; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator = std::_Rb_tree_iterator]’ /usr/include/c++/9/bits/stl_multiset.h:503:40: required from ‘std::multiset<_Key, _Compare, _Alloc>::iterator std::multiset<_Key, _Compare, _Alloc>::insert(const value_type&) [with _Key = int; _Compare = int; _Alloc = std::allocator; std::multiset<_Key, _Compare, _Alloc>::iterator = std::_Rb_tree_const_iterator; std::multiset<_Key, _Compare, _Alloc>::value_type = int]’ main.cpp:34:20: required from here /usr/include/c++/9/bits/stl_tree.h:2131:51: error: expression cannot be used as a function 2131 | __x = _M_impl._M_key_compare(__k, _S_key(__x)) ? /usr/include/c++/9/bits/stl_tree.h: In instantiation of ‘std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::M_insert(std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Base_ptr, std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Base_ptr, _Arg&&, _NodeGen&) [with _Arg = const int&; _NodeGen = std::_Rb_tree<int, int, std::_Identity, int, std::allocator >::_Alloc_node; _Key = int; _Val = int; _KeyOfValue = std::_Identity; _Compare = int; _Alloc = std::allocator; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator = std::_Rb_tree_iterator; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Base_ptr = std::_Rb_tree_node_base*]’: /usr/include/c++/9/bits/stl_tree.h:2183:37: required from ‘std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_insert_equal(_Arg&&) [with _Arg = const int&; _Key = int; _Val = int; _KeyOfValue = std::_Identity; _Compare = int; _Alloc = std::allocator; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator = std::_Rb_tree_iterator]’ /usr/include/c++/9/bits/stl_multiset.h:503:40: required from ‘std::multiset<_Key, _Compare, _Alloc>::iterator std::multiset<_Key, _Compare, _Alloc>::insert(const value_type&) [with _Key = int; _Compare = int; _Alloc = std::allocator; std::multiset<_Key, _Compare, _Alloc>::iterator = std::_Rb_tree_const_iterator; std::multiset<_Key, _Compare, _Alloc>::value_type = int]’ main.cpp:34:20: required from here /usr/include/c++/9/bits/stl_tree.h:1812:10: error: expression cannot be used as a function 1811 | bool __insert_left = (__x != 0 || __p == _M_end() | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1812 | || _M_impl._M_key_compare(_KeyOfValue()(__v), | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1813 | _S_key(__p))); | ~~~~~~~~~~~~~ /usr/include/c++/9/bits/stl_tree.h: In instantiation of ‘std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_lower_bound(std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Link_type, std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Base_ptr, const _Key&) [with _Key = int; _Val = int; _KeyOfValue = std::_Identity; _Compare = int; _Alloc = std::allocator; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator = std::_Rb_tree_iterator; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Link_type = std::_Rb_tree_node; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Base_ptr = std::_Rb_tree_node_base]’: /usr/include/c++/9/bits/stl_tree.h:2562:16: required from ‘std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::find(const _Key&) [with _Key = int; _Val = int; _KeyOfValue = std::_Identity; _Compare = int; _Alloc = std::allocator; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator = std::_Rb_tree_iterator]’ /usr/include/c++/9/bits/stl_multiset.h:776:29: required from ‘std::multiset<_Key, _Compare, _Alloc>::iterator std::multiset<_Key, _Compare, _Alloc>::find(const key_type&) [with _Key = int; _Compare = int; _Alloc = std::allocator; std::multiset<_Key, _Compare, _Alloc>::iterator = std::_Rb_tree_const_iterator; std::multiset<_Key, _Compare, _Alloc>::key_type = int]’ main.cpp:35:30: required from here /usr/include/c++/9/bits/stl_tree.h:1934:6: error: expression cannot be used as a function 1934 | if (!_M_impl._M_key_compare(_S_key(__x), __k)) /usr/include/c++/9/bits/stl_tree.h: In instantiation of ‘static const _Key& std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_S_key(std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Const_Link_type) [with _Key = int; _Val = int; _KeyOfValue = std::_Identity; _Compare = int; _Alloc = std::allocator; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Const_Link_type = const std::_Rb_tree_node]’: /usr/include/c++/9/bits/stl_tree.h:2131:44: required from ‘std::pair<std::_Rb_tree_node_base, std::_Rb_tree_node_base*> std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_get_insert_equal_pos(const key_type&) [with _Key = int; _Val = int; _KeyOfValue = std::_Identity; _Compare = int; _Alloc = std::allocator; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::key_type = int]’ /usr/include/c++/9/bits/stl_tree.h:2180:4: required from ‘std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_insert_equal(_Arg&&) [with _Arg = const int&; _Key = int; _Val = int; _KeyOfValue = std::_Identity; _Compare = int; _Alloc = std::allocator; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator = std::_Rb_tree_iterator]’ /usr/include/c++/9/bits/stl_multiset.h:503:40: required from ‘std::multiset<_Key, _Compare, _Alloc>::iterator std::multiset<_Key, _Compare, _Alloc>::insert(const value_type&) [with _Key = int; _Compare = int; _Alloc = std::allocator; std::multiset<_Key, _Compare, _Alloc>::iterator = std::_Rb_tree_const_iterator; std::multiset<_Key, _Compare, _Alloc>::value_type = int]’ main.cpp:34:20: required from here /usr/include/c++/9/bits/stl_tree.h:777:16: error: static assertion failed: comparison object must be invocable with two arguments of key type 777 | static_assert(__is_invocable<_Compare&, const _Key&, const _Key&>{},