samedi 25 avril 2015

Bug in C++ Segment Tree Implementation?


I implemented a segment tree that seemed to work when I tested it with small inputs, but produces wrong answer when I tried to solve a problem with it. I'm sure that the bug is in the segment tree, but I can't find it. Can someone find the bug in my implementation? Code is below.

class SegmentTree
{
public:
    int* st;
    int* a;
    int length;
    SegmentTree(int* arr, int n)
    {
        length = n;
        a = arr;
        int height = (int)(ceil(log2(n)));
        int maxSize = 2 * (1 << height) - 1;
        st = new int[maxSize];
        build(0, 0, length - 1);
    }
    int f(int a, int b) // change for different problems
    {
        return max(a, b);
    }
    void build(int node, int l, int r)
    {
    if (l == r)
        st[node] = a[l];
    else
    {
        int mid = (l + r) / 2;
        build(node * 2 + 1, l, mid);
        build(node * 2 + 2, mid + 1, r);
        st[node] = f(st[node * 2 + 1], st[node * 2 + 2]);
    }

    void update(int i, int v)
    {
        update(0, 0, length - 1, i, v); //if sum query last parameter should     be v - a[i], otherwise should be v
        a[i] = v;
    }
    void update(int node, int sl, int sr, int i, int v) 
    {
        if (i < sl || i > sr)
            return;
        st[node] = f(st[node], v);
        if (sl != sr)
        {
            int mid = (sl + sr) / 2;
            update(node * 2 + 1, sl, mid, i, v);
            update(node * 2 + 2, mid + 1, sr, i, v);
        }
    }

    int query(int ql, int qr)
    {
        return query(0, 0, length - 1, ql, qr);
    }
    int query(int node, int sl, int sr, int ql, int qr)
    {
        if (sl > qr || sr < ql)
            return -1;
        if (sl >= ql && sr <= qr)
            return st[node];
        int mid = (sl + sr) / 2;
        int a = query(node * 2 + 1, sl, mid, ql, qr);
        int b = query(node * 2 + 2, mid + 1, sr, ql, qr);
        if (a == -1)
            return b;
        if (b == -1)
            return a;
        return f(a, b);
    }
};

int main()
{
    int a[] = { 4, 1, 2, 0, 6 };
    SegmentTree st(a, 5);
    cout << st.query(0, 2) << endl;
}


Error when compiling/mexing imrender function with OS X in Matlab


I am trying to use a specific function in Oliver Woodford's imrender_v2.4.zip (http://ift.tt/1IWlmDh) in Matlab, specifically the vgg_qpbo function.

The related files are supposed to recognize that a mex-file does not exist and compile one.

However, after running startup.m and trying something like

>> vgg_qpbo(1,1,1)

I get

Warning: Missing MEX-file: vgg_qpbo. Will attempt to compile and run. 
 > In vgg_mexcompile_script at 25
  In vgg_qpbo at 84 
mex -O -I"/Users/.../imrender/vgg" "-Iqpbo/" "vgg_qpbo.cxx" "qpbo/QPBO.cpp" "qpbo/QPBO_maxflow.cpp" "qpbo/QPBO_extra.cpp" "qpbo/QPBO_postprocessing.cpp"
Building with 'Xcode Clang++'.
In file included from /Users/.../imrender/vgg/vgg_qpbo.cxx:11:
In file included from qpbo/QPBO.h:116:
qpbo/block.h:124:56: warning: conversion from string literal to 'char *' is deprecated [-Wc++11-compat-deprecated-writable-strings]
                            if (!next) { if (error_function) (*error_function)("Not enough memory!"); exit(1); }
                                                                               ^
qpbo/block.h:223:56: warning: conversion from string literal to 'char *' is deprecated [-Wc++11-compat-deprecated-writable-strings]
                    if (!first) { if (error_function) (*error_function)("Not enough memory!"); exit(1); }
                                                                        ^
2 warnings generated.

ERROR while compiling vgg_qpbo
Error using vgg_mexcompile_script (line 30)
Unable to compile vgg_qpbo.

Error in vgg_qpbo (line 84)
vgg_mexcompile_script; % Compilation happens in this script

I have been trying to figure out what is the problem. The main suspect is the Mac OS X (Yosemite 10.2) I am running, as it is compilable on a Linux version (do not know which, but I could find out if you think it is relevant) my supervisor used. It is not exclusive to my computer as we tried it on another mac with the exact same result.

I believe the warnings are ignorable as they are just warnings (I am not savvy in C++, but I gathered that it is a relatively new warning, but should not affect the compilation itself).

I have also tried figuring out where in the scripts the error occurs, but the mexing-part is definitely starting, and further than that I do not feel comfortable to go.

I have mexed other scripts on this computer before and I can run for example

>> mex -setup

without a hitch.

So does anyone know what the problem might be? And thank you for your time!

I am running Matlab R2014B by the way.


Bit field memory


If i declare something like this

struct S{
  unsigned int bit:4;
}

How is it working?

  1. I allocate 2 bytes in memory(size of structure(got this size from here http://ift.tt/1a6LHjs) but use only 4 bits of it, and other memory in that structure is wasted.
  2. I allocate only 4 bits, nothing more.

I'm very confused about this and can't find any info about this anywhere.


STL SET Iterator assignment no viable candidate


I have a C++ program using an STL Set with an iterator. The set and iterator are defined as:


 set<TokenTableEntry*, Comparator> _XCLITokenTable;

 set<TokenTableEntry*>::const_iterator it;

I have a routine called findToken (shown below), that has a statement: it = _XCLITokenTable.find(_TokenTableEntry);

Which is producing the error message:

"implicit std::_Tree std::less,std::allocator,0> >::const_iterator::operator=(const
std::_Tree,std::allocator,0> >::const_iterator &)" is not a viable candidate.

I have no idea what this message is telling me or how to correct it. Can anyone make a suggestion?

Thanks for any help.

John

int XCLITokenTable::findToken (string name,  TokenTableEntry *_TokenTableEntry) 
{

    int type;
    type = -1;

    string lookupName(name);

    std::transform(name.begin(), name.end(), name.begin(), ::tolower);

    _TokenTableEntry->name = lookupName;

    **it = _XCLITokenTable.find(_TokenTableEntry);**

    if (it != _XCLITokenTable.end())
    {
        if ((*it)->name == name)
        {
            type = (*it)->type;
            tokenCount++;
            *_TokenTableEntry = *(*it);
            return type;
        }

    }
    return type;
}


Can a forwarding reference be aliased with an alias template?


This is a continuation of my previous question:

Can an identity alias template be a forwarding reference?

It seems that the following code works in both Clang 3.7.0 (demo) and GCC 6.0.0 (demo):

template <class T>
using forwarding_reference = T&&;

template <class T>
void foo(forwarding_reference<T>) {}

int main()
{
  int i{};
  foo(i);
  foo(1);
}

Are the compilers right to substitute the alias template for a forwarding reference and this could be a fancy way of writing one?


C++ and Fortran interoperability


For my own entertainment I have decided to create a large scale physics engine. I have experience with Java and C++ but none with Fortran. My understanding of Fortran is that it is used in the scientific industry and is good for large calculations. I decided to use C++ for any gui, sound, user input, etc. that might be added while Fortran would handle the calculations. How easy is it to call Fortran methods from C++? I have googled the matter and haven't found much information. Despite not knowing Fortran I am determined to learn it no matter how strict the learning curve may be (assuming that I will get an appropriate performance increase). Is it practical to use Fortran in this way? Will I get a decent performance increase (for large calculations)? Is Fortran still used in the modern world or is it outdated?


Are array memory addresses always in the order of least to greatest?


When I'm making a procedure with pointer arithmetic and !=, such as

template <typename T> void reverse_array ( T * arr, size_t n )
{
    T * end = arr + n; 
    while (arr != end && arr != --end) 
    {
         swap(arr,end);
         ++arr;
    }
}

I always take a lot of caution because if I write my procedure wrong then in a corner case the first pointer might "jump over" the second one. But, if arrays are such that

&arr[0] < &arr[1] < ... < &arr[n]

for any array arr of length n-1, then can't I just do something like

template <typename T> void reverse_array ( T * arr, size_t n )
{
    T * end = arr + n;
    if (arr == end) break;
    --end;
    while (arr < end)
    {
        swap(arr,end);
        ++arr; --end;
    }
}

since it's more readable? Or is there a danger looming? Aren't memory addresses just integral types and thus comparable with < ?


I want to know how to perform input and output operations in C#


I want to know how to perform input and output operations in C#.I know C++ but I want to write a code in C. This is the basic code in C++ I want to write the same thing using C language.

    #include<iostream.h>
    #include<conio.h>
    void main()
    {
    clrscr();
    char name;
    cout<<"\n Enter name";
    cin>>name;
    cout<<"Hello!!"<<name<<": \t ";
    getch();
    }


CMake. Create coverage target


Sorry for such popular question. But I can't correspondingly apply answers from here to my environment.

I have api and tests to it. Both are subprojects to main "dummy" project. I stuck because I used CMake-anitpattern:

cmake_minimum_required (VERSION 2.8)
set(CMAKE_SKIP_RPATH FALSE)
add_subdirectory ( src )
add_subdirectory ( test )

add_custom_target(coverage
    COMMAND make
    COMMAND sh ${CMAKE_SOURCE_DIR}/do_coverage.sh
)

That COMMAND make is bad solution because I planning to build my project on Windows later (yep, I need put commands from sh-script in CMakeLists.txt for this purpose too).

So, how can I let CMake to build test project in automatic mode for doing coverage things (gcov, gcovr) even if after cmake I want to make coverage straightway? Thanks!


Passing MyClass defined in header as function argument to other file


I've spent around an hour and couldn't find anything helpful on the Web. The problem is that I've got some files like a.h, b.h, a.cpp, b.cpp and main.cpp. In a.h I've got declared a container with attributes defined by myself. I would like to pass this container as and argument to the function in b.h/b.cpp. What is the way of doing this?

a.h file

struct Container{
int size;
int* array
...};

b.cpp

void someFunction(Container container)
{...}

Thanks for any help.


Transmitting/receiving a bitmap with .NET Sockets C++/CLI


Im programming for my Schoolproject an Internet/Multiplayer based Drawing Game. So now i need to Program a PictureBox which is always actual with the Servers one.

First of all im using a .net TCP Client and Listener which already works(Im sending and receiving some strings). I have 2 static classes which represents the Server and the client.

My basic idea is to Convert the bmp from the PictureBox in a Byte[] transmitt it with a BinaryReader thru a NetworkStream.

On the Other Side the received Byte[] will be converted back to a bmp and goes into the PictureBox.

here my are my two Functions:

void Server::sendBMP(Bitmap^ bmp){
    array<Byte>^bytes = gcnew array<Byte>(256);
    BinaryWriter^ bw = gcnew BinaryWriter(stream);
    MemoryStream^ ms = gcnew MemoryStream(); 

    bmp->Save(ms,System::Drawing::Imaging::ImageFormat::Bmp); //Conversion from BMP to Byte[]
    bytes = ms->ToArray();  

    bw->Write(bytes);}


Bitmap^ Server::receiveBMP(void){
    array<Byte>^buffer = gcnew array<Byte>(10000);
    BinaryReader^ br = gcnew BinaryReader(stream);
    Bitmap^ bmp = gcnew Bitmap(1500,612);

    buffer = br->ReadBytes(10000);

    MemoryStream^ ms = gcnew MemoryStream(buffer); // Conversion From Byte[] to BMP
    bmp->FromStream(ms);

    return bmp;}

Im always getting a "System.ArgumentException" Error.

Im using synchronous TCP sockets. Is this the right Way im doing this?

Stack trace:

Server::receiveBMP() line 105 + 0x8 Bytes  
DrawMyThing::MyForm::streamIMG() line 2774 + 0x6 Bytes

line 105:

bmp->FromStream(ms);  //From my Server::receiveIMG()

line 2774:

private: static void streamIMG(void){
            while(1){    
             if(status==1){ //If Server
                     bitmap = Server::receiveBMP(); //line 2774

                 }else{
                     Client::sendBMP(bitmap);
                 }
            }
         }

BTW im calling this streamIMG function as a thread:

Thread^ imgstreamthread = gcnew Thread(gcnew ThreadStart(MyForm::streamIMG));
             imgstreamthread->Start();


while(getline(myReadFile, temp, ':')) executing one iteration too many causing out of bounds on vector


I have a question on std::readline(istream, string, delimiter). I am trying to read in a file and store the data in a struct and add it to a map. That I have gotten to work. However my while loop iterates one loop too many causing my vector to have no data stored in it which causes an assertion failure for out of bounds.

I have read every stack overflow question on readline and none seem to give me any idea as to why this behavior occurs. Perhaps someone here can enlighten me.

if (myReadFile.is_open()) {
    while(getline(myReadFile, temp, ':')){//loops through and splits the line one delimiter at a time
        stringVector.push_back(temp);//add to vector
        ItemInfo tempItem = ItemInfo(stringVector[1], stod(stringVector[2]), stod(stringVector[3]));//create the struct
        catalog.insert(pair<string,ItemInfo>(stringVector[0], tempItem));//add to map
        stringVector.clear();
    }

}

    myReadFile.close();

Thanks for any help


Suggestions on C++ Inheritence


I have been implementing the Red Black Trees in C++ using inheritence. I have 4 Classes, Node, Tree, RBNode, RBTree.

class Node
{
    protected:
        int data;
        Node *left;
        Node *right;
        Node *parent;
    public:
        Node();
        Node(int data);
        void print_node(ofstream &file);
        Node * find_node(int data);
        void insert_node(Tree *t);
        void left_rotate_node(Tree *t);
        void right_rotate_node(Tree *t);
        void delete_node(Tree *t);
}

class Tree
{
    protected:
        Node * root;
        list<int> treedata;
    public:
        Tree();
        virtual Node * get_root();
        virtual void set_root(Node *root_node);
        void insert_into_tree();
        void delete_from_tree();
        virtual void print_tree();
}

RBNode and RBTree inherit Node, Tree respectively. But I am not able to use the functions of the Node class. For example, the function void Tree::insert_node(Tree *t);

Even in the class RBNode, this function does the same work except that the funntion receives RBTree as the parameter. How can I make use of the same function without redeclaring it in RBNode. I thought of using casting inside function, but how will I know which classes object is calling the function.

Please give me some suggestions. I am new to C++.


Using library file built by different IDE


I'm trying to use KDL.

KDL is a library for computing kinematics and dynamics of robot maniputlator.

I built KDL with Visual Studio 2010.

I got orocos-kdl.lib successfully.

And I can use this library file in VS2010 but cannot use it in another IDE(CLion) with this error undefined reference to ....

But the same code can be built in VS2010.

A library file, built by different IDE, cannot be used?

If I built it by VS2010, I can use it only in VS2010?

Thank you.


How to make a list C++


So I have to make a program that stores input piece by piece, until -1 is input. An example of this input would be 1 1 1 0 3 5 3 -1. And -1 would not be recorded. Then it plays the list back to you, but bacwards, so output would be 3 5 3 0 1 1 1

To do this I need to make a list of objects, but I have no clue how to declare them, or how to add/remove items to them. how do I do this?


Reversing a word : C++


I want to reverse a char string in c++. I wrote this code:

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

using namespace std;

int main(){
    char word[80] = "polymorphism";
    char rev[80];
    int i, j;
    int l;
    l = strlen(word);
    for(i = 0, j = l; i < l-1; i++, j--){
        word[j] = rev[i];
    }
    cout << rev << endl;
    return 0;
}

In terminal it shows some characters like this:

83???uH??? ... Something like this


String Parsing in C++


I want to write a program which gets a formula like sin(20) + cos(20) + sqrt(59) from users and then show me the result of the calculation. How can i implement this program in c++?


How smart pointer weak_ptr is bound to shared_ptr in this case?


Here is an exercise from C++ Primer 5th Edition:

Exercise 12.20: Write a program that reads an input file a line at a time into a StrBlob and uses a StrBlobPtr to print each element in that StrBlob.

class StrBlob
{
    friend class StrBlobPtr;
public:
    StrBlob(): data(make_shared<vector<string>>()) { }
    StrBlob(initializer_list<string> il): 
        data(make_shared<vector<string>>(il)) { }
    int size() const { return data->size(); }
    bool empty() const { return data->empty(); }
    void push_back(const string& t) { data->push_back(t); }
    void pop_back();

    string& front();
    string& back();

    StrBlobPtr begin();
    StrBlobPtr end();
private:
    shared_ptr<vector<string>> data;
    void check(int i, const string& msg) const;
};

class StrBlobPtr
{
public:
    StrBlobPtr(): curr(0){ }
    StrBlobPtr(StrBlob &a, size_t sz = 0):
            wptr(a.data), curr(sz) { }
    string& deref() const;
    StrBlobPtr& incr();
private:
    shared_ptr<vector<string>> check(size_t i, const string& msg) const;
    weak_ptr<vector<string>> wptr;
    size_t curr;
};

StrBlobPtr StrBlob::begin() 
{
    return StrBlobPtr(*this); 
}

StrBlobPtr StrBlob::end()
{
    return StrBlobPtr(*this, data->size());
}

I don't understand in how smart pointer wptr is bound to the data member of StrBlob in StrBlobPtr StrBlob::begin by calling the default constructor function.

While in StrBlobPtr StrBlob::end(), StrBlobPtr(StrBlob &a, size_t sz = 0):wptr(a.data), curr(sz) { } is called explicitly and wptr is bound to a.data.


Cannot connect slots from another class


I currently try to write an little application for experiments and more. I write everything in its own file (Menu -> menu.cpp etc.). Now I want to create a menu action, this works but interacting with the action doesnt. Thats what I've done so far:

menu.cpp

#include "menu.h"
#include <QMenuBar>
#include <QMenu>
#include <QAction>


void Menu::setupMenu(QMainWindow *window) {
    QMenuBar *mb = new QMenuBar();
    QMenu *fileMenu = new QMenu("File");
    QAction *newAct = new QAction("New...", window);
    window->connect(newAct, SIGNAL(triggered()), this, SLOT(newFile()));
    fileMenu->addAction(newAct);
    mb->addMenu(fileMenu);
    window->setMenuBar(mb);
}

void Menu::newFile() {
    printf("hello world!");
}

menu.h

#ifndef MENU_H
#define MENU_H

#include <QObject>
#include <QMainWindow>
#include <QWidget>
#include <QMenuBar>

class Menu : public QObject
{
public:
    void setupMenu(QMainWindow *window);
private slots:
    void newFile();
};

#endif // MENU_H

But its not printing out 'hello world', the only message I get is:

QObject::connect: No such slot QObject::newFile() in ../from Scratch written UI app C++/src/ui/menu.cpp:11

What can I do to fix this?

~ Jan


Converting this C++ for loop into assembly language


I am having trouble understanding how I would convert a couple of lines of code from my simple encryption program into assembly language, mainly the FOR loop. Could anyone give me any pointers on how to achieve this? I understand I can create a breakpoint and look at it in asm when it is running but it points to specific memory locations and such, and I am wondering how I would write it myself.

This is part of my program including the lines I need to convert into assembly.

void encrypt_chars(int length, char EKey)   // Encryption Function.

{
char temp_char;                         // Char temporary store.    
for (int i = 0; i < length; i++)        // Encrypt characters one at a time.
{
    temp_char = OChars[i];              // Orignal Chars.

    __asm {                                 // Switch to inline assembly.

            push   eax                  
            push   ecx                  

            movzx  ecx, temp_char       
            push   ecx                  
            lea    eax, EKey            
            push   eax                  
            call   encrypt4             
            add    esp, 8               
            mov    temp_char, al        

            pop    ecx                  
            pop    eax          

      EChars[i] = temp_char;                
}
return;

Thank you.


What is the right way to overload the plus operator?


I have set of classes:

class A 
{
public:
    A(B b) {//..}   
    A(C C) {//..}
    A(D D) {//..}

    A& operator+=(A const& ls) {//..}
    A operator+(A const& ls) const {//..}
}

class B
{
//....
}

class C
{
//....
}

class D
{
//....
}

I want to support the following operations:

1) A result = a1 + a2;
2) a1 += a2;
3) A result = b1 + a1; (and C, D classes instead of B)
4) A result = a1 + b1; (and C, D classes instead of B)
5) a1 += b1; (and C, D classes instead of B)

How to do in this case? I would not want to use boost.


How to detect internet connection state with Qt 5.4 on OS X Yosemite 10.10.3?


I'm trying to check the internet connection state with Qt 5.4 on OS X Yosemite 10.10.3, but every time I run the code the result is connected, although I'm not connected to anything.

bool NetworkAccessManager::currentConnectivityStatus()
{
    QNetworkAccessManager *namanager = new QNetworkAccessManager(this);
    switch (namanager->networkAccessible()) {
    case QNetworkAccessManager::UnknownAccessibility:
        kdebug() << Q_FUNC_INFO << "QNetworkAccessManager::UnknownAccessibility";
        break;
    case QNetworkAccessManager::NotAccessible:
        kdebug() << Q_FUNC_INFO << "QNetworkAccessManager::NotAccessible";
        break;
    case QNetworkAccessManager::Accessible:
        kdebug() << Q_FUNC_INFO << "QNetworkAccessManager::Accessible";
        break;
    default:
        break;
    }

    QNetworkConfigurationManager manager;
        kdebug()<< Q_FUNC_INFO << " network connection " << manager.isOnline();

    QNetworkConfiguration cfg = manager.defaultConfiguration();
    QNetworkSession *session = new QNetworkSession(cfg);
    session->open();
    session->waitForOpened();

    if(session->isOpen())
    {
        switch (session->state()) {
        case QNetworkSession::Connected:
            kdebug() << Q_FUNC_INFO << "QNetworkSession::Connected";
            break;
        case QNetworkSession::Disconnected:
            kdebug() << Q_FUNC_INFO << "QNetworkSession::disconnect";
            break;
        default:
            break;
        }
    }
}

And here is the result for all the above when i disconnect everything

DEBUG 2015-04-25T16:00:59.560 bool NetworkAccessManager::currentConnectivityStatus() QNetworkAccessManager::Accessible 
DEBUG 2015-04-25T16:00:59.560 bool NetworkAccessManager::currentConnectivityStatus()  network connection OK  true 
DEBUG 2015-04-25T16:00:59.560 bool NetworkAccessManager::currentConnectivityStatus() QNetworkSession::Connected 


Template base type inheritance


I have an classes:

class Box{...};
class MyBox : public Box{...};

And an template:

template <type T>
class ObjectManager{...};

Which I use in some other class:

class Engine{
    ObjectManager<Box> * manager = nullptr;
    ...
};

Then I extend (implement) the Engine interface:

class MyEngine : public Engine{...}

And in that implementation (not earlier!) I know that manager should be like that:

MyEngine::MyEngine(){
    manager = new ObjectManager<MyBox>();
}

But this gives me an error because of types conflict (conversion between ObjectManager<Box> and ObjectManager<MyBox>), even when MyBox inherits from Box.

Is there any way around that problem? I don't want to modify the Box, MyBox, ObjectManager and Engine classes.


Conversion function from std::bind


I am receiving an error when I create a new function from another using std::bind and trying to pass it to another function.

My code looks like

#include <functional>
using namespace std;
typedef double (*t_function)(double t, double *y);

double integrate_fmax(double s, bool(*t_max)(double t, double *y), void(*fce_min)(double s, double &t_0, double *y_0), t_function fce_max, double err, t_function *f_diff, int dim){...}

get_x1_x2(double &x1, double &x2, double(*fce)(double x), double mlt){...}

double shoot_meth(double s1, double mlt, bool(*t_max)(double t, double *y), void(*fce_min)(double s, double &t_0, double *y_0), t_function fce_max, double err, t_function *f_diff, int dim){
    double s2;  
    auto fce_x = bind(integrate_fmax, placeholders::_1, t_max, fce_min, fce_max, err, f_diff, dim);
    get_x1_x2(s1, s2, fce_x, mlt);
}

I am receving error when I try pass function fce_x to get_x1_x2:

IntelliSense: no suitable conversion function from "std::_Bindconst)(double, bool ()(double t, double y), void ()(double s, double &t_0, double *y_0), t_function, double, t_function , int), std::_Ph<1> &, bool (&)(double t, double y), void (&)(double s, double &t_0, double *y_0), t_function &, double &, t_function &, int &>" to "double ()(double x)" exists

But when I tried something like double foo = fce_x(5) I get no error.

I am using Microsoft Visual Studio 2013.

P.S. Sorry for ugly functions but I am not sure where is the error and that simplifying would help.


WINAPI URLDownloadToFileA Problems


i'have used the microsoft WINAPI syntax from http://ift.tt/1HD4fsT

so there is my code

#include <windows.h>

#pragma comment(lib, "urlmon.lib")

HRESULT URLDownloadToFileW( FALSE, "http://ift.tt/1Gt7qAl", "C:\\psych0bOx.png", 0, NULL);

when i try to compile it with msvs 12.0 i'get these errors:

C:\>cl C:\URLDownloadToFileA.cpp

C:\URLDownloadToFileA.cpp(8) : error C2365: 'URLDownloadToFileA' : redéfinition ; la précédente définition était 'fonction' C:\Program Files\Windows Kits\8.1\include\um\urlmon.h(4780) : voir la déclaration de 'URLDownloadToFileA' C:\URLDownloadToFileA.cpp(8) : error C2078: initialiseurs trop nombreux

C:\>

i dont understand why i get therse errs i'm completely blocked here :x


Coapp / autopkg : multiple include folders in /build/native/include/


I am trying to build a nuget package via CoApp tool for c++. The package needs to embed 3 folders when compiling a cpp using it.

So, I want an internal include structure as following :

/build/native/include/lib1, /build/native/include/lib2, /build/native/include/lib3

My question: how to add several include folders in /build/native/include/

I tryied :

Multiple blocs of (varying lib1, lib2, lib3):

    nestedInclude += 
    { 
        #destination = ${d_include}lib1; 
        ".\lib1\**\*.hpp", ".\lib1\**\*.h"
    };

Multiple blocs of (varying lib1, lib2, lib3):

    nestedInclude 
    { 
        #destination = ${d_include}lib1; 
        ".\lib1\**\*.hpp", ".\lib1\**\*.h"
    };

but it seems coapp accumulates the .h/.hpp files among the blocs (depending of operator += or not) and at the end, add all of them to the last #destination tag value. So I get an unique entry : /build/native/include/lib3


Runtime Error when trying to submit an answer to URI online judge (C++)


My code works fine on Visual Studio but when i try to submit my code to URI i get runtime error...here's the link for the problem i am trying to slove hope this helps & thx in advance http://ift.tt/1DKv8nA

    #include <iostream>
using namespace std;
class LostBoots{
public:
    void intSwap(int *element1, int *element2){
        int temp = *element1;
        *element1 = *element2;
        *element2 = temp;
    }
    void charSwap(char *element1, char *element2){
        char temp = *element1;
        *element1 = *element2;
        *element2 = temp;
    }
    void sort(int arr[], char arcr[], int length){
        for (int i = 0; i < length - 1; i++){
            for (int j = i + 1; j < length; j++){
                if (arr[i] > arr[j]){
                    intSwap(&arr[i], &arr[j]);
                    charSwap(&arcr[i], &arcr[j]);
                }
            }
        }
    }
};
int main(){
    int N, M[60], count;
    char L[60];
    LostBoots boot;
    while (cin >> N){
        count = 0;
        for (int i = 0; i < N; i++){
            cin >> M[i] >> L[i];
        }
        boot.sort(M, L, N);
        for (int i = 0; i < N; i++){
            if (i % 2 == 0){
                if (M[i] == M[i + 1] && L[i] != L[i + 1])
                    count++;
            }
        }
        cout << count << endl;
    }
    return 0;
}


not correct print with unchar Mat for image 8UC1 c++


Could help somebody please ? I have an image after Canny detector, the type is 8UC1, when i want to access to the values, cout gives to me ? (Test Canny�), so my code is following:

Mat src;

/// Load an image
src = imread( argv[1] );

if( !src.data )
{ return -1; }

Mat src_gray(src.size[1],src.size[2],CV_8U,0);      

//some parameters

int edgeThresh = 1;
//int lowThreshold;
int lowThreshold = 100;
int const max_lowThreshold = 100;
int ratio = 3;
int kernel_size = 3;
//char* window_name = "Edge Map";

  cvtColor( src, src_gray, CV_BGR2GRAY );

  Mat detected_edges;
  /// Reduce noise with a kernel 3x3
  blur( src_gray, detected_edges, Size(3,3) );


  ///Canny edge detection
  Canny( detected_edges, detected_edges, lowThreshold, lowThreshold*ratio, kernel_size );


  for (unsigned int i=0;i<detected_edges.size[1];i++){
    for  (unsigned int j=0;j<detected_edges.size[1];j++) {
        if (detected_edges.at<unsigned char>(i,j)!=0)
            cout<<"Test Canny"<<detected_edges.at<unsigned char>(i,j)<<endl;
    }
}

When I change in short, i.e. (i,j), it gives to me value between -256 and 255. I do not understand why with the type 8UC1, i need to use short and is it correct to use short ? (To verify surely which type I have, I used this link how to find out what type of a Mat object is with Mat::type() in OpenCV) Thanks.


Why should "case statement" be constant?


In JavaScript the following statement is valid.

switch(true) {
    case a > b:
        max = a;
        break;
    case a < b:
        max = b;
        break;
    default:
       max = a;
}

But in C/C++ language, when I write this statement, compiler gives me an error showing case statement must be consist of constant values. Sometimes in particular circumstances writing such switch-case statements would be very useful, but C/C++ will not allow me to do so.

Now I am curious to know what is the point behind this to not allowing variable values to be used in case statements?


Exporting a visual studio c++ project for use in another project, without revealing the .cpp and .h source files


I have a visual studio project called

"TopSecretProject"

that I want to share with an anonymous developer user, without revealing any of my code, including the header files (Since my .h files include the structure of my project ant the user cannot know about it).

The user should receive:

  1. A list of function names that he may call (depending on the permissions that the user has) and the user should be able to develop a program using these functions as black boxes.
  2. My sealed TopSecretProject, that he cannot open.

Is this scenario possible in any way?

I tried the following solution but failed:

  1. Exporting TopSecretProject as a static library.
  2. Creating a new VS project for the user, and adding the .lib to the user project.
  3. Copying all the .h files to the user's project and creating a pre compiled header file.
  4. removing the headers (now that I have the .pch I don't need them anymore)

The pre compiled header is rebuilt in any run and thus removing my first pre built pch... I also tried to copy the pch directly from the TopSecretProject but it didn't help.

Thanks very much in advance!!


Save a float into an integer without losing floating point precision


I want to save the value of f in the third element of the array named i in a way that the floating point part isn't wiped (i.e. we don't want to save 1 instead of 1.5). After that, complete the last line in a way that we see 1.5 in the output (don't use cout<<1.5; or cout<<f; or some similar tricks!)

float f=1.5;
int i[3];
i[2] = ... ;
cout<<... ; 

Does anybody have any idea?

Note: I know this is not a typical, but this is a question of my Advanced C++ Programming course midterm exam!


Confusion about compile-time pointer values


C++ has compile-time pointer values. This is true, otherwise, non-type template parameters and constexpr won't work with pointers. However, as far as I know, addresses of functions and objects of static storage are known (at least) at link-time rather than compile-time. Following is an illustration:

main.cpp

#include <iostream>

template <int* p>
void f() { std::cout << p << '\n'; }

extern int a;

int main() {
    f<&a>();
}

a.cpp

int a = 0;

I'm just wondering how the address of a could possibly be known when compiling main.cpp. I hope somebody could explain this a little to me.

PLUS: This mechanism seems to be rather robust. Even when I enabled Randomized Base Address, the correct output is obtained.


C++ class dll with CUDA member?


I have a C++ class-based dll. I'd like to convert some of the class members to CUDA based operation.

I am using VS2012, WINDOWS 7, CUDA6.5, sm_20;

Say the original SuperProjector.h file is like:

class __declspec(dllexport) SuperProjector 
{
public:
    SuperProjector(){}; 
    ~SuperProjector(){};
    void sumVectors(float* c, float* a, float* b, int N);
};

and the original sumVector() function in SuperProjector.cpp

void SuperProjector::sumVectors(float* c, float* a, float* b, int N)
{
    for (int n = 1; n < N; b++)
        c[n] = a[n] + b[n];
}

I am stuck on how I should convert sumVector() to CUDA. Specifically:

  1. I read some posts saying add __global__ __device__ keywords in front of class members will work, but so I need to change the suffix of the cpp file to cu?
  2. I also tried to create a cuda project from the beginning, but it seems VS2012 does not give me the option of creating a dll once I chose to create a CUDA project.

I am very confused what is the best way to convert some of the members of tthis C++ class based dll into some CUDA kernel functions. I appreciate anyone can offer some ideas, or better with some very simple examples.


C++: Why is my vector not returning the median? [duplicate]


This question already has an answer here:

I need to take the median of a sorted vector for a homework assignment. I have tried a few different ways but I'm not sure how to properly tell the program to take the median. I have tried things like taking the size and dividing it by 2 then rounding up and attempting to return data[i] at this position, but with no success. This is where I'm at (does not compile). Any help will be well appreciated.

#include <iostream>
#include <stdlib.h>
#include <vector>
#include <cmath>

using namespace std;

void bubbleSort(vector<int>& data)
{
    if(data.size() <= 1)
        return;

    for(int i=1; i<data.size(); i++)
    {
        for(int j=0; j<data.size()-i; j++)
        {
            if(data.at(j) > data.at(j+1))
            {
                int temp = data.at(j+1);
                data.at(j+1) = data.at(j);
                data.at(j) = temp;
            }
        }
    }
}

int main()
{
    int n;
    vector<int> data;

    cout << "Vector Length?: ";
    cin >> n;

    // Filling vector
    for(int i=0; i<n; i++)
        data.push_back(rand()%10+1);

    cout << "Vector: ";
    for(int i=0; i<data.size(); i++)
        cout << data.at(i) << ", ";

    // Sorting
    bubbleSort(data);

    cout << endl << "Sorted Vector: ";
    for(int i=0; i<data.size(); i++)
        cout << data.at(i) << ", ";




    //Average & Median
    //average = accumulate(data.begin(), data.end(), 0.0)/data.size();
    double median = 0.0;
    if (data.size() % 2)
    {
        cout<<endl;
        cout<<"Vector is odd"<<endl;
        median = data.end(i/2);
        cout<<"Median: "<<median<<endl;



    }
    else{
        cout<<"Vector is even"<<endl;
        median = ((data.size()/2.0-1.0) + (data.size()/2.0+1.0)/2.0);
        cout<<"Median: "<<median<<endl;


    }




    system ("pause");

    return 0;





}


C++ 11 - Is moving non local variable safe?


Say I have a function which goes like:

void a_fct( std::vector<double> &some_vector )
{
  std::vector<double> a_temporary_vector = some_vector;

  ... some stuff involving only a_temporary_vector ...

  some_vector = a_temporary_vector;
}

which is of course a bit silly, but it is just intended as bringing the following general questions:

  • It seems to me that one should rather move a_temporary_vector into some_vector here, as it then goes out of scope. But is it safe to move some_vector into a_temporary_vector rather than copying ?

  • Imagine now that somewhere else in the code, I have a pointer to the vector given as argument here. Is this pointer still pointing to it if I move some_vector into a_temporary_vector ?

In both cases, can I expect it to be true for any STL implementation ?


Unavailable Ui properties


I've been trying to implement a project in C++ using Qt Creator – this is Qt Creator 3.3.1 (opensource) based on Qt Creator 5.4.1. I use Ubuntu 14.04. I've found some tutorials of which the subject was simillar to what I wanted to create, so I've been studying the code and trying to fit it to my needs. This is the GUI Project. I've been also dealing with this project to learn more C++, OOP. I did 2 forms. This project consists for now from 3 classes. One class includes a form to gather some information about persons – it works. The main class includes QtableWidget to present the details about the persons from the database in the table, I also implemented the method to find persons (also in the main class), searching by Surnames – in form I used QlineEdit to do it. But there should be also a form to edit the information about the strict person. I decided to implement this form to edit those information in another class. There occured the problem, because to edit the information about the strict person, I need to be able to read what I typed into the gap of QlineEdit and then to make a search in the database using this information ( from the QlineEdit which is included in the form of the main class). The problem is, that in the second class (to edit) when I use a construction in the constructor as: QString Surname = ui->name_of_the_gap->text(); - where „name_of_the_gap” is the name of the gap which includes the surname that I want to use but it occures to be unavailable for this ui (the ui in the class in which there is this form to edit infomation). I have tried to use inheritance ( I have googled through the Internet to get to know something more about this problem ) but non of it works. Could I please ask you to direct me / point me out how should I do it / what should I change?

Below I will present you the pieces of the code:


 1. Headers:

 **/*addrecord.h*/**


#ifndef ADDRECORD_H
#define ADDRECORD_H
#include <QDialog>
#include <QtSql/qsqldatabase.h>
#include <QtSql/QSqlError>
#include <QtSql/QSql>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlDriver>
#include <QtSql/qsqldriver.h>
#include <QtSql/QSqlDriverPlugin>
#include <QtSql/qsqldriverplugin.h>
#include <QSqlQuery>
#include <QDebug>
#include <QString>
#include <QMessageBox>
namespace Ui {
class AddRecord;
}
class AddRecord : public QDialog
{
    Q_OBJECT
public:
    explicit AddRecord(QWidget *parent = 0);
    ~AddRecord();
private slots:
    void on_btnQuit_clicked();
    void on_btnAdd_clicked();
private:
    Ui::AddRecord *ui;
};

 **/*addrecord.h*/**

<pre>


<pre>
    **/*editrecord.h*/**

#ifndef EDITRECORD_H
#define EDITRECORD_H
#include <QDialog>
//#include "mainwindow.h"
//#include "addrecord.h"
#include <QLineEdit>
namespace Ui {
class EditRecord;
}
class EditRecord : public QDialog
//class EditRecord :  public MainWindow
{
    Q_OBJECT
public:
    explicit EditRecord(QWidget *parent = 0);
    ~EditRecord();
    Ui::EditRecord *eui;
private slots:
    void on_btnQuit_clicked();
private:
    //Ui::EditRecord *ui;
    //Ui::EditRecord *ui;
    //Ui::MainWindow *mui;
    QLineEdit *searchSurnameEdit;
};
#endif // EDITRECORD_H

      **/*editrecord.h*/**


    /*mainwindow.h*/
enter code here
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include "addrecord.h"
#include "editrecord.h"
#include <QMainWindow>
#include <QtCore>
#include <QtGui>
#include <QSql>
#include <QtSql/qsqldatabase.h>
#include <QtSql/QSqlError>
#include <QtSql/QSql>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlDriver>
#include <QtSql/qsqldriver.h>
#include <QtSql/QSqlDriverPlugin>
#include <QtSql/qsqldriverplugin.h>
#include <QSqlQuery>
#include <QDebug>
#include <QSqlRecord>
#include <QSqlTableModel>
#include <QModelIndexList>
#include <QTableView>
#include "editrecord.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    Ui::MainWindow *ui;
    void fillTable();
private slots:
    void on_tableWidget_cellChanged(int row, int column);
    void on_btnQuit_clicked();
    void on_btnAdd_clicked();
    void on_btnSearchSurname_clicked();
    void on_btnEditData_clicked();
private:
    bool loading;
    //Ui::MainWindow *ui;
    QStandardItemModel *model;
    QSqlDatabase *myDb;
    QSqlTableModel *empmodel;
    QItemSelectionModel *selection;
    QTableView *view;
    QModelIndexList indexes;
    QSqlQuery *q;
    //EditRecord *editrecord;
};
#endif // MAINWINDOW_H


     **/*mainwindow.h*/**


 **Sources:**

   **/*addrecord.cpp*/**

  #include "addrecord.h"
#include "ui_addrecord.h"
AddRecord::AddRecord(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::AddRecord)
{
    ui->setupUi(this);
}
AddRecord::~AddRecord()
{
    delete ui;
}
void AddRecord::on_btnQuit_clicked()
{
    this->close();
}
void AddRecord::on_btnAdd_clicked()
{
    QSqlDatabase db1 = QSqlDatabase::addDatabase("QMYSQL");
    db1.setHostName("localhost");
    db1.setDatabaseName("dbname");
    db1.setUserName("user");
    db1.setPassword(„passwd");
    db1.open();
    QString gkUserid,name,second_name,surname,date_of_birth,NIP,street,postalcode,desc,telefhone,mobile_phone,email,sex,city;
    name = ui->nameEdit->text();
    second_name = ui->secondNameEdit->text();
    surname = ui->surnameEdit->text();
    date_of_birth = ui->dateofBirthEdit->text();
    NIP = ui->nipEdit->text();
    street = ui->streetEdit->text();
    postalcode = ui->postalCodeEdit->text();
    desc = ui->descEdit->acceptRichText();
    telefhone = ui->telephoneEdit->text();
    mobile_phone = ui->mobilePhoneEdit->text();
    email = ui->eMailEdit->text();
    sex = ui->sexEdit->text();
    city = ui->cityEdit->text();
    if(!db1.open()){
        qDebug()<<"Failed to open database";
        return;
    } else {
        qDebug()<<"OK";
    }
    QSqlQuery query("qt_mysql");
    query.prepare("INSERT INTO gkUsers VALUES (:gkUserid,:name,:second_name,:surname,:date_of_birth,:NIP,:street,:postal_code,:desc,:telephone,:mobile_phone,:email,:sex,:city)");
    query.bindValue(":name",name);
    query.bindValue(":second_name",second_name);
    query.bindValue(":surname",surname);
    query.bindValue(":date_of_birth",date_of_birth);
    query.bindValue(":NIP",NIP);
    query.bindValue(":street",street);
    query.bindValue(":postal_code",postal_code);
    query.bindValue(":desc",desc);
    query.bindValue(":telephone",telephone);
    query.bindValue(":mobile_phone",mobile_phone);
    query.bindValue(":email",email);
    query.bindValue(":sex",sex);
    query.bindValue(":city",city);
    if(query.exec()){
        QMessageBox::critical(this,tr("Save"),tr("Saved"));
        db1.close();
        ui->nameEdit->setText("");
        ui->secondNameEdit->setText("");
        ui->surnameEdit->setText("");
        ui->dateofbirthEdit->setText("");
        ui->nipEdit->setText("");
        ui->streetEdit->setText("");
        ui->postalCodeEdit->setText("");
        ui->descEdit->acceptRichText();
        ui->telephoneEdit->setText("");
        ui->mobilephoneEdit->setText("");
        ui->eMailEdit->setText("");
        ui->sexEdit->setText("");
        ui->cityEdit->setText("");
    } else {
        QMessageBox::critical(this,tr("Error"),query.lastError().text());
    }
}

   **/*addrecord.cpp*/**



   **/*editrecord.cpp*/**


#include "editrecord.h"
#include "ui_editrecord.h"
#include "mainwindow.h"
EditRecord::EditRecord(QWidget *parent):
        // MainWindow(),
       QDialog(parent),
    //eui(new Ui::EditRecord), MainWindow(parent)
       eui(new Ui::EditRecord)
{
    eui->setupUi(this);
    //ui->setupUi(mui->placeholder);
   // EditRecord(Ui::MainWindow *ui)
    //QString Surname = ui->szukajNazwiskoEdit->text();
   // eui->setupUi(ui.placeholder);
}
EditRecord::~EditRecord()
{
    delete eui;
}
void EditRecord::on_btnZamknij_clicked()
{
    this->close();
}

    **/*editrecord.cpp*/**


    **/*main.cpp*/** 

#include "mainwindow.h"
#include "editrecord.h"
#include <QApplication>
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    EditRecord e; //added
    w.show();
    return a.exec();
}         

     **/*main.cpp*/** 


    **/*mainwindow.cpp*/**

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "addrecord.h"
#include <QSql>
#include <QtSql/qsqldatabase.h>
#include <QtSql/QSqlError>
#include <QtSql/QSql>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlDriver>
#include <QtSql/qsqldriver.h>
#include <QtSql/QSqlDriverPlugin>
#include <QtSql/qsqldriverplugin.h>
#include <QSqlQuery>
#include <QString>
MainWindow::MainWindow(QWidget *parent) :    
     QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QSqlDatabase myDb = QSqlDatabase::addDatabase("QMYSQL");
    myDb.setHostName("localhost");
    myDb.setDatabaseName("db");
    myDb.setUserName("user");
    myDb.setPassword("passwd");
    myDb.open();
    qDebug()<<myDb.open();
    ui->tableWidget->hideColumn(0);
    fillTable();
}
MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::fillTable()
{
    loading = true;
    int num_rows, r, c;
    //QSqlQuery q(myDb);
    QSqlQuery q;
    //get the number of rows
    if(!q.exec("SELECT count(gkUserid) as num_rows FROM gkUsers")) qDebug()<< q.lastError().text();
    q.first();
    num_rows = q.value(0).toInt();
    ui->tableWidget->setRowCount(num_rows);
    ui->tableWidget->setMaximumWidth(1700);
    ui->tableWidget->setMaximumHeight(300);
    if(!q.exec("SELECT gkUserid, name, second_name, surname, date_of_birth, NIP, street, postalcode, desc, telephone, mobile_phone, email, sex, city FROM gkUsers ORDER BY gkUserid")) qDebug() << q.lastError().text();
    for(r = 0, q.first(); q.isValid(); q.next(), ++r)
    {
       //for(c = 0; c < q.numRowsAffected(); ++c)
       for(c = 0; c < 14; ++c)
       {
           ui->tableWidget->setItem(r,c, new QTableWidgetItem(q.value(c).toString()));
       }
    }
  loading = false;
}
void MainWindow::on_tableWidget_cellChanged(int row, int column)
{
    //int id = ui->tableWidget->item(row, 0)->text().toInt();
    if (loading) return;
    QSqlQuery q;
    q.prepare("UPDATE gkUsers SET name = :i, second_name = :d_i, surname = :n, date_of_birth = :d_u, NIP = :N, street = :u, postal_code = :k, opis = :o, telephone = :t, mobile_phone = :t_k, email = :e, sex = :p, city = :m WHERE gkUserid = :gkUserid");
    q.bindValue(":i", ui->tableWidget->item(row, 1)->text());
    q.bindValue(":d_i",ui->tableWidget->item(row, 2)->text());
    q.bindValue(":n", ui->tableWidget->item(row, 3)->text());
    q.bindValue(":d_u", ui->tableWidget->item(row, 4)->text());
    q.bindValue(":N", ui->tableWidget->item(row, 5)->text());
    q.bindValue(":u", ui->tableWidget->item(row, 6)->text());
    q.bindValue(":k", ui->tableWidget->item(row, 7)->text());
    q.bindValue(":o", ui->tableWidget->item(row, 8)->text());
    q.bindValue(":t", ui->tableWidget->item(row, 9)->text());
    q.bindValue(":t_k", ui->tableWidget->item(row, 10)->text());
    q.bindValue(":e", ui->tableWidget->item(row, 11)->text());
    q.bindValue(":p", ui->tableWidget->item(row, 12)->text());
    q.bindValue(":m", ui->tableWidget->item(row, 13)->text());
    q.bindValue(":gkUserid", ui->tableWidget->item(row, 0)->text().toInt());
    if(!q.exec()) qDebug() << q.lastError().text();
    fillTable();
}
void MainWindow::on_btnQuit_clicked()
{
    this->close();
}
void MainWindow::on_btnAdd_clicked()
{
    //QMainWindow window;
    //AddRecord * addrecord = new AddRecord(this);
    AddRecord addrecord;
    addrecord.setModal(true);
    addrecord.exec();
}
void MainWindow::on_btnSearchSurname_clicked()
{
    QString Surname = ui->searchSurnameEdit->text();
    qDebug()<<Surname;
    QSqlDatabase myDb = QSqlDatabase::addDatabase("QMYSQL");
    myDb.setHostName("localhost");
    myDb.setDatabaseName("db");
    myDb.setUserName("user");
    myDb.setPassword("passwd");
    qDebug()<<myDb.open();
    if(!myDb.open()){
        qDebug()<<"There is no connection to DB";
        return;
    }
    QSqlQuery qry;
    if(qry.exec("SELECT gkUserid, name, second_name, surname, date_of_birth, NIP, street, postal_code, desc, telephone, mobile_phone, email, sex, city FROM gkUsers WHERE surname = \'" + Surname + "\'"))
    {
        if(qry.next()){
            QString msg1 = qry.value(1).toString();
            QString msg2 = qry.value(2).toString();
            QString msg3 = qry.value(3).toString();
            QString msg4 = qry.value(4).toString();
            QString msg5 = qry.value(5).toString();
            QString msg6 = qry.value(6).toString();
            QString msg7 = qry.value(7).toString();
            QString msg8 = qry.value(8).toString();
            QString msg9 = qry.value(9).toString();
            QString msg10 = qry.value(10).toString();
            QString msg11 = qry.value(11).toString();
            QString msg12 = qry.value(12).toString();
            QString msg13 = qry.value(13).toString();
            QString msg14 = qry.value(14).toString();
            QString msg15 = qry.value(15).toString();
            ui->nameEdit->setText(msg1);
            ui->surnameEdit->setText(msg3);
            ui->dateofbirthEdit->setText(msg4);
            ui->nipEdit->setText(msg5);
            ui->telEdit->setText(msg9);
            ui->sexEdit->setText(msg12);
            ui->mobileEdit->setText(msg10);
            ui->streetEdit->setText(msg5);
            ui->cityEdit->setText(msg13);
            ui->descEdit->setText(msg8);
            myDb.close();
        } else {
            qDebug()<<"Something went wrong";
        }
    }
}
void MainWindow::on_btnEditData_clicked()
{
    EditRecord editrecord;
    editrecord.setModal(true);
    editrecord.exec();
    //editrecord = new EditRecord(this);
    //editrecord->show();
}

      **/*mainwindow.cpp*/**



      **/*mydelegate.pro*/**

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = MyDelegate
TEMPLATE = app

QT += sql

SOURCES += main.cpp\
        mainwindow.cpp \
    addrecord.cpp \
    editrecord.cpp

HEADERS  += mainwindow.h \
    addrecord.h \
    editrecord.h

FORMS    += mainwindow.ui \
    addrecord.ui \
    editrecord.ui \
    edit_record.ui          

      **/*mydelegate.pro*/**

enter code here


Why I have to give a negative two offset for seekg for end of file


So I was reading about file handling and wanted to read a text file from the end. So I decided to seek the get pointer to the last character using,

seekg(-2,ios::end);

My complete code is:

fin.open("source.txt");
fin.seekg(-2,ios::end);

fin>>ch;
if(fin.fail())
    cout<<"uh oh!";
else
    cout<<ch;

My question is that why I have to make the offset -2 and not -1 as I assume that the ios::end places the get pointer to one position after the last valid character of the file.

Any help? Thanks.


Is my function thread-safe and reentrant?


I have a function that is called by two threads each having a local copy of a vector. My Assumption was that since each thread has a different vector the function below is thread-safe.
Is the below function thread-safe and reentrant?

int Partition(int high, int low, int pivot, std::vector<int>& arr)
{
    int j = low;
    for (int i = low ; i <= high ; i++)
    {
        if (arr[i] <= pivot)
        {

            swap(i , j++ , arr);

        }
    }
    return arr.size() - j;
}

void swap(int fromIndex , int toIndex , std::vector<int> &arr)
{
    arr[fromIndex] = arr[fromIndex]^arr[toIndex];
    arr[toIndex] = arr[fromIndex]^arr[toIndex];
    arr[fromIndex] = arr[fromIndex]^arr[toIndex];
}


Detect if WM_MOUSEMOVE is caused by touch/pen


I am experimenting with WM_TOUCH and want to detect if mouse events are synthesized from touch/pen events or due to an actual mouse event.

The official solution according to MSDN is to check if the result of GetMessageExtraInfo() has the upper 24 bits set to 0xFF515700.

This works. Most of the time. If I use one finger, all is well and good, but if I use more than one, releasing the last one causes a mouse move with GetMessageExtraInfo() == 0. Also, when the window loses focus via touch, up to 3 mouse move messages with GetMessageExtraInfo() == 0 are generated.

Is there a reliable way of disambiguating between mouse, touch and pen inputs?


Stack based console application


in my console application I would check if the parenthesis balance of the equation in input is ok, but i get this error: "expected '}' at end of input" reffered to line 28 of the main(is the last line of the main).

this is code:

MAIN.CPP
#include <iostream> 
#include "Stack.h"
using namespace std;

int main() {
    char input, output;
    Stack s;
    while(input!=';'){
        cin>>input;
        if(input=='(' || input=='[' || input=='{')
            s.Push(input);
            if(input==')' || input==']' || input=='}'){
                output=s.Pop();
                        if(input==')' && output=='(' || input==']' && output==']' || input=='}' && output=='{')
                        cout<<"l'equazione è corretta";
                        else
                            cout<<"l'equazione è errata";
                }
    return 0;
    }


STACK.H
#ifndef STACK_H_
#define STACK_H_

namespace std {

class Stack
{
private:

    public:
            struct node {
                struct node *next ; /* puntatore nodo successivo */
                char data ; /* Dati contenuti nel nodo */
            };
        node *successivo;
        node *top;
        node *temp;

    Stack();
    void Push(char n);  //inserimento
    char Pop();  //estrazione
};

#endif /* STACK_H_ */

STACK.CPP
#include "stack.h"
#include <stddef.h>

using namespace std;

Stack::Stack(){
top = NULL;
successivo = NULL;
temp = NULL;
}

void Stack::Push(char n){
node *elem;
elem->data = n;
elem->next = top;
top = elem;
}

char Stack::Pop(){
char returned;
if(top != NULL){
    returned = top->data;
    temp = top->next;
    delete top;
    top = temp;
    }
    else
    returned = -1;
return returned;
}

Can anyone help me? Thanks in advance


How can we use std::transform, if we don't want to transform each element into one transformed element, but two?


How can we use std::transform, if we don't want to transform each element into one transformed element, but two?

The following pseudo code illustrates what I want to achieve

std::transform(a.cbegin(), a.cend(), std::back_inserter(b), [](T const& x) {
    return f(x) and g(x);
});

Of course, I could invoke std::transform two times, but that would be annoying. Maybe we need to provide a custom inserter. Any other option?


Invoke marshalled COM interface multiple times


I am writing a COM object for JavaScript consumption. JavaScript code is turn runs in an hosted WebBrowserControl. I need to fire some events from COM object to JavaScript, the excellent guide to which at Dr. Dobbs

e.g. I have following in my *.idl

IJSCallback
{
    void Listen(IDispatch* pJSMethod);
}

JavaScript methods are received as IDispatch* in C++ code, which is to be stored for calling it later, from another thread. No matter what method for marshaling is used (CoMarshalInterThreadInterfaceInStream or IGlobalInterfaceTable) the event firing thread is able to call JavaScript function only once. After that IDispatch::Invoke() returns E_ACCESSDENIED!

sample JavaScript code

var server = new ActiveXObject("prog_id")
var.Listen(function(ip_add) {
    // ip_add from COM object
});

the C++ thread is pretty straight forward.

// called from JavaScript
CMyObject::Listen(IDispatch* pJSMethod)
{
    // IStream* m_pStream;
    CoMarshalInterThreadInterfaceInStream(pJSMethod, IID_IDispatch, &m_pStream);
}

// called from internal C++ thread.
CMyObject::FireEvent()
{
    // IStream* m_pStream;
    // IDispatch* m_pJSMethod;
    CoGetInterfaceAndReleaseStream(m_pStream, IID_IDispatch, (LPVOID*)&m_pJSMethod);

    HSREULT hr = m_pJSMethod->Invoke(...); // hr = S_OK, call is received in JavaScript
    hr = m_pJSMethod->Invoke(...); // hr = E_ACCESSDENIED, call is not received in JavaScript
}

is this expected behavior? or something wrong in code?


Insert item to array


I have 3 arrays which contains 5 elements each (max size is 5). What I wanted to do is to insert an item, e.g, to position 7. The end result is the item should be placed in 2nd array at index 2 and a 4th array is then created with 1 element (from last item of 3rd array).

                                result
array1                          array1
    - item1 (position 0)            - item1 (position 0)
    - item2 (position 1)            - item2 (position 1)
    - item3 (position 2)            - item3 (position 2)
    - item4 (position 3)            - item4 (position 3)
    - item5 (position 4)            - item5 (position 4)
array2                          array2
    - item1 (position 5)            - item1 (position 5)
    - item2 (position 6)            - item2 (position 6)
    - item3 (position 7)            - item3 (position 7) -> new_item
    - item4 (position 8)            - item4 (position 8)
    - item5 (position 9)            - item5 (position 9)
array3                          array3
    - item1 (position 10)           - item1 (position 10)
    - item2 (position 11)           - item2 (position 11)
    - item3 (position 12)           - item3 (position 12)
    - item4 (position 13)           - item4 (position 13)
    - item5 (position 14)           - item5 (position 14)
                                array4
                                    - item1 (position 15)

And, if wanted to get the item at position 12, then the result should be item3 of array3.

How can I do this in c++?


constexpr char array with GCC and clang


Consider the following code:

#include <cstddef>
#include <iostream>
#include <stdexcept>

class const_string {
public:
    template <std::size_t sz>
    constexpr const_string(const char (&str)[sz]): p_(str) {}
    constexpr char operator[](std::size_t i) const { return p_[i]; }
private:
    const char* p_;
};

template <char c>
void Print() { std::cout << c << '\n'; }

int main() {
    constexpr char str[] = "Hello World";
    Print<const_string(str)[0]>();
}

It compiles fine with clang, while GCC gives the following error message:

in constexpr expansion of 'const_string((* & str)).const_string::operator[](0ul)' error: '(const char*)(& str)' is not a constant expression

However, if I change Print<const_string(str)[0]>(); to Print<const_string("Hello World")[0]>();. Both clang and GCC compile fine.

What is going on here? Which compiler is correct according to the standard?


Why is the letter 'D' missing in the output?


#include <iostream>
using namespace std;

int main() {

    char ch1 = 'A';
    char ch2 = 'B';
    char ch3 = '\n';
    cout << ch1 << '\t' << ch2 << ch3;
    cout << 'C' << '\t' << 'D' << '\b' << ch1 << ch3;
    //return 0;
    system("pause");
}

Output is:

A        B
C        A

Why is the last letter A and not D?


Class for avl trees in c++


So I wanted to make an avl tree in c++.I used a class to make the nodes and a class for the rest of the fuctions ( instert,delete etc).When I want to make more than one trees I decided that i needed to make more roots(one for every tree).The problem is when I declare the new root inside the main.When i declare it outside it seems to work fine. This is the class

class avl_node

{
public:
int data;

avl_node *left;

avl_node *right;

}*root;

and this is the main

int main()

{
avl_node *roott;
int item;   
avlTree avl;
avlTree kk;               
root=avl.insert(root,item);          
roott=kk.insert(roott,item);         
kk.display(roott, 1);
return 0;
}


call of overloaded 'swap(char&, char&)' is ambiguous


I can't figure out what is ambiguous about swap(arr[i++],arr[n--]); below. Please educate me on my wrongful ways.

#include <iostream>
#include <string>

template <typename T> void swap ( T & a, T & b )
{
    T temp = b;
    b = a;
    a = temp;
}

template <typename T> void reverse_array ( T * arr, size_t n )
{
   size_t i = 0;
   while (i < n) swap(arr[i++],arr[n--]); // problem line
}


int main () 
{
   char mystr [] = "Obama smokes";
   reverse_array(mystr, sizeof(mystr)/sizeof(char));
   return 0;
}


Why would the behavior of std::memcpy be undefined for objects that are not TriviallyCopyable?


From http://ift.tt/1pDNXbt:

If the objects are not TriviallyCopyable (e.g. scalars, arrays, C-compatible structs), the behavior is undefined.

At my work, we have used std::memcpy for a long time to bitwise swap objects that are not TriviallyCopyable using:

void swapMemory(Entity* ePtr1, Entity* ePtr2)
{
   static const int size = sizeof(Entity); 
   char swapBuffer[size];

   memcpy(swapBuffer, ePtr1, size);
   memcpy(ePtr1, ePtr2, size);
   memcpy(ePtr2, swapBuffer, size);
}

and never had any issues.

I understand that it is trivial to abuse std::memcpy with non-TriviallyCopyable objects and cause undefined behavior downstream. However, my question:

Why would the behavior of std::memcpy itself be undefined when used with non-TriviallyCopyable objects? Why does the standard deem it necessary to specify that?

UPDATE

The contents of http://ift.tt/1pDNXbt have been modified in response to this post and the answers to the post. The current description says:

If the objects are not TriviallyCopyable (e.g. scalars, arrays, C-compatible structs), the behavior is undefined unless the program does not depend on the effects of the destructor of the target object (which is not run by memcpy) and the lifetime of the target object (which is ended, but not started by memcpy) is started by some other means, such as placement-new.

PS

Comment by @Cubbi:

@RSahu if something guarantees UB downstream, it renders the entire program undefined. But I agree that it appears to be possible to skirt around UB in this case and modified cppreference accordingly.


Properly initialising variables in modern C++ (C++11 and above), using () or {}?


The C++ reference pages say that () is for value initialisation, {} is for value and aggregate and list initialisation. So, if I just want value initialisation, which one do I use? () or {}? I'm asking because in the book "A Tour of C++" by Bjarne himself, he seems to prefer using {}, even for value initialisation (see for example pages 6 and 7), and so I thought it was good practice to always use {}, even for value initialisation. However, I've been badly bitten by the following bug recently. Consider the following code.

auto p = std::make_shared<int>(3);
auto q{ p };
auto r(p);

Now according to the compiler (Visual Studio 2013), q has type std::initializer_list<std::shared_ptr<int>>, which is not what I intended. What I actually intended for q is actually what r is, which is std::shared_ptr<int>. So in this case, I should not use {} for value initialisation, but use (). Given this, why does Bjarne in his book still seem to prefer to use {} for value initialisation? For example, he uses double d2{2.3} at the bottom of page 6.

To definitively answer my questions, when should I use () and when should I use {}? And is it a matter of syntax correctness or a matter of good programming practice?

Oh and uh, plain English if possible please.

EDIT: It seems that I've slightly misunderstood value initialisation (see answers below). However the questions above still stands by and large.


tcp socket, cannot bind to port - in use


Ive got a c++ program that acts as a server (sends/receives). I'm trying to connect to the port that the server is using (say 2222). However, the message I'm getting is that the port is already bound to. The port is in use. I'm wondering how can I connect to this open port (bearing in mind the c++ tcp program is closed source)? I can change the source of the c++ program if needed, but it seems strange that I cannot just connect to the port it's using. I wonder do I need to implement threading in the tcp program, so that the send and receive's are using a different port?