Speaking as someone who's had to do exactly what you're talking about a number of time, rr got it basically right, but I would change the emphasis a little. For file versioning, text is basically the winner. Since you're using an hdf5 library, I assume both serializing and parsing are...
This question seems not specific to sockets, but to global variables in general. If you need to create a global variable (a socket, in this case) which must be accessible by multiple compilation units: You define the global variable in one single compilation unit (i.e. one cpp file) You declare...
Mentioned solution with fseek is good. However, it can be very slow for large matrices (as disks don't like random access, especially very far away). To speed up things, you should use blocking. I'll show a basic concept, and can explain it further if you need. First, you split your...
c++,opengl,opengl-es,integer,shader
These integers are handles.This is a common idiom used by many APIs, used to hide resource access through an opaque level of indirection. OpenGL is effectively preventing you from accessing what lies behind the handle without using the API calls. From Wikipedia: In computer programming, a handle is an abstract...
As @101010 hints at: pay is a string, while hours_day is a float, and while some languages allow you to multiply strings with integers, c++11 (or any other flavor of c) doesn't, much less allow strings and floats to be multiplied together.
No, you have to say p->~SomeClass(); operator delete(ptr);, where p = static_cast<SomeClass*>(ptr).
What you're trying to do makes little sense. We have subclass<int>. It is convertible to int&, but also to a lot of other reference types. char&. bool&. double&. The ambiguity arises from the fact that all the various overloads for operator<< that take any non-template argument are viable overload candidates...
You need to know the camera's intrinsic parameters, so that you can also know the distance between pixels in the same units (mm). This distance between pixels is obviously true for a certain distance from the camera (i.e. the value of the center pixel) If the camera matrix is K...
your code works for me. But you used cv::waitKey(0) which means that the program waits there until you press a keyboard key. So try pressing a key after drawing, or use cv::waitKey(30) instead. If this doesnt help you, please add some std::cout in your callback function to verify it is...
Simply create a normal class without static methods, ditch the singleton pattern aside, and create an instance. The burden of singleton pattern usually outweigh any benefit....
You could use std::promise and std::future (or their boost counterparts if your are not yet on C++11). The idea is to store a std::shared_ptr<std::promise<bool>> with the current sequence id as a key in the map whenever a request is sent. In the blocking send function you wait for the corresponding...
c++,long-integer,modulus,integer-overflow
Many compilers offer a 128-bit integral type. For example, with g++ you can make a function static inline int64_t mulmod(int64_t x, int64_t y, int64_t m) { return ( (__int128_t)x * y) % m; } Aside: if you can, try to stick to unsigned integer types when you're doing modular arithmetic....
This code works fine for a right angled triangle - * ** *** But I guess you want a triangle like this - * *** ***** Try this - #include <iostream> using namespace std; int main() { int i, j, k, n; cout << "Please enter number of rows you...
It doesn't work. That way you simply suppress the warning by making the situation harder to analyze. The behavior is still undefined.
The main reason to do something like this is to specialize void integerA(int x) to do something else. That is, if the programmer provides as input argument an int to member function abc::integerA then because of the C++ rules instead of instantiating the template member function the compiler would pick...
Similar to @GPPK's optional method, you can hack it by: Mat tmp, dst; c.convertTo(tmp, CV_64F); tmp = tmp / 8 - 0.5; // simulate to prevent rounding by -0.5 tmp.convertTo(dst, CV_32S); cout << dst; ...
Yes you can as of C++11 standard. Wiki article. Also a quick empirical verification: using namespace std; class A { public: A() { cout << "Hello "; } A(int x) : A() { cout << "World!" << endl; } }; int main() { A a(1); return 0; } Prints: Hello...
Plenty of solutions are possible. A geometric approach would detect that the one moving blob is too big to be a single passenger car. Still, this may indicate a car with a caravan. That leads us to another question: if you have two blobs moving close together, how do you...
Basically, you are finding all permutations of the array using a recursive permutation algorithm. There are 4 things you need to change: First, start your loop from pos, not 0 Second, swap elements back after recursing (backtracking) Third, only test once you have generated each complete permutation (when pos =...
The simplest thing you can do is to use a for/while loop. A loop will basically repeat the same instruction for a number of n steps or until a certain condition is matched. The solution provided is pretty dummy, if you want to read the first name and last name...
c++,inheritance,constructor,subclass,superclass
This map: typedef map<string, Object> obj_map; only stores Object objects. When you try to put an Image in, it is sliced down and you lose everything in the Image that was not actually part of Object. The behaviour that you seem to be looking for is called polymorphism. To activate...
QCoreApplication::applicationDirPath() returns the exact directory path of your app, for example H:/programs if your app path is H:/programs/ftpserver.exe so if you modify that QString you can get the root dir. For example: QString rootPath = QCoreApplication::applicationDirPath(); rootPath.chop(rootPath.length() - 3); //we leave the 3 first characters of the path, the root...
This macro is designed to validate a certain real parameter passes a certain validation rule(s). The logic part of the macro is composed of 2 parts: Validate that param is a real parameter, with a valid name. This is done by using the static_cast, and if an illegal name is...
Your first problem is C++ name mangling. If you run nm on your .so file you will get something like this: nm test.so 0000000000000f40 T __Z3funv U _printf U dyld_stub_binder If you mark it as C style when compiled with C++: #ifdef __cplusplus extern "C" char fun() #else char fun(void)...
I think you just misspelled CFLAGS in CFLAGES=-c -Wall I'm guessing this is the case since g++ ../src/main.cpp -I ../include/ does not have the -c option...
c++,templates,struct,const,extern
This is one of the parts of the standard that changed from C++03 to C++11. In C++03, [temp.arg.nontype] reads: A template-argument for a non-type, non-template template-parameter shall be one of: [...] [...] the address of an object or function with external linkage, including function templates and function template-ids but excluding...
If a base class is not mentioned in the constructor initializer list, it will be default initialized. Since the base class will definitely be of class type, that means that the default constructor will be called. Two of those references also have examples of derived classes which implicitly call the...
c++,templates,language-lawyer,c++14,friend
It doesn't have to be in namespace A. I think the confusion might come from this sentence from [namespace.memdef]/3: If the name in a friend declaration is neither qualified nor a template-id and the declaration is a function or an elaborated-type-specifier, the lookup to determine whether the entity has been...
c++,templates,constructor,explicit-instantiation
When the constructor is a template member function, they are not instantiated unless explicitly used. You would see the code for the constructor if you make it a non-template member function. template<typename T> class test { public: /*** template<typename T> test(T param) { parameter = param; }; ***/ test(T param)...
You cannot push back a matrix into a vector. What you can do is preallocate memory for your vector (for speeding things up) then use the std::vector<>::assign member function to "copy" from the matrix into the vector: vector<int> collectionSum(gray.rows * gray.cols); // reserve memory, faster collectionSum.assign(*auxMat, *auxMat + gray.rows *...
c++,date,datetime,time,converter
There are 86400 seconds in a day, and 25569 days between these epochs. So the answer is: double DelphiDateTime = (UnixTime / 86400.0) + 25569; You really do need to store the Unix time in an integer variable though. ...
You need to create new slot for that purpose. But in C++ 11 and Qt 5 style you can use labmdas! It is very comfortable for such short functions. In your case: connect(ui->horizontalSlider, &QSlider::sliderMoved, this, [this](int x) { this->ui->progressBar->setValue(x / 2); }); ...
Change this: [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 36)] private string iu; to this: [MarshalAs(UnmanagedType.LPStr)] private string iu; Note that this code is good only to pass a string in the C#->C++ direction. For the opposite direction (C++->C#) it is more complex, because C# can't easily deallocate C++ allocated memory. Other important thing:...
With regards to how to create an array of matrices, you are asking how to create a C array for a C++ data structure. Calling malloc will not correctly initialize the matrices in the array, nor calling "free" will deallocate dynamic memory if instances of ublas::matrix uses it, both failure...
c++,geometry,quaternions,euler-angles
The quaternions -q and q are different; however, the rotations represented by the two quaternions are identical. This phenomenon is usually described by saying quaternions provide a double cover of the rotation group SO(3). The algebra to see this is very simple: given a vector represented by quaternion p, and...
It really depends what you want to do. Make a vector of length 5, filled with ones: std::vector<int> vec(5, 1); Grow a vector by 5 and fill it with ones: std::vector<int> vec; // ... vec.insert(vec.end(), 5, 1); Or resize it (if you know the initial size): std::vector<int> vec(0); vec.resize(5, 1);...
The function will be called along with other static initializers, before main() starts. You don't risk anything more than with other means of static initialization. Keep in mind tough that all static initializers should be designed to avoid triggering a SIOF -- Static Initialization Order Fiasco. Static initializers in the...
For your android problem you can use fb-adb which "propagates program exit status instead of always exiting with status 0" (preferred), or use this workaround (hackish... not recommended for production use): def run_exe_return_code(run_cmd): process=subprocess.Popen(run_cmd + '; echo $?',stdout=subprocess.PIPE,shell=True) (output,err)=process.communicate() exit_code = process.wait() print output print err print exit_code return exit_code...
The only error that I see is this>current_generation_.end() instead that ->. In addition you should consider declaring your compare fuction as accepting two const FPGA* instead that just FPGA*. This will force you to declare fitness() as const int fitness() const but it makes sense to have it const. Mind...
Converting comments into answer: condition_variable::wait(lock, pred) is equivalent to while(!pred()) wait(lock);. If pred() returns true then no wait actually takes place and the call returns immediately. Your first wake is from the notify_one() call; the second "wake" is because the second wait() call happens to execute after the Stop() call,...
Your program is not ill-formed because <vector> is guaranteed to include <initializer_list> (the same is true for all standard library containers) §23.3.1 [sequences.general] Header <vector> synopsis #include <initializer_list> ... Searching the standard for #include <initializer_list> reveals the header is included along with the following headers <utility> <string> <array> <deque> <forward_list>...
Yes, those objects still exist and you must delete them. Alternatively you could use std::vector<std::unique_ptr<myObject>> instead, so that your objects are deleted automatically. Or you could just not use dynamic allocation as it is more expensive and error-prone. Also note that you are misusing reserve. You either want to use...
c++,templates,c++11,metaprogramming
You can do this without recursion by simply expanding the parameter pack directly into a std::tuple: template<My_enum... Enums> struct Tuple { using type = std::tuple<typename Bind_type<Enums>::type...>; }; To answer your question more directly, you can declare a variadic primary template, then write two specializations: for when there are at least...
c++,c++11,preprocessor,rawstring
GCC and clang are right, VC++ is wrong. 2.2 Phases of translation [lex.phases]: [...] The source file is decomposed into preprocessing tokens (2.5) and sequences of white-space characters (including comments). Preprocessing directives are executed, [...] And 2.5 Preprocessing tokens [lex.pptoken] lists string-literals amongst the tokens. Consequently, parsing is required to...
It is very bad, accessing deleted objects as if they were not deleted will in the general case crash. There is no guarantee that the memory is still mapped inside the process and it could result in a virtual memory page fault. It is also likely that the memory will...
int wordCounter(char usStr[]) { int index= sizeof(usStr); int result = 0; for (int i=0; i<index; i++){ if(usStr[index]== ' ') result++; }//end of the loop return result+1; } //try this one. ...
A workaround is to modify the sudoers file and remove the requirement of a password from your user ID for a particular script to have sudo privileges. Enter sudo visudo After this, add the details in the following manner. username ALL=(ALL) NOPASSWD: /path/to/script Another method would be to pipe the...
I see several possible causes. First of all, casting char* to double* and then accessing it through that pointer is undefined behavior. Most of time it works, but you are warned. Pointer misalignment. double is most likely supposed to be aligned to 8 bytes, and you read it through pointer...
If you want a sequence of int, then use a vector<int>. Using the key_char string, the values of the chars in it will serve as the initial value of the ints. std::vector<int> key_num(key_char.begin(), key_char.end()); Then, iterate over each character of key_num and convert it to the equivalent int value for...
Preferred option: change isPrime to take a long (and pass *it to it). Secondary option: pass &*it instead of it. Your original code doesn't work because it is an iterator (which is a class) whereas the function expected long int * and there is no implicit conversion from iterator to...
You cannot load a 64 bit DLL into a 32 bit process. Or indeed vice versa FWIW. It follows that you'll need two processes and IPC. An out of process COM server would probably be the simplest way to proceed. ...
Removing BreakBeforeBraces: Allman Seems to do what you want (for me). I'm using SVN clang though. Although you probably wanted it there for a reason. According to the clang-format docs, the AllowShortBlocksOnASingleLine should do exactly what you want (regardless of brace style). This might be a bug in clang-format....
c++,time,standards,chrono,time-t
The type of std::time_t is unspecified. Although not defined, this is almost always an integral value holding the number of seconds (not counting leap seconds) since 00:00, Jan 1 1970 UTC, corresponding to POSIX time. So, just a safe casting between them could be fine. Also be carefull about portability...
c++,string,c++11,memory,standards
Section 21.4.1.5 of the 2011 standard states: The char-like objects in a basic_string object shall be stored contiguously. That is, for any basic_string object s, the identity &*(s.begin() + n) == &*s.begin() + n shall hold for all values of n such that 0 <= n < s.size(). The two...
If I read this translation phase reference correctly, then the sequence // \u000d some code here is mapped in phase 1 to itself, i.e. the parser does not translate or expand \u000d. Instead the translation of such sequences happens in phase 5, which is after the comments are replaced by...
c++,gcc,g++,c++14,predefined-macro
According to the GCC CPP manual (version 4.9.2 and 5.1.0): __cplusplus This macro is defined when the C++ compiler is in use. You can use __cplusplus to test whether a header is compiled by a C compiler or a C++ compiler. This macro is similar to __STDC_VERSION__, in that it...
This happens because the compiler will prefer built-in conversions to user-defined conversions. The conversion from a pointer to a bool is built-in, so that overload is selected rather than constructing a std::string. You could add an overload which takes a const char* and forwards it to the std::string version: void...
You forgot the return statement in the function bool func(const pair<int,pair<int,int> >&i , const pair<int,pair<int,int> >&j ) { i.second.first < j.second.first ; } Write instead bool func(const pair<int,pair<int,int> >&i , const pair<int,pair<int,int> >&j ) { return i.second.first < j.second.first ; } Also you should include header <utility> where class std::pair...
You should use the random header. #include <random> std::default_random_engine generator; std::uniform_int_distribution dist(0, 5); int StringIndex = dist(generator); std::string ChosenString = characters[StringIndex]; The above will generate a random index into your array. If you want to limit the range, change the constructor of dist, for example (dist(0,2) would only allow for...
c++,templates,template-specialization
The specialization still needs to be a template template argument. You passed in a full type. You want: template <class Type, class Engine> class random_gen<std::uniform_real_distribution, Type, Engine> { ... }; Just std::uniform_real_distribution, not std::uniform_distribution<Type>. ...
c++,inline,private,member,protected
The Compiler can Access everything. The restrictions are only valid for the programmer. This means there are no restrictions for the Compiler to Access any variables! At the end every variable is just translated to an address which can be accessed. So for the Compiler it is no Problem to...
I think you just need some clarification about GDI. A DC is exactly what its name imply : a device context. It's just a context, nothing concrete. Some DCs are context to a real graphic device, some others (memory DCs) are context to a virtual graphic surface in memory. The...
toupper returns int. You need to cast the return value to char such that the output stream operator << prints out the character and not its numeric value. You should also cast the input to unsigned char, to cover the case where char is signed and your character set includes...
Are DETUNE1 and DETUNE2 calculated every time it is called? Very unlikely. Because you are calling sqrt with constants, most compilers would optimize the call to the sqrt functions and replace it with a constant value. GCC does that at -O1. So does clang. (See live). In the general...
The fanciest way I've seen to perform what you want is straight from the boost filesystem tutorial. In this particular example, the author appends the filename/directory to the vector and then utilizes a std::sort to ensure the data is in alphabetical order. Your code can easily be updated to use...
Your error is actually coming from: array.push_back(day); This tries to put a copy of day in the vector, which is not permitted since it is unique. Instead you could write array.push_back( std::move(day) ); however the following would be better, replacing auto day...: array.emplace_back(); ...
You have declared coordinate startPt, endPt; in main() and you are trying to access them Readcoordinate(). To resolve error you should declarecoordinate startPt, endPt;inReadcoordinate()` or pass them as argument. coordinate Readcoordinate() { coordinate startPt; cout << "Enter Longitude(in degrees)" << endl; cin >> startPt.latitude >> startPt.longitude >> startPt.city; return startPt;...
I am assuming your pointer refers to 20 bytes, for the 160 bit value. (An alternative may be text characters representing hex values for the same 160 bit meaning, but occupying more characters) You can declare a class for the data, and implement a method to increment the low order...
You're not using the function setText correctly. The canonical prototype is text(QString & subtype, Mode mode = Clipboard) const from the documentation. What you want to do is assemble your QString ahead of time and then use that to populate the clipboard. QString message = QString("Just a test text. And...
c++,pointers,pass-by-reference,undefined-behavior,const-iterator
The code is perfectly fine. You're not stripping away any constness (there's no way to do that implicitly in C++). *it gives you a const intp &. You're copying the pointer referred to by that reference into arg. Copying from something does not strip constness away. The assignment to arg...
The first obvious mistake you're doing here is this: char* temp = new char[255]; temp = this->c_str(); You allocate memory then you're copying the value of a pointer. So first you're getting a memory leak and second depending on your implementation of c_str() you are copying the address of something...
Use stoi, it's the modern C++ version of C's atoi. Update: Since the original answer text above the question was amended with the following error message: ‘stoi’ was not declared in this scope Assuming this error was produced by g++ (which uses that wording), this can have two different causes:...
If this is interview question or something , and you have to do it anyways , you can do this like ,below code . derive from std::stack , and overload [] operator #include <iostream> #include <algorithm> #include <stack> #include <exception> #include <stdexcept> template <typename T> class myStack:public std::stack<T> { public:...
There are no operator[] of std::map which is const, you have to use at or find: template<> struct Record::getDispatcher<std::string> { static std::string impl(Record const& rec, std::string& const field) { return rec.fieldValues_.at(field); // throw if field is not in map. } }; or template<> struct Record::getDispatcher<std::string> { static std::string impl(Record const&...
The A[32] in the method is actually just a pointer to A. Therefore, sizeof is the size of *int. Take the following test code: void szof(int A[32]) { std::cout << "From method: " << sizeof(A) << "\n"; } int main(int argc, char *argv[]) { int B[32]; std::cout << "From main:...
You have to specify a version of the function without args: #include <iostream> template <typename... Args> void foo(Args&&... bargs, Args&&... aargs) { std::cout << "Hello with args" << std::endl; } void foo() { std::cout << "Hello without args" << std::endl; } int main() { foo<int, double>(1, 2.0, 3, 4.0); //OK...
If you can use boost library you could simple do it like this: string date("2015-11-12"); string format("%Y-%m-%d"); date parsedDate = parser.parse_date(date, format, svp); You can read more about this here. If you want a pure C++ solution you can try using struct tm tm; std::string s("2015-11-123"); if (strptime(s.c_str(), "%Y-%m-%d", &tm))...
i dont think you can just input a raw file to glTexImage2D, except if you store texture files in that format (which you probably dont). glTexImage2D expects a huge array bytes (representing texel colors), but file formats typically dont store images like that. Even bmp has some header information in...
The header file provides enough information to let you declare variables. And for that matter to just compile (but not link) code. When you link, the linker has to resolve e.g. function references such as a reference to ServerConnection::getLicenceRefused, by bringing in the relevant machine code. You have to tell...
Your code makes no sense, why are you passing someStruct twice? For the reference part, you should have something like: void names(someStruct &s) { // <<<< Pass struct once as a reference cout << "First Name: " << "\n"; cin >> s.firstname; cout << "Last Name: " << "\n"; cin...
The valid range of indices of an array with N elements is [0, N-1]. Thus instead of for example this loop for (int i=1; i <= n; i++) ^^^^ ^^^^^^ you have to write for ( int i = 0; i < n; i++ ) As you used operator new...
The while true loop is definitely not good practise, I'd suggest doing something like this. But you should make it in the same structure as Michael's answer above like this: void reroll(int lastNumber, int amountOfNumbers) { int newRand = std::rand() % (amountOfNumbers); while (newRand == lastNumber) { newRand = std::rand()...
c++,algorithm,parallel-processing,c++14
Parallel prefix sum is a classical distributed programming algorithm, which elegantly uses a reduction followed by a distribution (as illustrated in the article). The key observation is that you can compute parts of the partial sums before you know the leading terms.
c++,polar-coordinates,cartesian-coordinates
You are converting to cartesian the points which are in cartesian already. What you want is: std::cout << "Cartesian Coordinates:" << std::endl; std::cout << to_cartesian(to_polar(a)) << std::endl; std::cout << to_cartesian(to_polar(b)) << std::endl; //... Edit: using atan2 solves the NaN problem, (0, 0) is converted to (0, 0) which is fine....
Your issue is that std::deque (and other standard containers) doesn't just take a single template argument. As well as the stored type, you can specify an allocator functor type to use. If you don't care about these additional arguments, you can just take a variadic template template and be on...
Its not the fastest method but you can do this: #include <string> #include <sstream> #include <iostream> template<typename ValueType> std::string stringulate(ValueType v) { std::ostringstream oss; oss << v; return oss.str(); } int main() { std::cout << ("string value: " + stringulate(5.98)) << '\n'; } ...
int C::* is a pointer to a member of class C whose type is int. Example: struct C { C () : a(0), b(0) {} int a; int b; }; int main() { int C::*member1 = &C::a; int C::*member2 = &C::b; C c1; c1.*member1 = 10; // Sets the value...
c++,casting,parameter-passing,pass-by-reference
In the first example, you're actually passing the pointer variable b. So it works. In the second example, the first reinterpret_cast returns a pointer (by value), which doesn't match the reference the function should get, while the second returns said reference. As an example to show you how references work,...
(Edited away first "answer", this is an actual attempt at an answer) My guess: QList<Msg> messages() const { return _messages; } It's returning a copy of the QList _messages, rather than a reference to it. I'm not sure that it would give the results you're seeing, but it looks wrong...
You should always do things that improve the readability and understandability of your code when first learning a language. (And, in many cases, well beyond that point.) Readability of code should be your number one priority at this point. That being said, functions do not really cost any more time...
c++,arrays,multidimensional-array,initialization
If you want to copy the values of temp array , instead of "=", you should use memory copy memcpy( test[i], temp, sizeof(temp[192])); ...
c++,templates,generic-programming
This depends on what you want the behaviour (protocol) of your class to be. Since you're logging into the error stream there, I assume you consider this an error condition to call pop() on an empty stack. The standard C++ way of signalling errors is to throw an exception. Something...