samedi 29 février 2020

Execution order of map[K] = V [duplicate]

Give the following C++ code.

std::map<std::pair<int, int>, int> map;
int test = 0;
map[std::make_pair(test, 2)] = ++test;

The contents of map becomes to (1,2) -> 1. Why not (0, 2) -> 1? Can anyone explain the order of execution in this scenario?

How can i link the vector elements to a pointer

I need help in the class design workflow with the following functionality.

I have a class with the name of Stage the stage has a variable of class Director as vector and i would want to point to these data elements of the vector from another class Channel.

class Stage
{
private:
    int time;
    std::vector<Director> directors;
public:
    Stage()
    { }
    void AddDirector(Director director)
    {
        directors.push_back(director);
    }    
    Director* GetDirector(int index)
    {
        return &directors[index];
    }    
    void DeleteDirector(std::string dirName)
    {
        // remove the director from the vector which matches the name of the input string
    } 
};

////////////////////////////////////////////////////////////////////////////////////////////////

class Director
{
private:
    int time;
    std::string stdstrDirName;
public:
    Director()
    { }
    std::string GetName()
    {
        return stdstrDirName;
    }
    void SetName(std::string name)
    {
        stdstrDirName = name;
    }

   // GetTime and SetTime

};




 class Channel
{
private:
    int time;
    std::string stdstrChannelName;
    Director* dir;
public:
    Channel()
    { }
    std::string GetName()
    {
        return stdstrChannelName;
    }
    void SetName(std::string name)
    {
        stdstrChannelName = name;
    }

    std::string  GetDirectorName()
    {
        dir->GetName();
    }

    void SetDirector(Director* director)
    {
        dir = director;
    }

};

This is how i would point them.

int main()
{
    Stage stage;  // Create Stage Object
    Director d1, d2, d3; // Create Director Objects
    Channel channel;
    d1.SetName("D1"); d2.SetName("D2"); d3.SetName("D3");
    stage.AddDirector(d1); stage.AddDirector(d2); stage.AddDirector(d3);
    channel.SetDirector(stage.GetDirector(1)); // Link Director to Channel
}

This approach has a drawback whenever the vector gets resize the pointers in the Channel will not hold reference to their valid object.

I need help in what should be the design of the class structure ?

Is it OK to use global variables when they are only used in one file? Are const/constexpr global variables generally considered OK to use?

I understand that global variables should be avoided whenever possible for a few reasons:

  1. It's hard to debug if a global variable has an invalid value (since every function has access to it)

  2. For multiple global variables over multiple files, if there are any dependencies on the global variables (e.g., if you have a = 1; in one file, and extern a; b = a + 1; in another file), the values of these variables will be undefined since we can't know the order of evaluation of these expressions.

Are const or constexpr global variables generally ok to use? Since they can't be ever be written to, they aren't ever affected by the first point, and constexpr global variables are evaluated before runtime by the compiler, so the second point doesn't apply to them. Also, if you only use const variables in the file they are defined in, the second point won't apply to them either.

Also, there are probably some situations where using non-const global variables is really convenient. Assuming they are only used in one file so the order of evaluation of translation units won't matter, is it worth it to use a small amount of global variables when they really simplify your code? (e.g., you won't have to keep passing local variables by reference to various functions from main).

Creating Thread Group in c++ in 2020?

When i read a source code from 2011 in c,

The programmer used to create thread group before creating the threads,

Now i read that thread group are no longer needed in java , Is c/c++ the same as creating thread group no longer needed? What was the benefit of it , if not needed those days

How to link pointer to a std::vector element

I want to link a pointer to one of the data member of an std vector.

int main()
{
    std::vector<int> vec;
    vec.push_back(1);
    vec.push_back(2);
    vec.push_back(3);
    vec.push_back(4);
    vec.push_back(5);
    int *ip = &vec[2];
    std::cout << *ip << std::endl;
    vec.erase(vec.begin() + 1); 
    std::cout << *ip << std::endl;
    while (!_kbhit())
    {


    }
    std::cout << "Hello World!\n"; 
}

The issue which i am facing is that whenever i delete a data element from the vector the pointer than points to another data member.

How can i make a pointer to point at the same data member even after the vector resizes ?

How to free memory from front end c++

How to delete memory from a front end application allocated by a library and we don't know whether the memory is allocated using "new" or "malloc" ?

why initialize reference succeeds with one constructor but not the other

Our code was using something like below, to pass a const string reference:

const char& str = // passed in;
const std::string& sym(str);

Then I need to fix it for take symbol only as the first 5 chars, I did:

const std::string& sym(str, 5);

but this throws me this compiling error:

error: expression list treated as compound expression in initializer [-fpermissive]

Why can I invoke the first constructor, but no the second one?

How to wrap an object and its member functions with c++

I'm developing a c++ class to wrap an object and its member functions. As the object may be changed, so I'm thinking if it is possible to use some mechanism to do so, such as template. Here is an example:

class ObjectA
{
public:
    void funcA1(double);
    void funcA2(int, char);
private:
    int value;
};

class ObjectB
{
public:
    void funcB1(double);
    void funcB2(int, char);
private:
    int value;
    float point;
};

Now I need to develop a class, which can easily wrap the ObjectA or the ObjectB. It is for sure that ObjectA and ObjectB don't inherit any parent class and they must have two functions, the names of functions are not the same but the parameters must be the same, just like funcA1 funcB1 and funcA2 funcB2.

I'm thinking the code as below should work.

template<typename T, typename funcAT, typename funcBT> // T: Object, funcAT: Object::funcA, funcBT: Object::funcB
class Wrapper
{
    // ...
};

Well, if the code works, is there some method to make more constraint? For example, how to make sure that funcAT must belong to the T, instead of other functions? how to make sure that funcAT must have only one parameter double, instead of other cases?

What I mean is:

ObjectA objA;
Wrapper<objA, objA::funcA1, objA::funcB1> wrapper; // no error
Wrapper<objA, other_funcA, other_funcB> wrapper; // ERROR

vendredi 28 février 2020

UINT32_T - values are getting changed

We have an embedded product in which we make use of small OS - it has its own header file where below is the declation for uint32_t in it's own header file:

#define ui32    unsigned int

While we have also added socket libraries where we have below declarations:

struct in_addr
{
  in_addr_t s_addr;     /* IPv4 address */
};

where

#define in_addr_t   uint32_t

Defined in stdint.h C++ library header file -

typedef unsigned int       uint32_t;

The problem I am facing is then when I assign value if uint32_t to ui32 I see some values getting changed:

struct in_addr ipl_addr;
.. assign some value ..

ui32 addr = ip_addr.s_addr
callme(addr)

When I debug the code I find that if the value of ip_addr.s_addr is 3456346304 in callme function the argument value is 65193 - however printing the value in the function of ui32 variable gives me 3456346304 but when used in if conditional statements I can see its value as 65193

Printing the sizeof both types is 4 - how the value getting changes and how can I protect the same - what compiler options we should use to error during compilation in such issues?

Passing move-only objects as r-value reference parameters vs no-reference parameters - what is the difference?

Move-only objects can be passed into functions as r-value reference parameters and as regular no-reference parameters. What is the difference between these two cases?

See noRValueReference and rValueReference in the following example:

struct MoveOnly {
  MoveOnly() = default;
  MoveOnly(MoveOnly&&) = default;
  MoveOnly& operator=(MoveOnly&&) = default;
  MoveOnly(const MoveOnly&) = delete;
  MoveOnly& operator=(const MoveOnly&) = delete;
};

void noRValueReference(MoveOnly val) {}
void rValueReference(MoveOnly&& val) {}

int main() {
    MoveOnly a, b;
    noRValueReference(std::move(a));
    rValueReference(std::move(b));
}

Stoi is not a member of std [duplicate]

I'm working on a program where I'm using stoi to convert strings and getting the error in the title. I'm compiling using g++ version 7.3.0 on Ubuntu. The full line I'm entering to compile is g++ -c -std=c++11 -Wall -ansi -pedantic test.cpp Below I included a minimal version of my program that produces the same error.

test.cpp

#include <iostream>
#include <stdio.h>
#include <vector>
#include <fstream>
#include <string>

int main(){
   std::string string = "12"
   int num = std::stoi(string);   //this line causes error
   std::cout << num << std::endl;
}

error

test.cpp: In function `int main()`:
test.cpp:9:20: error: 'stoi' is not a member of 'std'
       int num = std::stoi(string);
                      ^~~~

I'm not sure what could cause this issue, I realize that some of the things i'm including at the top aren't necessary for this program but I just copied them from my actual program into this reproducible example in order to keep everything consistent. Could this be an issue where the compiler Isn't compiling with c++11? I thought the -std=c++11 flag would work but I'm relatively new at this so i could be wrong. Thanks in advance!

Different uses of noexcept

In the book The C++ Programming Language it is written that you can declare a function to be conditionally noexcept. For example:

template<typename T>
void my_fct(T& x) noexcept(std::is_pod<T>::value);

noexcept takes a predicate that must be a constant expression (in the example std::is_pod<T>::value).

However, in the book it is also written:

The noexcept() operator takes an expression as its argument and returns true if the compiler knows that it cannot throw and false otherwise.

Taking this into account, consider:

constexpr bool f() { return true; }

void g() noexcept(f())
{
    f();
}

Is g() marked as noexcept or not? I see two possibilities:

  1. The call f() is evaluated at compile-time because it is marked constexpr, it returns true and as a result g() is marked noexcept.
  2. The compiler cannot determine that f() cannot throw an exception because f() is not marked noexcept. As a result g() is not marked noexcept.

Which one does happen? How can I select one or other behavior for noexcept?

access to iterator in lambda function of an algorithm cause me segmentation fault

I need to sort a table by column. My tables are represents by a single vector.

example :

col_name A B C

vector : 1 2 3 6 5 4 7 8 9

that give me the table :

A B C

1 6 7
2 5 8
3 4 9

After a sort on column B , I need to obtain :

A B C

3 4 9
2 5 8
1 6 7

my code :

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

int main()
{

  std::vector<std::string> vec = {"1","8","1","2","3","2","3",
                                  "5","5","2","5","6","5","6",
                                  "9","3","3","4","8","3","9"};

  int size = 7;
  int col_idx = 1;


  for(int i = 0; i<3;++i)
    {
      if(i==col_idx)
        continue;

      std::sort(vec.begin() + i*size, vec.begin() + (i+1)*size,
                [col_idx, size, i](std::string& s1,std::string& s2)
                       {
                         std::cout << s1 << " "
                                   << s2 << " "
                                   << *(&s1 +(col_idx - i)*size) << " "
                                   << *(&s2 +(col_idx - i)*size) << " "
                                   << (*(&s1 +(col_idx - i)*size) < *(&s2 +(col_idx - i)*size)) << std::endl;
                         return *(&s1 +(col_idx - i)*size) < *(&s2 +(col_idx - i)*size);
                       });
    }
  std::sort(vec.begin() + col_idx*size, vec.begin() + (col_idx+1)*size);
}

I have a segmentation fault error : only the first line appear from the cout.

unodered_map is compiling fine but segfaults on execution

I am having difficulty in understanding why the below program is giving core dump on execution.

   #include <iostream>
   #include <unordered_map>
   using namespace std;
   int main()
   {
       std::unordered_map<int,int> hMap;
       return 0;
   }

There is no compilation warnings or errors but it gives core dump when I execute it. Is this issue related to the platform or compiler? Or am I missing something here?

I am compiling the code using below g++ command

g++ -g -Wall -Werror -std=c++11 -o file file.cpp

Platform is

Linux 3.10.0-1062.4.1.el7.x86_64 #1 SMP Wed Sep 25 09:42:57 EDT 2019 x86_64 x86_64 x86_64 GNU/Linux

Compiler :

gcc version 4.8.5 20150623 (Red Hat 4.8.5-39) (GCC)

On debugging I am getting the following stacktrace:

#0  0x0000000000601e30 in memset@@GLIBC_2.2.5 ()
#1  0x0000000000400fd4 in std::_Hashtable<int, std::pair<int const, int>, std::allocator<std::pair<int const, int> >, std::__detail::_Select1st, std::equal_to<int>, std::hash<int>, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, std::__detail::_Prime_rehash_policy, std::__detail::_Hashtable_traits<false, false, true> >::_M_allocate_buckets (
    this=0x7ffffffe8310, __n=11) at /usr/include/c++/4.8.2/bits/hashtable.h:780
#2  0x0000000000400db4 in std::_Hashtable<int, std::pair<int const, int>, std::allocator<std::pair<int const, int> >, std::__detail::_Select1st, std::equal_to<int>, std::hash<int>, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, std::__detail::_Prime_rehash_policy, std::__detail::_Hashtable_traits<false, false, true> >::_Hashtable (this=0x7ffffffe8310, 
    __bucket_hint=10, __h1=..., __h2=..., __h=..., __eq=..., __exk=..., __a=...) at /usr/include/c++/4.8.2/bits/hashtable.h:831
#3  0x0000000000400bc5 in std::_Hashtable<int, std::pair<int const, int>, std::allocator<std::pair<int const, int> >, std::__detail::_Select1st, std::equal_to<int>, std::hash<int>, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, std::---Type <return> to continue, or q <return> to quit---
__detail::_Prime_rehash_policy, std::__detail::_Hashtable_traits<false, false, true> >::_Hashtable (this=0x7ffffffe8310, 
    __n=10, __hf=..., __eql=..., __a=...) at /usr/include/c++/4.8.2/bits/hashtable.h:397
#4  0x0000000000400aff in std::unordered_map<int, int, std::hash<int>, std::equal_to<int>, std::allocator<std::pair<int const, int> > >::unordered_map (this=0x7ffffffe8310, __n=10, __hf=..., __eql=..., __a=...)
    at /usr/include/c++/4.8.2/bits/unordered_map.h:142

reference binding to null pointer of type 'int' (stl_iterator.h)

can someone help me to solve this error

Line 786: Char 17: runtime error: reference binding to null pointer of type 'int' (stl_iterator.h)

class Solution {
public:
    vector<int> findDisappearedNumbers(vector<int>& nums) {
        vector<int>result;
        sort(nums.begin(),nums.end());
        int p=1;
        int minel=*min_element(nums.begin(),nums.end());
        int maxa=*max_element(nums.begin(),nums.end());
        for(int64_t i=minel;i<=maxa;i++)
        {
            int c=count(nums.begin(),nums.end(),i);
            if(c==0)
            {
                result.push_back(i);
            }
        }
        return result;
    }
};

Custom strtoi function compile time issue

I am trying to implement a very simple strtoi function. It works fine when when the passed arguments are dynamically created (case 2 below). However if the char is created by char[] which is allocated during compile time, I get a constant value on len because of std::strlen(ch) which messes up my logic, and I can't find a solution for this.

 int strtoi(char* ch)
 {   
  int sum {0};
  int len = static_cast<int>(std::strlen(ch));
  int skipLast = static_cast<int>(static_cast<int>(ch[0]) == 45);

  //Integer Method
  for(int i = len - 1; i >= 0 + skipLast; i--)
  {
    if(static_cast<int>(ch[i]) < 48 || static_cast<int>(ch[i]) > 57)
      return 0;
    sum += (ch[i]-48) * std::pow(10,i-skipLast);
  }

   sum = skipLast == 1 ? -sum : sum;
   return sum;
 }

int main()
{
  char pos[3] {'1','2','3'};
  std::cout << strtoi(pos) << std::endl;
  char neg[4] {'-','1','2','3'};
  std::cout << strtoi(neg) << std::endl;
  return 0;
}

Returns: 0 and -123. The len variable in my function doesn't get the expected value for the first call and I assume it is because neg[4] allocates more memory then pos[3]. However, for the second case:

int main()
{
  char* pos;
  pos = new char[3] {'1','2','3'};
  std::cout << strtoi(pos) << std::endl;
  char* neg;
  neg = new char[4] {'-','1','2','3'};
  std::cout << strtoi(neg) << std::endl;
  return 0;
}

Returns 123, -123. The expected result. I guess this happens because in the first case the compiler is allocating memory for the function and its argument according to the char[4] array. Is this correct? How it work for the second case, how is the compiler allocating memory to the function for the dynamic variables? And what is a possible solution to make the function work for both cases? Thanks in advance for any help.

Why the static variable is not set to 1000 [duplicate]

I have a static variable in my class , which I instantiate in the cpp file to value 1000.

class Container
{
private: 
    static long GLOBALID;
    long MyID;
public:

    Container();
    long GetId();   
};

The code for cpp file.

long Container::GLOBALID = 1000;

Container::Container()
{
    MyID = GLOBALID++;

}

long Container::GetId()
{
    return MyID;
}

When I print the ID value of container objects, they keep incrementing.

My question is that when I create a new object I instantiate the static varible to value 0f 1000 so why does it keep incrementing with each object created?

jeudi 27 février 2020

C++ error: cannot convert ‘Graph

I am trying to make construct a graph using adjacency list. I have used template for the same. However, I am facing an error

I am assigning one variable (v_node *) to another of the same type. But this leads to an error. This might be happening to to the template < class T > that I used.

Please Suggest a solution.

Here is the code :

template < class T >
class Graph
{
    public:
        Graph()
        {
            h = NULL;
            H = NULL;
        }
        virtual ~Graph()
        {

        }
        void insertEdge(T, T)
        {
            struct v_node *a, *b, *c;
            struct e_node *tmp;
            c = H;
            if(c == NULL)
                return;
            while(c != NULL && c -> data != data1)
            {
                if(c == NULL)
                    break;
                c = c -> nxt;
            }
            if(c == NULL)
                return;
            a = c;
            c = H;
            while(c != NULL && c -> data != data2)
            {
                if(c == NULL)
                    return;
                c = c -> nxt;
            }
            if(c == NULL)
                return;
            b = c;
            if(a -> enode == NULL)
            {
                 a -> enode = new e_node;
                 tmp = a -> enode;
                 tmp -> vnode = b;
                 tmp -> nxt = NULL;
            }
            else
            {
                struct e_node *tmp = a -> enode;
                while(tmp -> nxt != NULL)
                {
                    tmp = tmp -> nxt;
                }
                tmp -> nxt = new e_node;
                tmp -> nxt -> nxt = NULL;
                tmp -> nxt -> vnode = b;
            }
            if(b -> enode == NULL)
            {
                 b -> enode = new e_node;
                 b -> enode -> vnode = a;
                 b -> enode -> nxt = NULL;
            }
            else
            {
                struct e_node *tmp = b -> enode;
                while(tmp -> nxt != NULL)
                {
                    tmp = tmp -> nxt;
                }
                tmp -> nxt = new e_node;
                tmp -> nxt -> nxt = NULL;
                tmp -> nxt -> vnode = a;
            }
        }
        void add(T)
        {
            if(H == NULL)
            {
                H = new v_node;
                H -> nxt = NULL;
                H -> enode = NULL;
                H -> data = data;
                return;
            }
            v_node *tmp = H;
            while(tmp -> nxt != NULL)
            {
                tmp = tmp -> nxt;
            }
            tmp -> nxt = new v_node;
            tmp -> nxt -> nxt = NULL;
            tmp -> nxt -> enode = NULL;
            tmp -> nxt -> data = data;
            return; 
        }
        void display()
        {
            struct v_node *p = H;
            struct e_node *q = NULL;
            while(p != NULL)
            {
                cout << p -> data << " : ";
                q = p -> enode;
                while(q != NULL)
                {
                    cout << q ->
                }
            }
        }
    private:
        struct e_node
        {
            struct v_node *vnode;
            struct e_node *nxt;
        }*h;
        struct v_node
        {
            struct v_node *nxt;
            struct e_node *enode;
            T data;
        }*H;
};

How to check whether two vectors have common elements without repeat?

Here is my function code fragment that checks whether two arrays have distinctly common elements and returns a new vector with those elements. However there is a run time error, I do not see it and cannot fix it. I learned how to use the unique function from here:

Checking for duplicates in a vector

vector<int> distinctCommonElements(vector<int>&x, vector<int>&y)
{
vector<int>z;

for(vector<int>::iterator itx=x.begin(); itx<x.end(); itx++)
{
    int ctr=0; 
    int memory=0;
    for(vector<int>::iterator ity=y.begin(); ity<=y.end(); ity++)
    {
        if(*itx==*ity&&ctr==0)
        {
            ctr++;
            z.push_back(*itx);
        }
    }
}
//inspiration from stack overflow and the c++ reference for unique algorithm
sort(z.begin(),z.end()); //sort due to the implementation of the unique algorithm
z.erase(unique(z.begin(),z.end()), z.end()); //unique checks adjacent elements, hence sort first, 
//hence answer always sorted
return z;

}

Error with lambda in template member function

I have the following c++ code

#include <iostream>

template<typename Func>
class Foo
{
private:
    Func func;

public:
    Foo(Func func) : func(func) {}

    template<typename T>
    Func wrap()
    {
        Func clbk = func;
        auto wrapperCB = [clbk](T t) {
            auto job = [clbk, t](){
                clbk(t);
            };
            job();
        };

        return wrapperCB;
    }

    template<typename T>
    void call(T t)
    {
        func(t);
    }
};

int main()
{
  int m = 2;
  auto f = [](int & p) {std::cout << "test success " << p << "\n";};
  auto obj = std::make_shared<Foo<std::function<void(int &)>>>(f);
  auto wrapper = obj->template wrap<int &>();
  wrapper(m);
  return 0;
}

This is giving compilation error

tsavs-mbp:p utsagarw$ clear; g++ -std=c++11 a.cpp -o z; ./z
a.cpp:18:17: error: no matching function for call to object of type 'const std::__1::function<void (int &)>'
                clbk(t);
                ^~~~
a.cpp:38:32: note: in instantiation of function template specialization 'Foo<std::__1::function<void (int &)> >::wrap<int &>' requested here
  auto wrapper = obj->template wrap<int &>();
                               ^
/Applications/Xcode_10.1/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/functional:1677:9: note: candidate function not viable: 1st argument ('const int') would lose const qualifier
    _Rp operator()(_ArgTypes...) const;
        ^
1 error generated.

I don't understand this error. Where did this const come from?

It is building successfully if in wrap I don't create job functor and call clbk directly. What is this job doing to type T?

template<typename T>
Func wrap()
{
    Func clbk = func;
    auto wrapperCB = [clbk](T t) {
        clbk(t);
    };

    return wrapperCB;
}

error: cannot convert 'std::__cxx11::basic_string

i've tried and fixed bt others comment at stackoverflow, but my program still not working properly

#include <iostream>
#include <windows.h>
#include <mysql.h> //header mysql
#include <sstream>
#include <cstring>
#include <algorithm>

using namespace std;

 int main()
{
int j, count = 0;
char del[] = ".,/;:";
string hadis, hadis1;
MYSQL* conn;
MYSQL_ROW row, row2;
MYSQL_RES* res, res2;
conn = mysql_init(0);
conn = mysql_real_connect(conn, "192.168.43.205", "ibrahim", "hadis", "hadis", 0, NULL, 0);
if(conn)
{
    //int qstate = mysql_query(conn, "SELECT NoHdt, Isi_Arab, Isi_Indonesia, Kategori, Perawi FROM malik ORDER BY id ASC");
    //int qstate = mysql_query(conn, "SELECT NoHdt, Isi_Indonesia FROM malik ORDER BY id ASC");
    int qstate = mysql_query(conn, "SELECT Isi_Indonesia FROM malik");
    if(!qstate)
    {
        res = mysql_store_result(conn);
        while(row = mysql_fetch_row(res))
        {
            hadis = row[0];
            for(unsigned int i=0;i<strlen(del);++i)
            {
                hadis.erase (remove(hadis.begin(), hadis.end(), del[i]), hadis.end());
            }
            for (j=0; hadis[j]; j++)
            {
                if (hadis[j] == ' ')
                {
                    count++;
                    cout<< "-";
                }
                hadis1 = hadis[j];
                cout<<hadis1;
            }
            cout<<"\n";
            int input = mysql_query(conn, "INSERT INTO totalkata_malik(kata,total) VALUES ('"+hadis1+"',1)");  //this is error
            }

        }
            cout<< "\n\nJumlah kata = "<<count+1<<"\n\n";
}

return 0;
}

and i've tried with this code

  std::string query = "INSERT INTO totalkata_malik(kata,total) VALUES 
  ('"+hadis1+"',1)";
        if (mysql_query(conn, query.c_str()))

these code is working and the compiler run well, but the result in my database wasn't suitable the result that i desire, i could input word by word as the result of splitting the string(data from database)

Non-negative integer?

I saw this word many times in competitive programming contest. why question setter doesn't use positive integer instead of non-negative integers.Please tell someone what's the reason ?

Operator overload for vector function c++

so I'm sure this question is super simple, I'm just quite new to programming and to C++ in general. So for my class was making a Vector with a class template. My professor has supplied the .h file and we have to write the integrated .cpp file. Heres the .h file:

#ifndef SIMPLEVECTOR_H
#define SIMPLEVECTOR_H
#include <iostream>
#include <new> // Needed for bad-alloc exception
#include <cstdlib> // Needed for the exit function
using namespace std;

template <class T>
class SimpleVector
 {
        private:
                T *aptr;                         // To point to the allocated array
                int arraysize;                   // Number of elements in the array
                void memError();                 // Handles memory allocation errors
                void subError();                 // Handles subscripts out of range


        public:
        SimpleVector()
                {
                aptr = 0;
                arraysize = 0;
                }
        SimpleVector(int s);
        SimpleVector(const SimpleVector & sv);
        ~SimpleVector();
        int size() const
                {
                return arraysize;
                }
        T getElementAt(int sub);
        T &operator[](const int);


};

#endif //SIMPLEVECTOR_H


//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
template <class T>
SimpleVector<T>::SimpleVector(int s)
{
        if(s<1)
        {
        arraysize=1;
        }
        else
        {
        arraysize=s;
        }

        try
        {
        aptr = new T [arraysize];
        }

        catch (bad_alloc)
        {
        memError();
        }

        for(int i=0;i<arraysize;i++)
        {
        aptr[i]=0;
        }
}

//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
template <class T>
void SimpleVector<T>::memError()
{

        cout<<"Error: cannot allocate memory."<<endl;
        exit(EXIT_FAILURE);

}
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
template <class T>
void SimpleVector<T>::memError()
{

        cout<<"Error: cannot allocate memory."<<endl;
        exit(EXIT_FAILURE);

}

//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
template <class T>
T SimpleVector<T>::getElementAt(int sub)
{
        return aptr[sub];
}

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

template <class T>
SimpleVector<T>::~SimpleVector()
{
        delete aptr;
}

//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
template <class T>
void SimpleVector<T>::subError()
{

        cout<<"Subscripts out of range."<<endl;
        exit(EXIT_FAILURE);

}
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

template <class T>
SimpleVector<T>::SimpleVector(const SimpleVector & sv)
{
        aptr=sv.aptr;
}

template <class T>
T<T>&::operator[](const int &)
{
        return aptr[];
}

I know that my overload operator is way off and makes no sense, I just dont understand the syntax well enough to even know where to begin. Obvisouly, the operator should return the value of the aptr at whatever index was passed in through []. Any help or insight would be amazing!

template declaration cannot appear at block scope

so this is for my class and, to be frank, I've never used templated before. Here is my simple vector.h file, but I keep the getting error that templates can not appear at block scope. My understanding of this is that indicates I'm attempting to define in it in a function. Here is my code:

#ifndef SIMPLEVECTOR_H
#define SIMPLEVECTOR_H
#include <iostream>
#include <new> // Needed for bad-alloc exception
#include <cstdlib> // Needed for the exit function
using namespace std;

template <class T>
class SimpleVector {
        private:

        T *aptr; // To point to the allocated array
        int arraysize; // Number of elements in the array
        void memError(); // Handles memory allocation errors
        void subError(); // Handles subscripts out of range
public:

        SimpleVector()
                {
                aptr = 0; arraysize = 0;
                }

        SimpleVector(int s);

        SimpleVector(const SimpleVector &);

        ~SimpleVector();

        int size() const
                {
                return arraysize;
                }

        T getElementAt(int sub);

        T &operator[](const int &);


};

#endif //SIMPLEVECTOR_H

template <class T>
SimpleVector<T>::SimpleVector(int s)
{
        if(s<1)
                {
                arraysize=1;
                }

        else
                {
                arraysize=s;
                }

        try
                {
                aptr = new T [arraysize];
                }

        catch (bad_alloc)
                {
                memError();
                }

        for(int i=0;i<arraysize;i++)
                {
                aptr[i]=0;
                {
} 

template <class T>
void SimpleVector<T>::memError()
{

        cout<<"Error: cannot allocate memory."<<endl;
        exit(EXIT_FAILURE);

}

template <class T>
T SimpleVector<T>::getElementAt(int sub)
{
        return aptr[sub];
}

template <class T>
SimpleVector<T>::~SimpleVector()
{
        if(arraysize>0)
                {
                aptr.clear();
                aptr=aptr[0];
                }
}

template <class T>
void SimpleVector<T>::subError()
{

        cout<<"Subscripts out of range."<<endl;
        exit(EXIT_FAILURE);

}


Then here are the errors I'm getting.

In file included from main.cpp:4:0:
simplevector.h: In constructor ‘SimpleVector<T>::SimpleVector(int)’:
simplevector.h:87:1: error: a template declaration cannot appear at block scope
 template <class T>
 ^
simplevector.h:99:1: error: expected ‘;’ before ‘template’
 template <class T>
 ^
simplevector.h:109:1: error: a template declaration cannot appear at block scope
 template <class T>
 ^
simplevector.h:122:1: error: expected ‘;’ before ‘template’
 template <class T>
 ^
main.cpp:9:1: error: a function-definition is not allowed here before ‘{’ token
 {
 ^
main.cpp:47:1: error: expected ‘}’ at end of input
 }
 ^
main.cpp:47:1: error: expected ‘}’ at end of input
make: *** [main.o] Error 1

Any insight or help would be amazing!

C++ Linker error on template class and template function [duplicate]

Test.h

typedef enum oflags_t : uint8_t
{
    FLAG_CREAT = O_CREAT  
  , FLAG_RONLY = O_RDONLY  
  , FLAG_RDWR = O_RDWR  
} oflags_t;

template <uint8_t flags>
class Test {

public:

    template <uint8_t flags_in = flags>
    Test(const std::string &p_name);

};

using Test_1 = Test<FLAG_RONLY>;

Test.cpp

template <uint8_t flags>
template <uint8_t flags_in>
Test<flags>::Test(const std::string &p_name) {

}

template class Test<FLAG_RONLY>;

main.cpp

 Test_1 obj1("Obj");

When i try to build this, i get linker error "unresolved external symbol...".

What can i do to solve the issue? Thank you.

Conversion of an configuration settings file (.ini) to json format

I have a configuration settings file (.ini) like declared in the code :

Volumes::Volumes(QWidget *parent) :
QDialog(parent),
ui(new Ui::Volumes), m_settings(new QSettings(qAppName() + ".ini", QSettings::IniFormat))

What I want to do is to save those settings, like I did in file.ini, but not as an ini file, but as json format. How can I do that ? Is there a possibility to declare the file from the beginning as json file ? ( It would be better ) Otherwise, how can I convert the .ini file that I have to json format ?

Parsing comma delimited text in C++

I am working on a project where I am given a comma delimited string of text in an array, and need to parse each array index into its own object.

For example: string studentData[] = { "Student1,Adam,Smith,ASmith@gmail.com,20", "Student2,Erick,Smith,ESmith@gmailcom,19"}

I have objects created to hold StudentName, EmailAddress, and Age, but cannot find a way to get the values from the array into the objects.

Iterate through std::initializer_list

//parameter pack sum example

constexpr int sum(int N= 0)
{
    return N;
}
template<typename ...Args>
constexpr int sum(int first, int second, Args ...N)
{
    return first + second + sum(N...);
}

int main()
{
    std::cout << sum<int>(1,6,3);
}

Is it possible to make this sum at compile time with std::initializer_list<int> how can i iterate recursive through this.

How do I pass a Self referential Structure by Reference in C++

I have the following c++ structure

struct TreeNode {
      int val;
      TreeNode *left;
      TreeNode *right;
      TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  };

I have a function which sets TreeNode's children to null if their subtrees do not contain the value 1.

bool modify(TreeNode *root)
{
   if(root==NULL)
   return false;

   if(root->val!=1)
   {
      bool l = modify(root->left);
      bool r = modify(root->right);
      if(l||r)
      {
       return true;
      }
      else
      {
       root = NULL;
       return false;
      }
   }
   else
   return true; 
}

How do I pass TreeNode *root by reference so that modifications made inside modify() are persisted?

mercredi 26 février 2020

Constructing std::chrono::system_clock::time_point from a duration

I have a data source that provides time since the start of the day (00:00:00Z). I want to construct a std::chrono::time_point based in this input.

For the sake of example, the current time is 2020-02-27T01:05:30.687073184. My source provides me a binary-coded decimal value, to 0.01 seconds. I construct intermeditate values to separate the parsing/mediation from the combination.

        using Days = std::chrono::duration<int, std::ratio<86400>>;

        auto hr10  = std::chrono::duration<unsigned, std::ratio<36000>> ( 0 );
        auto hr1   = std::chrono::duration<unsigned, std::ratio<3600>>  ( 1 );
        auto mn10  = std::chrono::duration<unsigned, std::ratio<600>>   ( 0 );
        auto mn1   = std::chrono::duration<unsigned, std::ratio<60>>    ( 5 );
        auto sc10  = std::chrono::duration<unsigned, std::ratio<10>>    ( 3 );
        auto sc1   = std::chrono::duration<unsigned, std::ratio<1>>     ( 0 );
        auto ms100 = std::chrono::duration<unsigned, std::ratio<1, 10>> ( 6 );
        auto ms10  = std::chrono::duration<unsigned, std::ratio<1, 100>>( 8 );

        auto t = hr10 + hr1 + mn10 + mn1 + sc10 + sc1 + ms100 + ms10;  // 393068
        auto now = std::chrono::system_clock::now();
        auto sinceEpoch = now.time_since_epoch();      // 1582765530687073184 ns

        auto today = std::chrono::duration_cast<Days>(sinceEpoch);    // 18319 days
        auto sinceDay = sinceEpoch - today;            // 3930687073184 ns

// There is logic to determine if there is a day roll-over; it is not relevant here
        auto adjust = Days(0);

// Create the time_point
        auto tp = std::chrono::system_clock::time_point();
        std::cout << "\n\tnull:       " << tp.time_since_epoch().count();

        tp += today;
        std::cout << "\n\ttoday:      " << tp.time_since_epoch().count();

        tp += adjust;
        std::cout << "\n\tadjust:     " << tp.time_since_epoch().count();

        tp += t;
        std::cout << "\n\tt:          " << tp.time_since_epoch().count();

        std::cout << "\n\tall-in-one: " << decltype(tp)(today+adjust+t).time_since_epoch().count();

This results in the following output:

        null:       0
        today:      1582761600000000000
        adjust:     1582761600000000000
        t:          1582765530680000000
        all-in-one: 36577304120000000

What I don't understand is why incrementally adding each duration to the time_point produces the desired effect, but trying to construct the time_point from an aggregate duration does not.

Unable to find a user-defined type in an c++ unordered set with custom operator==()

Problem Statement: Iterate over an array of objects and check if the object exists in an unordered_set.

Goal: I could have thousand of objects in one container to check their existence in millions of objects in another container. I choose unordered_set for its constant finding complexity and vector for iterating. I'm new to this and if you have any alternate approach, I'd really appreciate it.

Issue: unordered_set find isn't working as expected or I got the concept wrong!

Main:

int main() {
  std::vector<std::unique_ptr<Block>> vertices;

  vertices.push_back(std::make_unique<Block>("mod1", "work"));
  vertices.push_back(std::make_unique<Block>("mod2", "work"));
  vertices.push_back(std::make_unique<Block>("mod3", "work"));

  std::unordered_set<std::unique_ptr<Block>> undefs;

  undefs.insert(std::make_unique<Block>("mod1", "work"));
  undefs.insert(std::make_unique<Block>("mod2", "work"));

  for(auto& vertex : vertices) {
    auto search = undefs.find(vertex);
    if(search != undefs.end()){
      std::cout << "Block: " << vertex->getName() << "\n";
    }
  }
}

Block Class Overload:

bool Block::operator==(std::unique_ptr<Block>& block) const {
  return block->getName() == mName;
}

Expected Output:

mod1

mod2

Block:

#pragma once

#include <string>
#include <memory>

using std::string;

class Block {
  private:
    string mName;
    string mLib;
  public:
    Block(string const& name, string const& lib);
    string getName() const;
    string getLib() const;
    bool operator==(std::unique_ptr<Block>& block) const;
};

Auto keyword in C++ 17 [closed]

I am reviving some old code that was written using C++ 11, but I now want to utilize some C++ 17 features.

        auto last = std::unique(creoBomVector.begin(), creoBomVector.end());

        creoBomVector.erase(last, creoBomVector.end());

This will compile in C++ 11 no problem, the system knows what type last is.

In C++ 17, the compile error is:

error: 'last' does not name a type error: 'last' was not declared in this scope

In C++ 11, last was not defined in this specific function.

I tried defining 'last', but I quickly realized the compiler was handling 'last' differently than I realized.

I defined last as a string, and I am getting the error: error: 'last' does not name a type.

I admit, my C++ skills are extremely rusty and even at my best, I was mostly using basic standard features to get my scripts done.

Is there a quick fix to the above two lines of code, or do I need to rebuild the way I handled this instruction? I am sure the way I am utilizing the auto keyword in this instance is not recommended.

How to implement std::move() alternative if I am not using C++11?

I am working on some projects and have a problem. I have a class that is too big and don't want to copy objects and want to use a smarter solution. So, if I don't want to copy, I can move() it. But the problem is that I am not using C++11 but C++10 (as the people in my company said)

I can't use the std::move() function and have to implement it in my source code.

Can somebody help me to do that in efficient way?

Pointer To Pointer passed by reference

Just to check: if i want to pass by ref a double pointer float **ptr through a function, should i declare it as: void Func(float **&ptr) or Func(float **&&ptr) ?

Thanks

Avoid field zero initialization in C++14

Since C++14 (it might be C++11, i'm not sure), zero initialization happens on class construction on certain conditions, depending on the way the constructor is called. Is there a way to ensure a raw value field (let's say a pointer) is never zero initialized ?

I guess not because it seems that zero initialization happens at the class level and not at the field level (surely a kind of memset(this, 0, sizeof(TheClass))), but I'm still hoping there is way, a hack, something...

The idea is to be able to initialize a field before a placement new is called so that that member is available during construction time.

"initial value of reference to non-const must be an lvalue" with overloading + for concatenating vectors

void print(/* const  */ vector<int> &A)
{
   for (int i = 0; i < A.size(); i++)
      cout << A[i] << " ";
   cout << endl;
}

vector<int> operator+(vector<int> &a, vector<int> &b)
{
   vector<int> ret = a;
   ret.insert(ret.end(), b.begin(), b.end());
   return ret;
}

int main(){
     vector<int> A = {1,1,1}
     vector<int> D = {1,1}
     print(A + B)

}

Without decommenting const it says

initial value of reference to non-const must be an lvalue

why is that so ? if operator returns non-const vector and print accepts non-const ?

i.m trying to split string by whitespace using c++, where the data from database

i have tried this, the compilation's result is no error, but the result of running is not suitable

therefore i'm freaking desperate to solve this problem, i have been trying since 2 weeks ago but got nothing

using namespace std;
int main()
{
int j, count = 0;
char del[] = ".,/;:";
string hadis;
MYSQL* conn;
MYSQL_ROW row;
MYSQL_RES* res;
conn = mysql_init(0);
conn = mysql_real_connect(conn, "192.168.43.205", "ibrahim", "hadis", "hadis", 0, NULL, 0);
if(conn)
{
    int qstate = mysql_query(conn, "SELECT Isi_Indonesia FROM malik");
    if(!qstate)
    {
        res = mysql_store_result(conn);
        while(row = mysql_fetch_row(res))
        {
            hadis = row[0];
            for(unsigned int i=0;i<strlen(del);++i)
            {
                hadis.erase (remove(hadis.begin(), hadis.end(), del[i]), hadis.end());
                }
            for (j=0; hadis[j]; j++)
            {
                if (hadis[j] == ' ')
                count++;
                cout<< "-";
            }
            cout<<hadis[j];
        }
    }
}
return 0;

}

Lambda expression with external parameters [duplicate]

I have a question about using lambda expression as input for another function. In the following, I reproduce the problem using the simplest code:

#include<iostream>
using namespace std;

double myop(double (*func)(double), double x)
{
    return (*func)(x);
}

int main()
{
    double a = 0.1;
    auto sq = [a](double x)
    {
        return a+x*x;
    };

    double x = 2;
    cout << myop(sq, x) << endl;
    return 0;
}

Once I compile the code, the compiler pop up "error: cannot convert ‘main()::’ to ‘double ()(double)’ for argument ‘1’ to ‘double myop(double ()(double), double)’ cout << myop(sq, x) << endl;".

I have tested that if the lambda expression doesn't contain any external parameters (such as 'a' in this example), then it works. But how can I deal with the case that having some external parameter dependence? Thanks in advance.

When I call a function with single argument of type bool with empty parentheses, what is the value of a bool parameter?

I just wonder what is the value of bool parameter of member function, when function is called without passing value?
Is it false? Why is it false?

bool CSVread::Reset( bool partial_reset /* = false */ )  

then reset is called as

obj.reset()

No argument is passed so what is value of partial_reset and why? In visual studio it is false, but why?

I cannot find any definition of bool value as being false for function argument?
Isn't function argument part of function scope, so it should be of automatic storage and thus its default value is undefined?

Template argument substitution fails and implicit conversion is not done

#include <type_traits>

template<bool Const>
struct view_tpl {
    using value_type = std::conditional_t<Const, const int, int>;
    value_type* ptr;

    view_tpl() = default;
    view_tpl(const view_tpl<false>& other) : ptr(other.ptr) { }
};

using view = view_tpl<false>;
using const_view = view_tpl<true>;

void read(const const_view& vw) { }

int main() {
    view vw;
    read(vw);
}

This code defines a const and a non-const view type, both as aliases to a view_tpl<Const> template. It should be such that view is implicitly convertible to const_view, but not the other way around.

It Const is true, the defined copy-constructor enables this, and the compiler generates an additional default copy-constructor. If Const is false the defined copy-constructor replaces the default copy-constructor.

This implicit conversion should happen when f(vw) is called.

It works correctly in the above code.


But if I add an argument to the templates (int N), and turn f and the two type aliasses into templates, it no longer works:

#include <type_traits>

template<int N, bool Const>
struct view_tpl {
    using value_type = std::conditional_t<Const, const int, int>;
    value_type* ptr;

    view_tpl() = default;
    view_tpl(const view_tpl<N, false>& other) : ptr(other.ptr) { }
};

template<int N> using view = view_tpl<N, false>;
template<int N> using const_view = view_tpl<N, true>;

template<int N>
void read(const const_view<N>& vw) { }

int main() {
    view<0> vw;
    read(vw);
}

Instead of doing the conversion of view_tpl<0, true> to view_tpl<0, false>, the compiler only tries a direct template substitution and fails:

main.cpp: In function 'int main()':
main.cpp:20:12: error: no matching function for call to 'read(view<0>&)'
   20 |     read(vw);
      |            ^
main.cpp:16:6: note: candidate: 'template<int N> void read(const_view<N>&)'
   16 | void read(const const_view<N>& vw) { }
      |      ^~~~
main.cpp:16:6: note:   template argument deduction/substitution failed:
main.cpp:20:12: note:   template argument 'false' does not match 'true'
   20 |     read(vw);
      |            ^

Is there a way to make this work without changing too much of the code? (The real code is more complex than this example)

mardi 25 février 2020

Map object method using std::function

I want to map the Math object method in string in the following code

#include <functional>
#include <iostream>
#include <map>
#include <string>

struct Math
{
    double foo(double& x) { return 100.0; };
    double bar(double& x) { return 400.0; };
};

int main()
{
    Math m;
    std::map<std::string, std::function<double(double&)>> nn =
    {
        {"sin", [&m](double& x) {m.foo(x);}}
    };
}

The above code gives two errors, the first is

'initializing': cannot convert from 'initializer list' to 'std::map<std::string,std::function<double (double &)>,std::less<_Kty>,std::allocator<std::pair<const _Kty,_Ty>>>'
        with
        [
            _Kty=std::string,
            _Ty=std::function<double (double &)>
        ]

and the second error:

no instance of constructor "std::map<_Kty, _Ty, _Pr, _Alloc>::map [with _Kty=std::string, _Ty=std::function<double (double &)>, _Pr=std::less<std::string>, _Alloc=std::allocator<std::pair<const std::string, std::function<double (double &)>>>]" matches the argument list

Please help, thank you

Using strcpy to copy elements of an char array to another array

So I building a spell checker and I have this as my TrieNode class:

class TrieNode{
public:
    bool isWord;
    char word[100][20];
    TrieNode* letter[alphabetSize];

I have an insert method inside my Trie class which is:

    void insert(TrieNode* root, char* wordInsert);

I was able to insert the letters of char* word into my trie

This is what I have for my insert function:

void Trie::insert(TrieNode* root, char* wordInsert) {
    TrieNode* currentNode = root;
    int wordLength = strlen(wordInsert);
    for (int i = 0; i < wordLength; i++) {
        //strcpy(currentNode->word[i], currentNode->letter);
        int index = wordInsert[i]- 'a';
        if(!currentNode->letter[index]){
            currentNode->letter[index] = new TrieNode();
        }
        currentNode = currentNode->letter[index];
    }
    currentNode->isWord = true;

}

Now I want to insert the current->letter[i] into my other char* array in my TrieNode class called word

I tried doing

strcpy(currentNode->word, currentNode->letter[i])

but I get an error saying :

No matching function for call to 'strcpy'

How would I be able to get the elements from the letter array into the array called word which is also in my TrieNode class

How to create BOOST_COMPUTE_FUNCTION from class member function?

my object-class is as follows:

class TTT{
public:
    int value;
    double start(std::vector<unsigned int> input){
        double out=0;
        for (auto i:input){
            out+=this->factorial(i);
        }
        return out+this->value;
    }
private:
    double factorial(unsigned int i)
    {
        if(i <= 1)
        {
            return 1;
        }
        return i * factorial(i - 1);
    }
};

when I try to create it like this:

    BOOST_COMPUTE_FUNCTION(double, test,
                           (TTT values0,std::vector<unsigned int> values1),
                           {
                               return values0.start(values1);
                           });

I got errors,because I use two classes TTT and std::vector:

sp, how should I use boost::compute to improve CPU object-class computation ?

I have a problem about linked list and its nodes

I have a homework in c++ (using vector is illegal. the only vector in struct). I have to create a linked list and every node has 3 different empty data. First is int for month, second is int for year and the last one is vector of string for specific number from struct. But I'm trying to learn and not good at it. How can i create the linked list? And while creating every node i have to add year and month in it. And I have to pushback the number in vector. But if the month and year will be the same in another line i have to pushback the number to old vector which has the same month and year in same node. my txt file is like that

number month year number month year ... ... ...

it goes like that. every number is specific. but year and month could be same.

C++ map: operator[] with custom class does not work

I'm trying to implement a MinHeap, where objects on the heap are WorkerNodes. My method returns map which is intended to allow client code to determine which WorkerNode indices have changed from the minHeapify operation.

std::cout << "heapifying " << heap_[root] << "from index " << root << "\n.";
    int size = heap_.size();
    bool swapped = false;
    std::map<WorkerNode, int> tracker;

    for (int i = root; i >= 0; --i)
    {
        while (true)
        {
            int leftChild = 2 * i + 1;
            if (leftChild < 0 || leftChild >= size)
                break;
            int rightChild = 2 * i + 2;
            int smallerChild = leftChild;
            if (rightChild < size && heap_[rightChild] < heap_[leftChild])
                smallerChild = rightChild;

            if (heap_[i] <= heap_[smallerChild])
                break;

            // index tracking

            tracker[heap_[i]] = smallerChild;
            tracker[heap_[smallerChild]] = i;

            std::cout << "**\n\n"
                      << heap_[i] << " has moved to " << smallerChild;
            std::cout << ", and " << heap_[smallerChild] << " has moved to " << i << "\n**";

            // swap heap_[i] and heap_[smallerChild]
            swapped = true;
            T temp = heap_[i];
            heap_[i] = heap_[smallerChild];
            heap_[smallerChild] = temp;
            i = smallerChild;
        }
    }
    if (!swapped) // avoids bad access
    {
        tracker[heap_[root]] = root;

        for (auto &itm : tracker)
        {
            std::cout << "**\n"
                      << itm.first << " is at " << itm.second << "!!!\n";
        }
        std::cout << "**\nno swap; " << heap_[root] << " stays at " << tracker[heap_[root]] << "\n**";
    }

    return tracker;

Here is the ouput that I am seeing:

heapifying W1-1from index 0
.**
W1-1 is at 0!!!
**
no swap; W1-1 stays at 0
**heapifying W2-2from index 1
.**
W2-2 is at 1!!!
**
no swap; W2-2 stays at 0
**heapifying W3-3from index 2
.**
W3-3 is at 2!!!
**
no swap; W3-3 stays at 0
**heapifying W0-3from index 3
.**
W0-3 is at 3!!!
**
no swap; W0-3 stays at 0

This issue was brought to my attention when running test cases, where I am doing something like this:

WorkerNode key("W4", 2);
    // after two decrements, its index should still be 3.
    BOOST_TEST(tracker[key] == 3);

And getting output like this:

error: in "minheap_test_suite/case6": check tracker[key] == 3 has failed [0 != 3]

So from what I can tell, The pre-exit for loop in my minHeapify method confirms that the proper data is being inserted into the map, but when I try to access this data using the [] operator, it is unable to locate the WorkerNode-index pairing I just inserted, returning 0 as the value it has probably just default-constructed.

When I tried using find() instead of [] just now like so:

tracker[heap_[root]] = root;

        for (auto &itm : tracker)
        {
            std::cout << "**\n"
                      << itm.first << " is at " << itm.second << "!!!\n";
        }
        int index = tracker.find(heap_[root])->second;
        std::cout << "**\nno swap; " << heap_[root] << " stays at " << index << "\n**";

I get the following output:

heapifying W1-1from index 0
.**
W1-1 is at 0!!!
**
no swap; W1-1 stays at -1354735968
**heapifying W2-2from index 1
.**
W2-2 is at 1!!!
**
no swap; W2-2 stays at 3233540

Here is my WorkerNode.h file, comments removed:

#include <ostream>
#include <string>

struct WorkerNode
{
    unsigned numJobs_;     ///< worker job count.
    std::string workerID_; ///< worker ID string.

    explicit WorkerNode() : numJobs_(0), workerID_("") {}

    WorkerNode(std::string id) : numJobs_(0), workerID_(id) {}

    WorkerNode(std::string id, unsigned jobs) : numJobs_(jobs), workerID_(id) {}

    WorkerNode(WorkerNode &&other) : numJobs_(other.numJobs_), workerID_(other.workerID_)
    {
        other.numJobs_ = 0;
        other.workerID_ = "";
    }

    WorkerNode(const WorkerNode &other) : numJobs_(other.numJobs_), workerID_(other.workerID_) {}

    WorkerNode &operator=(const WorkerNode &other)
    {
        if (this == &other)
            return *this;
        this->numJobs_ = other.numJobs_;
        this->workerID_ = other.workerID_;
        return *this;
    }

    WorkerNode &operator=(WorkerNode &&other)
    {
        if (this == &other)
            return *this;
        this->numJobs_ = other.numJobs_;
        this->workerID_ = other.workerID_;
        other.numJobs_ = 0;
        other.workerID_ = "";
        return *this;
    }

    ~WorkerNode() {}

    bool operator<(const WorkerNode &rhs) const
    {
        return *this <= rhs;
    }

    bool operator<=(const WorkerNode &rhs) const
    {
        if (numJobs_ < rhs.numJobs_)
            return true;
        else if (rhs.numJobs_ < numJobs_)
            return false;
        else
        {
            return workerID_.compare(rhs.workerID_) <= 0 ? true : false;
        }
    }

    bool operator==(const WorkerNode &rhs) const
    {
        if (numJobs_ == rhs.numJobs_ && workerID_ == rhs.workerID_)
            return true;
        else
        {
            return false;
        }
    }

    void operator--()
    {
        if (numJobs_ > 0)
            numJobs_ -= 1;
    }

    void operator++()
    {
        numJobs_ += 1;
    }

    friend std::ostream &operator<<(std::ostream &out, const WorkerNode &n)
    {
        out << n.workerID_ << "-" << n.numJobs_;
        return out;
    }
};

WTF am I doing wrong here?

Are std::atomic loads and stores both required?

According to this article:

Any time two threads operate on a shared variable concurrently, and one of those operations performs a write, both threads must use atomic operations.

However, if a lower-priority thread is the writer, and a higher-priority thread is the reader, does the lower-priority thread need to enforce atomic stores? It seems to me that only the higher-priority thread needs to enforce an atomic load:

#include <atomic>

std::atomic<T*> ptr; // assume initialized to some non-null value

void highPriThreadFcn(void)
{
    T* local_ptr = ptr.load(); // need atomic load here in case lowPriThread write/store was interrupted
}

void lowPriThreadFcn(T* some_ptr)
{
    ptr = some_ptr; // do I need an atomic store here? I'd think not, as ptr is not written to by highPriThread
}

A similar question would apply in the "reverse" case (write in high-priority thread, read from low-priority thread):

void highPriThreadFcn(T* some_ptr)
{
    ptr = some_ptr; // do I need an atomic store here? I'd think not, as write to ptr cannot be interrupted
}

void lowPriThreadFcn(void)
{
    T* local_ptr = ptr.load(); // need atomic load here in case read/load was interrupted
}

Finding smallest value in an array with C++ [duplicate]

I am a C++ beginner and would like to find the smallest value in an array.

In JAVA, no problem at all.

JAVA

public class Algorithm {
    public int smallest(int[] a) {
        int smallest = a[0];
        for (int i = 1; i < a.length; i++) {
            if (smallest > a[i]) {
                smallest = a[i];
            }
        }
        return smallest;
    }
    public static void main(String[] args) {
        int[] numbers = { 3, 5, 6, -12, -36, 5, 6, 7, -37 };
        Algorithm al = new Algorithm();
        System.out.print(al.smallest(numbers));
    }
}

But in C++ - I cannot find a solution to loop thru an array.

C++

#include <iostream>

int smallest(int a[]) {
    int smallest = a[0];
    for(int i = 1; i < a."whatComeHere??"; i++){
        if(smallest > a[i]) {
            smallest = a[i];
        }
    }
    return smallest;
}
int main() {
    int numbers[] = { -5, 2, 4, -6, 5, 6, 7, 8, -3, -56 };
    std::cout << smallest(numbers) << std::endl;
    return 0;
}

Thanks for any help. I appreciate that.

C++ What syntax for avoid duplicated declarations?

I'm learning C++ and especially OO Programming.

My program use pointers to deal with Dynamic memory allocation.

While creating my default constructor, I was boring about repeat myself with

myInt = new int;
myOtherInt = new int; 

etc..

So my question is : is there a way to write something like :

myInt, myOtherInt = new int;

Here's my constructor code :

Annonce::Annonce(string Titre, long double Prix, string Intro, string Description, vector<vector<string>> ImgUrls) {

    titre = new string;
    intro = new string;
    description = new string;
    imgUrls = new vector<vector<string>>;
    prix = new long double;

    id = new size_t;
    *id = nbAnnonces;

    *titre = std::move(Titre);
    *prix = Prix;
    *intro = std::move(Intro);
    *description = std::move(Description);
    *imgUrls = std::move(ImgUrls);

}

"throw expression code" How is this piece of code working and what are that arguments meaning?

I want to learn all about exceptions in c++ and I found this code here to issue some because my OOM killer on Linux is not issuing terminate. I just don't understand what this code is doing in particular:

#include <iostream>
#include <stdexcept>

double f(double d)
{
    return d > 1e7 ? throw std::overflow_error("too big") : d; //what is going on here?
}
int main()
{
    try {
        std::cout << f(1e10) << '\n';
    } catch (const std::overflow_error& e) {
        std::cout << e.what() << '\n'; // information from length_error printed
    }
    return 0;
}

Difference between std::resize(n) and std::shrink_to_fit in C++?

I came across these statements:

resize(n) – Resizes the container so that it contains ‘n’ elements. shrink_to_fit() – Reduces the capacity of the container to fit its size and destroys all elements beyond the capacity.

Is there any significant difference between these functions? they come under vectors in c++

I have added data to the file using one char variable and 1 integer if I want to check the data with the string variable i am not able to check that

* I am working on my attendance mini project .I want to check the string variable is entered in present in my file or not .There is problem in my check_data() function .Kindly help me out *

 #include<fstream>
#include<iostream>
using namespace std;
class attend
{
int idn;
char ar[10];
public:
   void getdata()
   {
    cout<<"ENTER THE ROLL NUMBER \n";
    cin>>idn;
    fstream fout("AT1.txt",ios::app);
    fout<<"\n"<<idn;
    cout<<"ENTER THE NAME "<<endl;
    cin>>ar;
    fout<<"\t"<<ar;
    fout.close();
  }
   void check_data()
   {
    char i,chk[10];
   cout<<"ENTER THE NAME TO CHECK "<<"\n";
   cin>>chk;
   fstream fin("AT1.txt",ios::in);
              while(!fin.eof())
            {
                fin>>ar;
                cout<<"\n"<<ar;
                for(i=0;i<10;i++)
                {
                if(chk[i]==ar[i])
                {
                    cout<<"DATA FOUND ";
                }
                }
            }   
   }    
};
int main()
{
    attend obj;
    obj.getdata();
    obj.check_data();
}

conditional constexpr functions

I have here the case that a function could potentially be constexpr. Normally one adds the constexpr and use the constant evaluation only if the context allows it. However the following code complaints despite not using it in a constexpr context:

template <typename T>
struct Wrapper
{
    friend constexpr bool operator==(const Wrapper& crLhs, const Wrapper& crRhs) noexcept
    {
        return crLhs.m_t == crRhs.m_t;
    }

    T m_t = {};
};

Using Visual Studio 2017 15.9.20 this gives 'error C3615: constexpr function 'operator ==' cannot result in a constant expression' when e.g. instantiated for std::string. The information is correct but I am not instantiating it in a constexpr context.

void f()
{
   bool b;

   Wrapper<int>  a;

   b = a == a; //ok

   Wrapper<std::string> c;

   b = c == c;  //C3615, but not using constexpr context
}

I can apply a workaround it by using a member template or drop the constexpr but is there fancy trick here to have the best of both worlds (i.e. constexpr when applicable)?

why does my code occur segmentation fault?

I tried to solve algorithm that print out the maximum value.

And it printed out segmentation fault. I looked up for any memory access, but I couldn't find any mistakes..

Please help me why the code occurs segmentation fault..

 #include <iostream>
 #include <cstring>
 #include <algorithm>
 #include <cmath>

 using namespace std;

 int M, A;
 int ans=0;
 struct BC{
    int x, y;
    int C;
    int P;
    bool valid;
 }ap[8];

 int path[2][100];
 int dx[5]={0, 0, 1, 0, -1};
 int dy[5]={0, -1, 0, 1, 0};

 struct people{
     int x, y; 
 }human[2];


void init(){
    memset(path, 0, sizeof(path));
    std::cin>>M>>A;
    for(int j=0; j<2; j++){
        for(int i=0; i<M; i++){
            std::cin>>path[j][i];
        }
    }

for(int i=0; i<A; i++){
    std::cin>>ap[i].x>>ap[i].y>>ap[i].C>>ap[i].P;
    ap[i].valid=true;
}
ans=0;
human[0].x=1;
human[0].y=1;
human[1].x=10;
human[1].y=10;
}

bool pos(int h, int idx){
    int dist=abs(human[h].x-ap[idx].x)+abs(human[h].y-ap[idx].y);
    if(dist<=ap[idx].C) return true;
    return false;
}

int ret=0;
void dfs(int user, int d){
    if(user==2){
        if(ret<d) ret=d;
        return;
    }
    for(int i=0; i<A; i++){
        if(ap[i].valid && pos(user, i)){
            ap[i].valid=false;
            dfs(user+1, d+ap[i].P);
            ap[i].valid=true;
        }
    }
    dfs(user+1, d);
}

void solve(){
    ret=0;
    dfs(0,0);
    ans+=ret;
    for(int i=0; i<M; i++){
        for(int j=0; j<2; j++){
            human[j].x+=dx[path[j][i]];
            human[j].y+=dy[path[j][i]];
        }
        ret=0;
        dfs(0,0);
        ans+=ret;
    }
}

int main(){
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    int TC;
    for(int i=0; i<TC; i++){
        init();
        solve();

        std::cout<<"#"<<i+1<<" "<<ans<<"\n";
    }
    return 0;
}

sample input is like this:

1

20 3

2 2 3 2 2 2 2 3 3 4 4 3 2 2 3 3 3 2 2 3

4 4 1 4 4 1 4 4 1 1 1 4 1 4 3 3 3 3 3 3

4 4 1 100

7 10 3 40

6 3 2 70

How to elevate a specific style error in cppcheck

I use cppcheck via the CLI in a continuous integration test parcours. If cppcheck fails, my job fails. Thus, I am limiting the issues cppcheck tests in order to not halt the development completely.

More specifically, I currently use --enable=missingInclude,warning together with some --suppress.

How can I elevate specific, non-error and non-warning issue to let cppcheck fail, e.g. missingOverride, which is of the category "style" ?

  • --enable=missingOverride does not seem to work as enable only accepts error|warning|style|performance|portability|information|all
  • --enable=style is also no option because then I have way too many aspects to take care of to get my CI running again instead of fixing them iteratively

Creating an object instance of a class inside another class c++

Hey I try to understand the constructing order in objects, as I see when I wrote the following code I see the object x inside the class Y was never constructed, any explanation why?

    #include <iostream>
    class X {
    public:
        X() { std::cout << "1"; }
        ~X() { std::cout << "2";  }
    };
    class Y {
    public:
        **X x**;
        Y() { std::cout << "3"; }
        ~Y() { std::cout << "4"; }

    };
    void main()
    {
        Y y;
    }

Nth digit from Most significant digit side

I want to write a function int returnNthDigit(long long int number, int position) {} such that it returns the Nth position digit from the left side. e.g. returnNthDigit(45006, 1); must return 4. Similarly, returnNthDigit(45006, 2); must return 5. I am not allowed to use any looping statement. Here is one solution I came up with by using loops.

#include <iostream>
#include <math.h>

int returnNthDigit(long long int number, int position)
{
    int numberOfDigits = log10(number) + 1;
    int iteration = numberOfDigits - position;
    while (iteration != 0)
    {
        number = number / 10;
        --iteration;
    }
    return number % 10;
}

int main() {
    std:: ios_base::sync_with_stdio(false);
    std:: cout << returnNthDigit(230045, 5);
    return 0;
}

Can I do better?

C++ or MFC - How to read a file which is in UCS-2 LE BOM encoding

Please suggest me a way to read a file with UCS-2 LE BOM encoding in C++/MFC.

Thanks in advance

Overloading type from parent namespace

This seems to compile correctly:

namespace A {
    template<typename T>
    struct S {};

    namespace B {
        using S = S<int>;
    }
}

int main() {
    using namespace A::B;
    S s;
}

Even though at the line using S = S<int>, the first S refers to A::B::S, whereas the second S refers to the template A::S.

Is this standard C++?

lundi 24 février 2020

C++ map segmentation fault (core dumped)

I'm trying to use an map with string key, but it's not working and I couldn't figure out why. I would like to have some help to understand C++ fundamentals about the usage of this so essential structure.

model.hpp

#pragma once
#include <map>
#include <utility>
#include <string>
#include <iostream>
#include "../prs/ast.h"

using namespace std;
using namespace ast;

typedef map<string, Variable> Map;
typedef pair<string, Variable> Element;

namespace model{

    class Warehouse {
    public:
        Map stock;

        Warehouse(){
            Map* _stock = new Map();
            stock = *_stock;
        }

        Variable* get(string id){
            Map::iterator it = stock.find(id);
            if (it != stock.end()){
                return &(*it).second;
            }
            else {
                return __define__(id);
            }
        }

        Variable* __define__(string id){
            Variable* defined = new Variable(id);
            stock.insert(Element(id, *defined));
            return defined;
        }
    };

    static Warehouse* WAREHOUSE;
};

model.cpp

#pragma once
#include "model.hpp"

using namespace std;

namespace model {
    Warehouse* WAREHOUSE = new Warehouse();
}

In this context, Variable is a project object defined in ast namespace already tested, as well WAREHOUSE pointer is working accordingly, with class initialized

The instruction stock.find(id) is throwing the mentioned error message: Segmentation fault (core dumped), what I suppose means stock isn't correct initialized.

What is exactly happening with stock initialization done at Warehouse constructor? I understand that new keyword allocs the map and dereference its returned point would store the structure at stock Warehouse member attribute.

Am I misunderstand it?

Boolean function with reference parameter

I have been searching around and I cant quite get the answer I looking for or see the example I want. I'm working with a binary tree. I have a bool search function that checks the whole tree. I currently have this

  bool search(int key)
  {
    NODE* cur = Root;

    while (cur != nullptr)
    {
      if (key == cur->Key)  // already in tree
        return true;

      if (key < cur->Key)  // search left:
      {
        cur = cur->Left;
      }
      else
      {
        cur = cur->Right;
      }
    }//while  

    // if get here, not found
    return false;
  }

But now i want to modify this to as if the key is found the corresponding value is also returned as a reference parameter. So adding, and having the function declaration be

bool search(int key, int& value)

If this is the case can I just declare int value on top of when I return true and have value equal whatever i want it to pass in my case what the value is in that key?

Linked Set ADT implementation troubles

My assignment is to make and ADT for a Set that uses linked lists. I have working methods for the ADT except for one called the "difference." This method should return a new set that contains the strings that the called upon Set and the argument Set don't have in common.

Ex.) Set 1 contains (one, two, three)

Set 2 contains (two, three)

The function should return a Set containing (one)

Any help would be greatly appreciated :) Thanks much!

LinkedSet header:

 *
 *  @course CS1521
 *  @section 8
 *  @term Spring 2020
 *
 *  Header file for a linked implementation of the ADT set.
 *
 *  @date 20 Feb 2020*/
#ifndef LINKED_SET_
#define LINKED_SET_

#include <vector>

#include "SetInterface.h"
#include "Node.h"

/** @class LinkedBag LinkedBag.h "LinkedBag.h"
 *
 *  Specification of a pointer-based ADT bag. */
template <typename ItemType>
class LinkedSet : public SetInterface<ItemType> {
 private:
  using NodePtr = Node<ItemType>*;

  /** Pointer to first node. */
  NodePtr headPtr = nullptr;

  /** Number of items in this bag. */
  int itemCount = 0;

  /** Gets a pointer to the node containing the target in this bag.
   *
   * @pre None.
   *
   * @post None.
   *
   * @param target The ItemType value to find.
   *
   * @return A pointer to the node that contains the given target or
   *         nullptr if the bag does not contain the target. */
  NodePtr getPointerTo(const ItemType& target) const;

 public:
  /** Default constructor. */
  LinkedSet() = default;

  /** Copy constructor. */
  LinkedSet(const LinkedSet<ItemType>& aBag);

  virtual ~LinkedSet();

  virtual int getCurrentSize() const;

  virtual bool isEmpty() const;

  virtual bool add(const ItemType& newEntry);

  virtual bool remove(const ItemType& anEntry);

  virtual void clear();

  virtual int getFrequencyOf(const ItemType& anEntry) const;

  virtual bool contains(const ItemType& anEntry) const;

  virtual LinkedSet<ItemType> difference(LinkedSet<ItemType>& set) const;

  virtual std::vector<ItemType> toVector() const;
};

#include "LinkedSet.cpp"

#endif

Linked Set C++:

 *
 *  @course CS1521
 *  @section 8
 *  @term Spring 2020
 *
 *  Implementation file for the class LinkedSet.
 *
 *  @date 20 Feb 2020*/

#include <vector>

template <typename ItemType>
LinkedSet<ItemType>::LinkedSet(const LinkedSet<ItemType>& aSet) {

  itemCount = aSet.itemCount;

  // If aSet.headPtr is not pointing at a node:
  if (!aSet.headPtr) { // aSet.headPtr == nullptr (!nullptr == true)
    headPtr = nullptr;
  }
  else {
    NodePtr origChainPtr(aSet.headPtr);

    headPtr = new Node<ItemType>(origChainPtr->getItem() );

    NodePtr newChainPtr(headPtr);

    origChainPtr = origChainPtr->getNext();

    while (origChainPtr) { // while (origChainPtr != nullptr) {
      newChainPtr->setNext(new Node<ItemType>(origChainPtr->getItem()) );

      newChainPtr = newChainPtr->getNext();
      origChainPtr = origChainPtr->getNext();
    }
  }
}

template <typename ItemType>
LinkedSet<ItemType>::~LinkedSet() {

  clear();
}

template <typename ItemType>
int LinkedSet<ItemType>::getCurrentSize() const {

  return itemCount;
}

template <typename ItemType>
bool LinkedSet<ItemType>::isEmpty() const {

  return itemCount == 0;
}

template <typename ItemType>
bool LinkedSet<ItemType>::add(const ItemType& newEntry) {
  if (getPointerTo(newEntry) == nullptr)
        {
          headPtr = new Node<ItemType>(newEntry, headPtr);
          ++itemCount;
          return true;
        }
}

template <typename ItemType>
bool LinkedSet<ItemType>::remove(const ItemType& anEntry) {

  NodePtr entryNodePtr(getPointerTo(anEntry) );

  // If entryNodePtr is pointing at a node:
  if (entryNodePtr) { // entryNodePtr != nullptr (nullptr == false)
    entryNodePtr->setItem(headPtr->getItem() );

    NodePtr nodeToDeletePtr(headPtr);

    headPtr = headPtr->getNext();

    delete nodeToDeletePtr;

    --itemCount;
  }

  return static_cast<bool>(entryNodePtr);
}

template <typename ItemType>
Node<ItemType>* LinkedSet<ItemType>::getPointerTo(const ItemType& target) const {

  NodePtr curPtr(headPtr);

  while (curPtr) { // curPtr != nullptr
    if (curPtr->getItem() == target) {
      return curPtr;
    }

    curPtr = curPtr->getNext();
  }

  return curPtr; // nullptr
}

template <typename ItemType>
void LinkedSet<ItemType>::clear() {

  NodePtr nodeToDeletePtr(headPtr);

  while (headPtr) { // headPtr != nullptr
    headPtr = headPtr->getNext();

    delete nodeToDeletePtr;

    nodeToDeletePtr = headPtr;
  }
  // Note that headPtr == nodeToDeletePtr == nullptr
  itemCount = 0;
}

template <typename ItemType>
bool LinkedSet<ItemType>::contains(const ItemType& anEntry) const {

  return static_cast<bool>(getPointerTo(anEntry) ); // ... != nullptr;
}

template <typename ItemType>
int LinkedSet<ItemType>::getFrequencyOf(const ItemType& anEntry) const {

  int frequency(0);

  NodePtr curPtr(headPtr);

  while (curPtr)
    { // != nullptr
    if (curPtr->getItem() == anEntry) {
      ++frequency;
    }

    curPtr = curPtr->getNext();
    }

  return frequency;
}

template <typename ItemType>
LinkedSet<ItemType> LinkedSet<ItemType>::difference(LinkedSet<ItemType>& set) const{
  LinkedSet<ItemType> newSet;
  NodePtr curPtr(headPtr);
  while (curPtr)
    {
      if (set.getPointerTo(curPtr) != getPointerTo(curPtr))
        {
          newSet.add(curPtr);
        }
      curPtr = curPtr->getNext();
    }
    return newSet;
    }

template <typename ItemType>
std::vector<ItemType> LinkedSet<ItemType>::toVector() const {

  std::vector<ItemType> SetContents;

  NodePtr curPtr(headPtr);

  while (curPtr) { // != nullptr
    SetContents.push_back(curPtr->getItem() );

    curPtr = curPtr->getNext();
  }

  return SetContents;
}

How to implement operator[] for a class which holds a std::vector

I'd like to override the [] operator for an object which holds a std::vector object (that is, have the subscripting act as though it were directly applied to the member vector). This is what I have so far

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

class VectorWrapper
{
public:
    VectorWrapper(int N): _N(N), _vec(N) {}

    ~VectorWrapper() {delete &_vec;}

    string operator[](int index) const
    {
        return _vec[index];
    }

    string& operator[](int index)
    {
        return _vec[index];
    }


private:
    int _N;
    vector<string> _vec;
};

int main()
{
    VectorWrapper vo(5);
    vo[0] = "str0";
    std::cout << vo[0];
}

Which upon running produces the following error

Process finished with exit code 11

What am I doing wrong?

passing a class variable to API function

I want to track a global variable that I am passing into an API function. I found that one could do it using a class:

template <class T>
class MonitoredVariable
{
public:
    MonitoredVariable() {}
    MonitoredVariable(const T& value) : m_value(value) {}

    //T operator T() const { return m_value; }

    const MonitoredVariable& operator = (const T& value)
    {
        PlugIn::gResultOut << "value changed " << std::endl;
        m_value = value;
        return *this;
    }


private:
    T m_value;
};

The API function takes variables as

bool APIFunction(double time, bool *is_done, double *fraction_done);

The following gives me an error:

ImagePtr Im;
bool is_done;
MonitoredVariable<double*> fraction_done;
bool frameready = Im->APIFunction(2.1, *is_done, fraction_done);

ERROR:
    error C2664: cannot convert argument 3 from 'MonitoredVariable<double *>' to 'double *'

what would I have to change here? thx!

reason for unknown exception in promise without lpthread

Note that this question has an 'answer' at here and here, but my question is not on how to get rid of the error, but why this error occurs.

Consider the following code:

include <cstdio>
#include <future>

int main() {
  std::promise<int> promise;
  auto future = promise.get_future();
  promise.set_value(42);

  auto result = future.get();
  printf("%d\n", result);
}

This code throws an exception:

$ g++ -g -std=c++1z main.cpp
$ ./a.out
terminate called after throwing an instance of 'std::system_error'
  what():  Unknown error -1
Aborted (core dumped)

The solution is to pass -lpthread on command line:

$ g++ -g -std=c++1z -lpthread main.cpp
$ ./a.out
42

Now, I am used to get a linking error when I don't link with a required library. This is the first time I get a runtime error.

When you run the version (without lpthread) under gdb, this is the stack trace you get (redacted some of it):

#5  0x00007ffff7aa6ef3 in __cxxabiv1::__cxa_throw (obj=obj@entry=0x61ad00,
    tinfo=tinfo@entry=0x7ffff7dce6b0 <typeinfo for std::system_error>,
    dest=dest@entry=0x7ffff7ad02b0 <std::system_error::~system_error()>)
    at /tmp/tmp.kmkSDUDFn8/build/../gcc-9.1.0/libstdc++-v3/libsupc++/eh_throw.cc:95

#6  0x00007ffff7a9d0ec in std::__throw_system_error (__i=-1)
    at /tmp/tmp.kmkSDUDFn8/build/x86_64-pc-linux-gnu/libstdc++-v3/include/ext/new_allocator.h:89

#7  0x000000000040240f in std::call_once<void (std::__future_base::_State_baseV2::*)(std::function<std::unique_ptr<std::__future_base::_Result_base, std::__future_base::_Result_base::_Deleter> ()>*, bool*), std::__future_base::_State_baseV2*, std::function<std::unique_ptr<std::__future_base::_Result_base, std::__future_base::_Result_base::_Deleter> ()>*, bool*>(std::once_flag&, void (std::__future_base::_State_baseV2::*&&)(std::function<std::unique_ptr<std::__future_base::_Result_base, std::__future_base::_Result_base::_Deleter> ()>*, bool*), std::__future_base::_State_baseV2*&&, std::function<std::unique_ptr<std::__future_base::_Result_base, std::__future_base::_Result_base::_Deleter> ()>*&&, bool*&&) (__once=..., __f=
    @0x7fffffffdd80: (void (std::__future_base::_State_baseV2::*)(class std::__future_base::_State_baseV2 * const, class std::function<std::unique_ptr<std::__future_base::_Result_base, std::__future_base::_Result_base::_Deleter>()> *, bool *)) 0x40200c <std::__future_base::_State_baseV2::_M_do_set(std::function<std::unique_ptr<std::__future_base::_Result_base, std::__future_base::_Result_base::_Deleter> ()>*, bool*)>, __args#0=@0x7fffffffdd78: 0x61ac30, __args#1=@0x7fffffffdd70: 0x7fffffffddf0,                                                                                        
    __args#2=@0x7fffffffdd68: 0x7fffffffdd67) at /.../include/c++/9.1.0/mutex:697

#8  0x0000000000401e5d in std::__future_base::_State_baseV2::_M_set_result(std::function<std::unique_ptr<std::__future_base::_Result_base, std::__future_base::_Result_base::_Deleter> ()>, bool) (this=0x61ac30, __res=..., __ignore_failure=false)                                                 
    at /.../include/c++/9.1.0/future:401

So it is something to do with call_once. Curious on why that manifests as a runtime error instead of link time.

How to get the number of words from string with c++ from maria db data

** I want to get the number of words from a string, with the data from mariadb**

but I got a warning like this: no matching function for call to

if(!qstate){
        res = mysql_store_result(conn);

        while(row = mysql_fetch_row(res)){
        string hadis = row[0];
        cout<<hadis<<endl;
        if(isspace (hadis) || ispunct (hadis))
                {
                    spasi++;
                }
            cout << "\t Jumlah Kata = "<< spasi +1 <<"\n\n";

C++ primer 5 ed. Writing a move constructor for class String

I have this exercise from C++ primer 5 ed. It asks me to add a move constructor and a move assignment operator for my class String.

  • String has pointers to character (char*). It looks like:

    class String
    {
      public:
        String(String&&) noexcept; // move constructor
        String& operator=(String&&) noexcept;// move assignment operator
    
      private:
        iterator beg_; //using iterator = char*;
        iterator end_; 
        iterator off_cap_;
        alloc alloc_; // using alloc_ = std::allocator<char>
    
    };
    

Now in implementation file I've defined the move-ctor this way:

// move constructor
String::String(String&& rhs) noexcept :
    beg_(rhs.beg_), // or beg_(std::move(rhs.beg_))?
    end_(rhs.end_),
    off_cap_(rhs.off_cap_),
    alloc_(rhs.alloc_)// or alloc_(std::move(rhs.alloc_))?
{
    std::cout << "String move-ctor\n";
    rhs.beg_ = rhs.end_ = rhs.off_cap_ = nullptr; // putting objects in a destructible valid state
        // alloc_
}
  • So should I use std::move on those members or directly? because they are Built-in Pointers to char? - The two cases give me the expected results.

  • Should I move allocator alloc_? if So, how? and what will happen to the move-from alloctor? and how can I put in a destructible valid state?

  • Excuse me for such many questions. Thank you for your efforts and time.

PS: N.B: Please don't ask me about breaking the rule of 3, 5 and 6 because for readability and brevity I've not copied it from my source.

c++ the difference between string using the assign function and directly using '=' to change the value

For example, this code

std::string a("this is a string");
std::string b;
b = a;
std::string c;
c.assign(a);

Is there any difference between B and C in essence?

C++ decltype and parentheses - why?

The subject was discussed before, but this is not a duplicate.

When someone asks about the difference between decltype(a) and decltype((a)), the usual answer is - a is a variable, (a) is an expression. I find this answer unsatisfying.

First, a is an expression as well. The options for a primary expression include, among others -

  • ( expression )
  • id-expression

More importantly, the phrasing for decltype considers parentheses very, very explicitly:

For an expression e, the type denoted by decltype(e) is defined as follows:
(1.1)  if e is an unparenthesized id-expression naming a structured binding, ...
(1.2)  otherwise, if e is an unparenthesized id-expression naming a non-type template-parameter, ...
(1.3)  otherwise, if e is an unparenthesized id-expression or an unparenthesized class member access, ...
(1.4)  otherwise, ...

So the question remains. Why are parentheses treated differently? Is anyone familiar with technical papers or committee discussions behind it? The explicit consideration for parentheses leads to think this is not an oversight, so there must be a technical reason I'm missing.

Creating a closure for std::function

I am not sure if I am using the exact terminology , But I'll try to be as descriptive as possible to clear out any confusion .

Suppose I have an std::function variable

std::function<void(int)>  callback ;

Due to some reasons beyond my scope , I cannot change the function prototype. I receive the std::function variable at some point in my code and I have to call it.Something like this :

int a = 10 // just an example value
callback(a); 

Now I have another variable . Let's name it id .

int id = rand(); // Let us assume that rand here generates a random variable
int a = 10 // just an example value
callback(a);

I want id to be accessible inside the callback i.e I am looking for some form of closure . Is there any way to do it without making the id static/global.

dimanche 23 février 2020

Time a function within a loop [closed]

I am trying to get a time breakdown of different parts of a loop. For example :-

for (i = 0; i < 1000; i++) {
    //some code
    foo(); (Total time taken by foo for all 1000 iterations)
    //some code
}

I been using gettimeofday() until now but not sure how to use chrono library or any such timer for this use case. Any help would be appreciated.

Codeblocks creates the text file in the home folder, instead of creating it in the Project folder. (Mac)

So basically, I'm using CodeBlocks 13.12 on my mac. So when I try and run this code, it creates the file (filename.txt) in my home directory. However, I need it to create the file in my project folder instead as it does in windows. (for assignment purposes) Here's a list of things I do not want: 1)No additional code can be added. 2)I don't want to add an absolute path as it would not work in Windows.

Here's what I want: I just want a setting the allows me to create the text file in my project folder instead. Mind the fact that all other files (cpp and headers) are created in the project folder. But just not this.

I've found some people addressing the same problem however, the solution wasn't much useful to me. I'm adding some links so that you can get a good idea of my problem. Feel free to ask more in the comments! http://forums.codeblocks.org/index.php?topic=21767.0 How Do I Set the Working directory on Code::Blocks on Mac?

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ofstream MyFile ("filename.txt");

    MyFile<< "Hey this is my file" << endl;

    MyFile.close();

    return 0;
}

Why does my compiler takes longer time to give me output when I try to calculate the value of pi in a C++ program

I am working on a a c++ program to calculate the value of pi using following series Pi = 4 * (1/1 – 1/3 + 1/5 – 1/7 + 1/9 … (alternating + -) (1/n)).

I am reading input from a file with following values: 12 123 1234 12345 123456 12345678 123456789 My compiler gives me instant out of for value of pi for these values. But when I try to go further than above values lets say 12345678922. it takes atleast 2 mins to get the output value. Can someone explain why it takes longer time ?

What are the advantages of c++ over c

What is oops concept in c++ I can understand every function calls happens through object which binds data member and member fuction with the help of that we can achieve (encapsulation,inheritance,abstraction,polymorphism----- I know what these concepts are but I want exact use of it where it is applied and when it is applied and what should one know to face interviews)