FAQ Database Discussion Community


C++ need help figuring out word count in function. (Ex. Hello World = 2)

c++,function
I'm figuring out the algorithm on this function and it keeps crashing at runtime, here's the code snippet: int wordCounter(char usStr[]) { int index= 0, punct= 0; while(usStr[index]!= '\0') //If it's not the end of the sentence if(usStr[index]== ' ') //If it finds a space index++; while(usStr[index]== '\0') //If it's...

How to add a gif image in the statusbar Qt [closed]

c++,qt
I'm pretty new to Qt and I was told that I can add a gif image to the status bar using the QMovie class. Can anyone tell how it can be done and is there any other way to do this too?

Passing a struct to a template with extern const. What is the extern for?

c++,templates,struct,const,extern
I am asking myself why the following code works and what the specifier extern does when instantiating baz_instance: struct baz { int value; }; extern const baz baz_instance = {3}; template<baz const& b> int foo(){ return b.value; } int main(){ foo<baz_instance>(); return 1; } Why does the above code compile...

create vector of objects on the stack ? (c++)

c++,vector,heap-memory
I am creating a temporary vector of pointers to myObject objects. But I am wondering about what happens to the objects I created... { std::vector<myObject *> myVector; myVector.reserve(5); for (int i = 0 ; i < 5 ; ++i){ myVector[i] = new myObject(); } } I assume that at the...

Type function that returns a tuple of chosen types

c++,templates,c++11,metaprogramming
I've implemented a type function Tuple that turn a list of My_enum values into an std::tuple of corresponding types: #include <tuple> enum My_enum{ t_int, t_double }; // Bind_type is a type function that given a My_enum returns the corresponding type template<My_enum E> struct Bind_type; template<> struct Bind_type<t_int>{ using type =...

linux running command as root from c code that run as normal user

c++,linux
I have a c++ code and I need to running from it a command to adjust the system time. so I thought using system("su root -c date hh:mm") command from my c++ code. The problem is that when I write 'su root -c date hh:mm' in the terminal its requires...

Surface normal on depth image

c++,opencv,computer-vision
How to estimate the surface normal of point I(i,j) on a depth image (pixel value in mm) without using Point Cloud Library(PCL)? I've gone through (1), (2), and (3) but I'm looking for a simple estimation of surface normal on each pixel with C++ standard library or openCV. ...

Checking value of deleted object

c++
I asked a question: Detecting if an object is still active or it has been destroyed Considering that I cannot use libraries, there are no good out of the box solutions in C++. So, is it a bad practice to check if the object has been destroyed by analyzing memory...

C++ template template

c++,templates
I'm trying to understand C++ template templates by implementing a generic container class. Here is the code: using namespace std; template <typename T, template <typename STORETYPE> class Container> class Store { public: ~Store() {}; Store() {}; void someFunc( const T & ) {}; //... private: Container<T> storage; }; int main(int...

MFC visual c++ LNK2019 link error

c++,mfc
I just don't understand why i can use the public variables on the class but are getting a link error when trying to use the getLicenceRefused method. I wasn't sure if the problem was because of the CString copy constructor problem I have had before so took the parameter out,...

__cplusplus < 201402L return true in gcc even when I specified -std=c++14

c++,gcc,g++,c++14,predefined-macro
The directive: #ifndef __cplusplus #error C++ is required #elif __cplusplus < 201402L #error C++14 is required #endif The command-line: g++ -Wall -Wextra -std=c++14 -c -o header.o header.hpp My g++ version: g++ (tdm-1) 4.9.2 The error C++14 is required is generated even when I added -std=c++14, I don't know why. Please...

Mixing “untyped” operator new and “typed” delete

c++
I want to make a class factory that can create classes knowing nothing about them (eg no headers included). I created a factory class with map, that stores info about classes (sizeof and pointer to static method) by strings ( map(string, mystruct) ), which is filled from each class. When...

Unable to render a texture on a quad

c++,opengl,textures,texturing
I am trying to program a simple game in C++ using OpenGL for graphics. In my game, I have objects that are rendered onscreen as a white square. I would like to be able to bind an image as a texture to these objects, so that I can render an...

C++11 Allocation Requirement on Strings

c++,string,c++11,memory,standards
I had heard that C++11 was going to require strings to be allocated in contiguous memory. I even thought I saw a stack overflow question on it, but I can't seem to find it. I know that in practice both gcc and Visual Studio do allocate strings contiguously, I'm just...

Dividing main function into other functions in opencv using c++

c++,opencv
I am learning opencv using c++. As I don't have any background knowledge in c++.I am learning it parallel with opencv. Here is my doubt.My main program is very big.So,I want to divide it into small functions and call them whenever necessary in a loop using conditional statements.I have searched...

Function pointer to singleton class instance function

c++,oop,pointers,singleton
What I'm trying to do is create a function pointer to a single class instance function. I want to do this so I can do something like this: C->member_method(); instead of: Config::inst()->member_method(); but I'm not sure how to go about it. Here is my singleton class: class Config { private:...

How can I pass N number of generic arguments to a typedef function pointer?

c++,generics,typedef
I have this typedef function pointer plot: typedef void(*plot)(); How can I pass a generic argument to it (Something like this): template<typename T> typedef void(*plot)(T); And then, how can I pass N number of generic arguments to it? template<typename T> typedef void(*plot)(T ...); ...

Add same value multiple times to std::vector (repeat)

c++,vector,std
I want to add a value multiple times to an std::vector. E.g. add the interger value 1 five times to the vector: std::vector<int> vec; vec.add(1, 5); vec should be of the form {1,1,1,1,1} afterwards. Is there a clean c++ way to do so?...

C++ & Qt: Random string from an array area

c++,arrays,string,qt,random
In my small Qt application, I want to pick a random string out of an array after I clicked on a button. I've read many threads but nothing works for me. So in my slot there's an array with several strings in it. I also implemented <string>, <time.h> and srand....

Method returning std::vector>

c++
As a continuation of a: Thread, I came across a problem with writing a method of a class which returns: std::vector<std::unique_ptr<Object>> I get compiler errors when such a return type is written. There is some problem with delete operand or something ... Generally, I've wanted to write a method which...

Translating a character array into a integer string in C++

c++,arrays,string
I was trying to achieve translating a character array into a integer string and corresponding character to their alphabetical order. For instance: A(a) = 0 , Z(z) = 25. string key_char = argv[1]; string key_num; for (int i = 0; i < key_char.length(); i++){ if (isalpha(key_char[i])){ if (islower(key_char[i])){ key_num[i] =...

template template class specialization

c++,templates,template-specialization
I am just learning about Template Template class specialisation. Not a big problem to explain in detail. From my understanding std::uniform_int_distribution is a template whereas std::uniform_int_distribution<Type> is the full specialisation of uniform_int_distribution giving a type. I pass this in the specialisation class template as follows below Main class template <template...

Incorrect Polar - Cartesian Coordinate Conversions. What does -0 Mean?

c++,polar-coordinates,cartesian-coordinates
I am getting incorrect conversions from polar to cartesian coordinates and vice versa. My code produces weird points like (1,-0). Im using this calculator to check my conversions. Also one of the conversions is completely wrong when I convert back to cartesian coordinates. Point b: (0,1) => (1,1.5708) => (0,0)...

winapi: from HDC to an HBITMAP

c++,winapi,bitmap,gdi
I would like to do something which I believe is fairly simple but since I am new to the winapi I am finding a lot of problems. Basically I have an HDC (which I am BitBlitting from a loaded Bitmap) and I am drawing a rectangle on it. Then I...

Should checking loop conditions be counted towards total number of comparisons?

c++,algorithm,sorting,c++11
I have implemented three different sorting algorithms and now I want to confirm that my approach of counting the total number of comparisons is correct. In my mind, the number of comparisons shouldn't be tied to the conditional branches because if the condition isn't met, the comparison was still made...

Convert long int seconds to double precision floating-point value

c++,date,datetime,time,converter
I have a long int variable wich containes seconds since Jan. 1, 1970 in this format: long int seconds = 1231241242144214; i need to convert this seconds to double precision floating-point value. The integer part of the value is the number of days since midnight, 30 December 1899. The fractional...

How to increment the value of an unsigned char * (C)

c++,c,openssl,byte,sha1
I have a value stored as an unsigned char * (in C). This holds the SHA1 hash of a string. My goal is to cover the SHA1 key space. Since I'm using <openssl/evp.h> to generate the hashes, I end up with an unsigned char* holding the SHA1 value. Now I...

Same function with and without template

c++,c++11
I am trying to understand a piece of code of C++11. A class contains 2 functions as shown below: class abc { public: void integerA(int x); template<typename typ> void integerA(typ x); }; I am unable to understand benefit of declaring 2 same functions. Why not declare only one template function?...

double* android ndk crash

c++,pointers,android-ndk
I'm facing a peculiar problem with the android ndk. I'm trying to read a previously stored set of bytes in an unsigned char* readBytes (previous allocated and read from file). The data needs to be interpreted as double. unsigned char* svDataOffset=(unsigned char*)(readBytes+byteCounter); unsigned char* chars=(unsigned char*)(svDataOffset+2); //offset of 2 is...

for loop c++ 'toupper' implementation

c++,toupper
Can someone explain why this short code in C++ doesn't produce the expected output. The code is supposed to print the string in capital letters. #include <iostream> #include <string> using namespace std; int main(){ string sample("hi, i like cats and dogs."); cout << "small: " << sample << endl <<...

Why is the boolean value within a structure within a vector not being updated?

c++,c++11
This might sound like a very basic question, but I have trying to fix a simple bug for over an hour now and I can't seem to understand what's happening. I have the following structure declaration in my header file: struct StudentBody { string name; Vec2 position; bool disabled; StudentBody(string...

Validate case pattern (isupper/islower) on user input string

c++,user-input
I need to write a program that checks if the user-provided first and last names are correctly typed. The program needs to validate that only the first letter of each name part is uppercase. I managed to write code that checks the first character of the input. So I have...

Algorithm for [inclusive/exclusive]_scan in parallel proposal N3554

c++,algorithm,parallel-processing,c++14
Proposal N3554 (A Parallel Algorithms Library) for C++14, proposes (among other things), what seem to be parallel versions of the current std::partial_sum, e.g.: template< class ExecutionPolicy, class InputIterator, class OutputIterator, class BinaryOperation> OutputIterator inclusive_scan( ExecutionPolicy &&exec, InputIterator first, InputIterator last, OutputIterator result, BinaryOperation binary_op); With the explanation Effects: For each...

Explicit instantiation of class template not instantiating constructor

c++,templates,constructor,explicit-instantiation
I'm working on a project in C++ and am having trouble understanding what members of a template class get explicitly instantiated when I explicitly instantiate the template class. I've written the following file, which I then compile using Visual C++ 2008 Express Edition's Release configuration and then pop into a...

How should I read the filename in FILE_NOTIFY_INFORMATION struct

c++,winapi,filesystems,file-monitoring,readdirectorychangesw
I'm trying to monitor file changes but I am not really sure on how to read the filename in the FILE_NOTIFY_INFORMATION struct: HANDLE dwChangeHandles[2]; DWORD dwWaitStatus; wChangeHandles[0] = FindFirstChangeNotification(dirname.c_str(), FALSE, FILE_NOTIFY_CHANGE_LAST_WRITE); if (dwChangeHandles[0] == INVALID_HANDLE_VALUE) printerr(__FILE__,__LINE__,"FindFirstChangeNotification function failed.\n"); ... if ((dwChangeHandles[0] == NULL) || (dwChangeHandles[1] == NULL)) //final validation printerr(__FILE__,__LINE__,"Unexpected...

Copy text and placeholders, variables to the clipboard

c++,qt,clipboard
In my application I want generate random numbers or strings with a text in front of it. It is important for me that the text won't appear in my window, but instead gets copied to the clipboard. int randomnumber = rand() % 46 + 1; QClipboard *cb = QApplication::clipboard(); cb->setText("Just...

How can I tell clang-format to follow this convention?

c++,clang-format
I would like to have this: if (!enabled) { return; } turned to this: if (!enabled) { return; } (In other words, I want short if-statements on a single line but keep the {} around them) Currently I'm using the following configuration: AllowShortIfStatementsOnASingleLine: true AllowShortLoopsOnASingleLine: true AllowShortCaseLabelsOnASingleLine: true AllowShortFunctionsOnASingleLine: true...

opencv window not refreshing at mouse callback

c++,opencv
I am trying to draw with mouse move in an opencv window. But when I draw, nothing draws on the window. When I try to close the window from the cross in the topleft(ubuntu), it opens a new window which it should be as I haven't pressed escape, and in...

Initializing a multidimensional array

c++,arrays,multidimensional-array,initialization
I am trying to initialize a multidimensional array in batches and can't seem to make it work or find an example! The dimensions I am working with are big enough that I don't want to specify them by hand! More precisely : int test[5][192]; for(int i = 0; i <...

segfault accessing qlist element through an iterator

c++,iterator,qlist
I get a segfault while iterating over a QList. I don't understand what I am doing wrong. I have a QList of Conversation. Inside a Conversation I have a QList of Msg. Below are the class description : Msg class : class Msg { public: Msg(); Msg(const Msg& other); Msg&...

Compile my 32 bit project with C++ dll 64 bit

c#,c++
I have some legacy C# application ( 32 bit ) that work with some C++ 3rd party dll ( not com .. just simple unmanaged C++ ) One of those 3rd party dll just release new dll version - and this version is not 32 bit any more - its...

3 X 3 magic square recursively

c++,algorithm,math,recursion
I'm trying to find all possible solutions to the 3X3 magic square. There should be exactly 8 solutions. My code gets them all but there are a lot of repeats. I'm having a hard time tracking the recursive steps to see why I'm getting all the repeats. // This program...

C++ Isn't this a useless inline declaration?

c++,inline,private,member,protected
This is another question about inlining a function. But I will take possible comments and answers right away: Defining a function inside a class makes it inline automatically. The same behaviour can be achieved by marking a function with inline outside of the class. An inline function doesn't have to...

Convert double to time_t

c++,time,standards,chrono,time-t
I have a double containing seconds. I would like to convert this into a time_t. I can't find a standard function which accomplishes this. Do I have to fill out the time_t by hand?...

pointer to pointer dynamic array in C++

c++,arrays,pointers
I've been having bad luck with dynamic pointers when I want to close it. why the application wrote to memory after end of heap buffer? how can I close my array? int main() { . . int **W; W = new int* [n]; for (int i=1; i <= n; i++)...

Can assignment from a const_iterator dereference cause undefined behaviour?

c++,pointers,pass-by-reference,undefined-behavior,const-iterator
This code is a simplified test for something I am trying to do for real elsewhere. I have a function which takes a "ref-to-ptr" argument and modifies it to return a pointer from a list of pointers. #include <iostream> #include <list> using namespace std; typedef int* intp; typedef std::list<intp> intplist;...

how to sort this vector including pairs

c++,vector
I want to sort in ascending order according to the first element of the inner pair, i.e. a in this case. But its not at all sorting. I am not sure if my function func logic is correct. #include<iostream> #include<algorithm> #include<vector> using namespace std; bool func(const pair<int,pair<int,int> >&i , const...

Is executing C++ code in comments with certain Unicode characters allowed, like in Java?

c++,c++11,unicode,comments
I know that executing Java code in comments with certain Unicode characters is allowed. Please see this question for further clarification Executing Java code in comments. So was just curious to know if C++ has such features?

Confused about returns in stack template

c++,templates,generic-programming
I'm implementing a generic stack (with an array) in C++ and am confused about what to return in this situation: template <class T> T Stack<T>::pop(void) { if (size != 0) { return items[size - 1]; size--; } else { cerr << "Cannot pop from empty stack." << endl; return ???;...

char* string substract function throws exception

c++,arrays,string,char
I'm working on my own string class called PString, I have this function that finds a specific character, like 6, and now I have this function called substr short fo substract, where I want to substract from 0 to [insertnumber]. the way I'm trying to call this is by doing...

.cpp:23: error: cannot convert ‘std::string’ to ‘const char*’ for argument ‘1’ to ‘int atoi(const char*)’

c++,string
Here a basic code I'm trying to run But I'm having trouble with stoi (it's c++) I keep getting error: ‘stoi’ was not declared in this scope I tried atoi and strtol with this error .cpp:23: error: cannot convert ‘std::string’ to ‘const char*’ for argument ‘1’ to ‘int atoi(const char*)’...

connecting signals and slots with different relations

c++,qt,connect,signals-slots
First of all I'd say I'm a noob to GUI programming. I use Qt 5.4. I came up with this code while watching voidRealms videos. connect(ui->horizontalSlider,SIGNAL(sliderMoved(int)),ui->progressBar,SLOT(setValue(int))); Obviously this connects slider movement with progressbar fill. This actually works like progressbarfill <- slidermovement. How can I make into a different relation? Like...

Implicit use of initializer_list

c++,c++11,initializer-list
§[dcl.init.list] 8.5.4/2: The template std::initializer_list is not predefined; if the header <initializer_list> is not included prior to a use of std::initializer_list — even an implicit use in which the type is not named (7.1.6.4) — the program is ill-formed. Does that mean this program is ill-formed? #include <vector> int main()...

Casting a pointer by reference

c++,casting,parameter-passing,pass-by-reference
I came across something I don't understand well. Let's suppose I want to pass a character pointer to a function that takes a reference to a void pointer. void doStuff(void*& buffer) { // do something } I would usually do something like this : int main() { unsigned char* buffer...

Undefined behaviour or may be something with memset

c++,undefined-behavior
I was trying to save the binary equivalent of a 32 bit number in an array A. For testing my showbits() function , I choosed 8,9 when I came across this thing: I am facing an unreasonable thing in my code when I am placing memset in the function showbits(),I...

Calling variadic template function with no args failing

c++,c++11
Given the following code: #include <iostream> template <typename... Args> void foo(Args&&... bargs, Args&&... aargs) { std::cout << "Hello" << std::endl; } int main() { foo<int, double>(1, 2.0, 3, 4.0); //OK foo<char>('c', 'd'); // OK foo(); //FAIL } I get the following compiler error: In function 'int main()': 15:9: error: no...

Test if string represents “yyyy-mm-dd”

c++,command-line-arguments
I am working on a program that takes two command line arguments. Both arguments should be dates of the form yyyy-mm-dd. Since other folks will be using this program and it will be requesting from mysql, I want to make sure that the command line arguments are valid. My original...

memory content not erased after deleting my pointer (on a simple example) [duplicate]

c++,pointers,memory-management
This question already has an answer here: Can a local variable's memory be accessed outside its scope? 16 answers Here is a simple of example of a question I have: I create a pointer of integer (value 5), I print the pointer (hence the address) of the memory case...

What is “Class::*”

c++
I am learning SFINAE(Substitution failure is not) I found an example of it in a site, template<typename T> class is_class { typedef char yes[1]; typedef char no [2]; template<typename C> static yes& test(int C::*); // What is C::*? template<typename C> static no& test(...); public: static bool const value = sizeof(test<T>(0))...

C++ function overload priority [duplicate]

c++,overloading
This question already has an answer here: Unexpected overload resolution in visual studio involving void*, string and const char[] 3 answers Why would the code give an output: bool ? Is there any way I could make the const char* to match the string version? #include <string> #include <iostream>...

OpenCV - Detection of moving object C++

c++,opencv
I am working on Traffic Surveillance System an OpenCv project, I need to detect moving cars and people. I am using background subtraction method to detect moving objects and thus drawing counters. I have a problem : When two car are moving on road closely them my system detects it...

I don't understand how the template function gets to be a friend of the class A::X::Y in the example in [namespace.memdef]/3 in C++14

c++,templates,language-lawyer,c++14,friend
Consider the following code from the example in [namespace.memdef]/3 in C++14: // Assume f and g have not yet been declared. void h(int); template <class T> void f2(T); namespace A { class X { friend void f(X); // A::f(X) is a friend class Y { friend void g(); // A::g...

Get an ordered list of files in a folder

c++,boost,boost-filesystem
I have used boost::filesystem::directory_iterator in order to get a list of all the available files into a given folder. The problem is that I supposed this method would give me the files in alphabetical order, while the results seem pretty random. Is there any fancy way of alphabetically sorting them?...

Make a triangle shape in C++

c++
I am trying to print out the shape of a triangle but I am kinda lost... this is what I have so far: #include <iostream> using namespace std; int main() { int i, k, n; cout << "Please enter number of rows you want to see: \n"; cin >> n;...

Is there a way to prevent rounding in opencv matrix divison

c++,opencv
I have an integer matrix and I want to perform an integer division on it. But opencv always rounds the result. I know I can divide each element manually but I want to know is there a better way for this or not? Mat c = (Mat_ <int> (1,3) <<...

what is the use of “static_cast” in macro?

c++,casting
I'm seeing a macro definition like this: #define ASSERT_VALID_PARAM(param, assertion) { static_cast<void>(param); if (!(assertion)) { throw InvalidParamError(#param, #assertion, __FILE__, __PRETTY_FUNCTION__, __LINE__); } } I'm not able to figure out the need of static_cast<void>(param) here. Any idea on why this is needed?...

std::condition_variable – notify once but wait thread wakened twice

c++,multithreading
Here's a simple C++ thread pool implementation. It's an altered version orginated from https://github.com/progschj/ThreadPool. #ifndef __THREAD_POOL_H__ #define __THREAD_POOL_H__ #include <vector> #include <queue> #include <memory> #include <thread> #include <chrono> #include <mutex> #include <condition_variable> #include <future> #include <functional> #include <stdexcept> namespace ThreadPool { class FixedThreadPool { public: FixedThreadPool(size_t); template<class F, class......

Storing columns on disk and reading rows

c++,file,matrix,io
So I have a C++ code that finds the inverse of a square matrix. The inverse is full and it would be bad to keep it all in memory because I am working with hundreds of thousands of columns. My code generates the columns one by one. After finding the...

Issue when use two type-cast operators in template class

c++
I define a template class in which, I define two type-cast operator template <class base_t> struct subclass { base_t base; //any function which defined for 'base_t' can be used with 'subclass<base_t>' operator base_t&() { return base; } //I want 'subclass<base_t>' can be converted to any class which 'base_t' can //I...

Marshal struct in struct from c# to c++

c#,c++,marshalling
I have the following structures in C# and C++. C++: struct TestA { char* iu; }; struct TestB { int cycle1; int cycle2; }; struct MainStruct { TestA test; TestB test2; }; C#: [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack = 1)] internal struct TestA { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 36)] private string iu; public...

How does int(or long long) overflow in c++ affect modulus?

c++,long-integer,modulus,integer-overflow
Suppose I have two long longs, a and b, that I need to multiply, then get the value mod k for some large k, such that a, b, and k are all in the range of long long but not of int. For simplicity, a, b < k. Thus the...

Make Boost Matrix attribute of a class

c++,boost
I want to make a Boost Matrix as an attribute of my class Adsorbate. I know beforehand that it will be (3,2). I want to do: #include <boost/numeric/ublas/matrix.hpp> using namespace boost::numeric::ublas; class Adsorbate { matrix<double> m(3,2); }; so that the compiler knows the size of the attribute m and thus...

Passing something as this argument discards qualifiers

c++,c++11
Using the below code, i get the following compile error: In static member function ‘static std::string ctedata::Record::getDispatcher<std::basic_string<char> >::impl(const ctedata::Record&, const string&)’: /home/jason/CrownTheEmpire/lib/ctedata/data.h:111:38: error: passing ‘const std::map<std::basic_string<char>, std::basic_string<char> >’ as ‘this’ argument discards qualifiers [-fpermissive] return rec.fieldValues_[field]; ^ In file included from /usr/include/c++/5.1.0/map:61:0, from...

How can I access the members of a subclass from a superclass with a different constructor?

c++,inheritance,constructor,subclass,superclass
I have the following class and typedef: class Object { protected: long int id; public: Object(void); ~Object(void) {}; long int get_id(void); }; typedef map<string, Object> obj_map; And then I have its child: class Image: public Object { private: path full_path; int x; int y; img image; public: Image(path p, int...

Use Sockets in multiple *.cpp files

c++,sockets,server
As you can see in the Title box, I´d like to find a way how to use my sockets in multiple cpp files. #pragma comment(lib,"ws2_32.lib") void main() { WSADATA wsaData; WSAStartup(MAKEWORD(2,0), &wsaData); SOCKET slisten,client; slisten = socket(AF_INET,SOCK_STREAM, 0); //and so on... } This is the way I use the ws2_32.lib...

Using rand() to get a number but that number can't be the number that was last generated

c++,random,std
I want to use std::rand() to generate a number between 0 and amountOfNumbers, but the generated number can't be the same number that was last generated. I wrote this function: void reroll() { int newRand; while (true) { newRand = std::rand() % (amountOfNumbers); if (newRand == lastNumber) { continue; }...

Return const reference to local variable correctly

c++,qt
Additionally to the answers 1, 2, 3 and GotW88, assume the following methods QString createString() { return QString("foobar"); } const QString& getString() { return createString(); } This will yield the famous "warning C4172: returning address of local variable or temporary" with VS2013. Now if i changed the second method to...

ctypes error AttributeError symbol not found, OS X 10.7.5

python,c++,ctypes
I have a simple test function on C++: #include <stdio.h> #include <string.h> #include <stdlib.h> #include <locale.h> #include <wchar.h> char fun() { printf( "%i", 12 ); return 'y'; } compiling: gcc -o test.so -shared -fPIC test.cpp and using it in python with ctypes: from ctypes import cdll from ctypes import c_char_p...

No match for 'operator*' error

c++,c++11
Hello fellow programmers! I was going to write a small program for calculating total pay for different periods of time depending on the amount of hours and the salary that the user enters. I managed to make a small bit of the program but when I try to run it...

How to re-write templated function to handle type deduction

c++,templates,c++11
So, I have this search function for the map container: template <typename Key, typename T> void searchInMapByKey(std::map<Key,T> Map, T keyValue) { if(Map.empty()) { std::cout << "Map is empty, nothing to search for..." << "\n"; } else { for(const auto & element : Map) { if(element.first==keyValue) { std::cout << keyValue <<...

Add more features to stack container

c++,visual-c++,stl
I am using default features(push, pop, top, empty, size) of stack container of STL. If I want to add more features like access an element from middle of stack. How could I do this? Thanks...

undefined reference to `vtable for implementation' error

c++,build,makefile
I wrote some c++ files and after compiling with out make file it works fine . But when using make file it pop out some errors . My codes are : include directory files : application.h #ifndef APPLICATION_H #define APPLICATION_H #include "employee.h" #include "employee_data.h" #include "employee.h" ...some defintions here... #endif...

Sorting vector of Pointers of Custom Class

c++,sorting,c++11,vector
I have vector<FPGA*> current_generation_, which I'd like to sort by FPGA member fitness_ using the sort_members function. Applicable code follows: bool sort_members (FPGA* fpga_first, FPGA* fpga_second) { return (fpga_first->fitness() < fpga_second->fitness()); }; fpga.hpp #include <vector> class FPGA { public: explicit FPGA(int input_gates, int output_gates, int normal_gates); const int fitness(); protected:...

Strings vs binary for storing variables inside the file format

c++,file,hdf5,dataformat
We aim at using HDF5 for our data format. HDF5 has been selected because it is a hierarchical filesystem-like cross-platform data format and it supports large amounts of data. The file will contain arrays and some parameters. The question is about how to store the parameters (which are not made...

change QDir::rootPath() to program running path?

c++,qt
I have a Qt FTP server that selects C:/ as root path. I'm trying to change that to select the starting program location path. For example: If ftpserver.exe is located in H:/programs/ftpserver.exe, it must automatically set the ftp root path to H:/. Code: ui->lineEditRootPath->setText(settings.value("settings/rootpath", QDir::rootPath()).toString()); Code: void MainWindow::on_toolButtonBrowse_clicked() { QString...

Stuck on Structs(c++)

c++,function,struct
Okay so this is what Ive been asked to do "make a struct called Coordinate that contains the latitude and longitude of a point on the surface of the Earth. The struct should also store a label or name for the coordinate (e.g., “Calgary”). Both the latitude and longitude member...

dispatch response packet according to packet sequence id

c++,boost,boost-asio
I have a third-part server, and I'm writing a dll interface for it, my clients use my dll to communicate with the server. The protocol uses a long tcp connection, all traffic goes from this tcp connection. There could be sending/receiving multiple packets at the same time, like a send_msg...

C++ error: deduced conflicting types for parameter 'T' string vs const char *

c++,string,templates,c++11,char
So, I am writing a simple, templated search function for deque container. Here's the code: template <typename T> void searchInDequeFor(std::deque<T> Deque, T searchValue) { for(const auto & element : Deque) { if(Deque.empty()) { std::cout << "Deque is empty, nothing to search for..." << "\n"; } else if(element==searchValue) { std::cout <<...

Static member function to initialize static member variable - usage and risks?

c++
In the case of In MyClass.h class MyClass { static vector<type> types; static vector<type> createTypes(); } In MyClass.cpp vector<type> MyClass::types = createTypes(); MyClass::MyClass() { } When will be createTypes() executed and does this method of initializing a static variable involve any risks?...

Quaternion to EulerXYZ, how to differentiate the negative and positive quaternion

c++,geometry,quaternions,euler-angles
I've been trying to figure out the difference between these, and why ToEulerXYZ does not get the right rotation. Using MathGeoLib: axisX: x 0.80878228 float y -0.58810818 float z 0.00000000 float axisY: x 0.58811820 float y 0.80877501 float z 0.00000000 float axisZ: x 0.00000000 float y 0.00000000 float z 1.0000000...

C++ / C #define macro calculation

c++,c,macros
Suppose I have #define DETUNE1 sqrt(7)-sqrt(5) #define DETUNE2 sqrt(11)-sqrt(7) And I call these multiple times in my program. Are DETUNE1 and DETUNE2 calculated every time it is called? Thanks. Please don't downvote this, I really want to know and a search didn't turn up anything definite. ...

Can python script know the return value of C++ main function in the Android enviroment

python,c++
There are several ways of calling C++ executable programs. For example, we can use def run_exe_return_code(run_cmd): process=subprocess.Popen(run_cmd,stdout=subprocess.PIPE,shell=True) (output,err)=process.communicate() exit_code = process.wait() print output print err print exit_code return exit_code to process a C++ executable program: run_exe_return_code('abc') while abc is created by the following C++ codes: int main() { return 1;...

How can I convert an int to a string in C++11 without using to_string or stoi?

c++,string,c++11,gcc
I know it sounds stupid, but I'm using MinGW32 on Windows7, and "to_string was not declared in this scope." It's an actual GCC Bug, and I've followed these instructions and they did not work. So, how can I convert an int to a string in C++11 without using to_string or...

Passing iterator's element to a function: wrong type of pointer

c++,pointers,stl,iterator
I'm attempting to solve Project Euler's problem #3 using C++ to gain an understanding of how to use C++ iterators. According to the examples I've seen online, I can use the dereferened iterator as a parameter for cout, and it will print the elements successfully. By that same logic, I...

Add a matrix of 2x2 into a vector in c++

c++,matrix,vector
I am trying to fill a vector with a matrix of values in c++. I'm not very self confident with this procedure (I don't know well about pointers and I don't know if I need it here) however I am trying this int auxMat[gray.rows][gray.cols]; vector<int> collectionSum; collectionSum.push_back(auxMat); When I try...

Parameters to use in a referenced function c++

c++,pointers,reference
I am very confused as to what kind of variables I would put into my function here: names. I am doing a practice problem in a C++ book, because I am learning C++ and am on References and pointers right now, and cannot find a solution. Just for background information,...

In c++11 what should happen first: raw string expansion or macros?

c++,c++11,preprocessor,rawstring
This code works in visual c++ 2013 but not in gcc/clang: #if 0 R"foo( #else int dostuff () { return 23; } // )foo"; #endif dostuff(); Visual C++ removes the if 0 first. Clang expands the R raw string first (and never defining dostuff). Who is right and why?...

c++ extend constructor of same class (no inheritance)

c++,constructor
I might have found my answer somewhere here, but nevertheless, I'd like to be sure. I am making something represented in a graph (hence the nodes), and I wondered if this code of the constructors is working the way I think. G++ doesn't complain. I have the following class: #ifndef...

Why are shaders and programs stored as integers in OpenGL?

c++,opengl,opengl-es,integer,shader
I'm following the "OpenGL Superbible" book and I can't help but notice that when we create a shader and create the program that we attach the shaders to, we store them as GLuint which are unsigned integers. Why are they stored as numbers? What does the value of the number...

How does a constructor choose a base class constructor in C++

c++,constructor
If you are inside the constructor of a derived class, and you make no explicit call to the base class constructor, how does the compiler know which base constructor to use?