question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
63,015,678
63,015,866
Overloaded child class function cannot call parent of similar name
I am assuming this is one of those "just not how it works" issues, but I fail to see why. Why do I need to qualify B's call to As Start with A::. If I change B::Start() to B::DoSomethingElse() I could call a parameter less Start() without A::. So what is happening? #include <iostream> #include <string> class A { pub...
From the C++ standard (draft, emphasis mine) [basic.lookup.unqual]/1: In all the cases listed in 6.4.1, the scopes are searched for a declaration in the order listed in each of the respective categories; name lookup ends as soon as a declaration is found for the name. If no declaration is found, the program is ill-for...
63,016,020
63,016,289
How to link .h files in vs code?
I am new in C++ and I have three files main.cpp, npc.cpp and npc.h. I tried to run it and this error appears: main.cpp:2:10: fatal error: npc.h: No such file or directory 2 | #include "npc.h" | ^~~~~~~ compilation terminated. Here is my main.cpp: #include <iostream> #include "npc.h" int main(int argc, ch...
A very simple solution to this problem is to execute the following command: g++ -o main main.cpp npc.cpp && ./main This will tell the compiler to link npc.cpp file with the main executable. The error was producible in my machine when I didn't include npc.cpp in the command line: g++ -o main main.cpp && ./main This th...
63,016,144
63,016,330
Array isn't free'd after going out of scope
I have a simple char array used to read from a pipe. This array is used in an infinite while cycle int main() { mkfifo("process1_write", 0666); mkfifo("process1_read", 0666); int fd1,fd2; fd1 = open(process1_write, O_RDWR); fd2 = open(process1_read, O_RDONLY| O_NONBLOCK); std::string o...
The following: while (1) { char str1[1050]; allocates on the function call stack, but does it like this: char str1[1050]; while (1) { So the location is reused, and only about 1050 bytes callocated. The problem is, that for strings a nul terminator is needed: int in = read(fd2, str1, 1024); if (in > 0) ...
63,016,274
63,018,285
link error when using random_device from boost
I have installed on MacOSX 10.15 boost using brew, all working fine, beside random_device. This is what i have written: #include <iostream> #include <boost/random/mersenne_twister.hpp> #include <boost/random/discrete_distribution.hpp> #include <boost/random/random_device.hpp> int main() { boost::random::random_dev...
Edit your CMakeLists.txt with the following code: find_package(Boost 1.72 COMPONENTS random) if(Boost_FOUND) include_directories(${Boost_INCLUDE_DIRS}) target_link_libraries(test_boost ${Boost_LIBRARIES}) endif()
63,016,641
63,019,197
Can't support both OpenMP v4 and v5 in GCC
I've come across an unusual problem in trying to make my C/C++ project support both gcc-8 (with OpenMP 4.5) and gcc-9 (with OpenMP 5.0). It is caused by variables defined as const which are to be shared between threads. For example, here's some code compatible with OpenMP 5, but fails with OpenMP 4.5 (with error 'x' is...
Porting to gcc-9 is addressed here. To maintain compatability with both versions of OpenMP, I'll have to either: remove default (none) remove all const
63,016,744
63,125,605
Exception 0x00000004 (sfml-graphics-2.dll) occuring after compilation
Recently, I've started to learn SFML. The first thing I wanted to do was a simple menu - so I've created an interface for all menus, containing everything necessary for other menus in protected field. However, my code throws an exception at some point, and I have no idea, why. #include <SFML/Graphics.hpp> #include <ios...
The main issue I can see is that in the constructor of FirstMenu you are sf::Font font; if (!font.loadFromFile("arial.ttf")) { std::cout << "Font error. \n"; } text.setFont(font) Essentially setting the text's font to a local font object. This is problematic because text in SFML doesn't copy the passed in font res...
63,016,784
63,032,634
Can't call java methods from c++ wrapper in JNI
I'm new in JNI and c++. I have some api that required shared pointer with some handler to subscribe on some messages. I can call required method in my handler in "main" c++ method, but when I call it from c++ wrapper I get JVM error and my application crash. My native method is next: public native int subscribe(Handler...
Finally, I wrote working code. In the native method it is required to retrieve and save JVM variable (which can be shared between threads) to retrieve JNIenv (which can't be shared between threads) when it will required in another thread: JNIEXPORT jint JNICALL Java_com_lib_NativeClient_subscribe (JNIEnv* env, jobject ...
63,017,208
63,017,314
How to declare a C++ variable type based on platform?
I'm trying to write some C++ code that will work on both Windows and Linux. I currently have this: #ifdef WINDOWS HINSTANCE _handle; #else void* _handle; #endif Is it possible to declare the type to be conditional based on the platform instead so that i could do something like: #ifdef WINDOWS //define TYPE = HI...
Do you mean something like: #ifdef WINDOWS typedef HINSTANCE TYPE; #else typedef void* TYPE; #endif TYPE _handle; Or, if you prefer using (altough in this context there is no difference): #ifdef WINDOWS using TYPE = HINSTANCE; #else using TYPE = void*; #endif
63,017,261
63,018,927
Writing a binary archive into a shared memory with BOOST::serialization
I am currently trying to serialize data as a binary archive into a shared-memory-segment with the BOOST library. I successfully implemented the functionality with a text_oarchive()-method as seen below. Now I wanted to use the binary_oarchive()-method instead of text_oarchive()-method. shared_memory_object::remove("shm...
I cannot reproduce the error you describe: Compiling On Coliru Using a filemapping allows us to even run it on COLIRU: Live On Coliru Prints 00000000: 3232 2073 6572 6961 6c69 7a61 7469 6f6e 22 serialization 00000010: 3a3a 6172 6368 6976 6520 3137 2030 2030 ::archive 17 0 0 00000020: 0a00 0000 0000 0000 0000 0000 000...
63,017,294
63,017,435
Pass stl container with ANY template parameter list into a structure
I want to implement custom "at" method, which gives more informative exception if some key does not exists in some container (in particular vector/map/deque/unordered_map). However, in my project i have to do some casting of key types (i.e passing int variable as a key to std::map<uint16_t, some_type>) and there is to...
using CKeyType = ContainerTraits<container>::KeyType; should instead be: using CKeyType = ContainerTraits<CntT>::KeyType; Also (typo): const bool valueExist = IsExists(container, safeKey); should be: const bool valueExists = IsExists(container, safeKey); But the most problematic line is this one: const auto safeKey ...
63,017,359
63,017,490
C++11 References variables as lvalues. Are they really "vars" or are only "alias"?
Well, the question is in the title. If i have the following code in c++11: int a, b = 20; int &ra = a; ra = b; std::cout << ra << std::endl; //Prints 20 how is the "ra" handled by the compiler, does it create another var as a pointer or it's just an alias and when the compiler finds "ra" is the same as saying "a"?...
Yes. And, no. Hehe. Read on. There are two layers of abstraction at work here, and you should try to understand both of them. The language When you write C++, you're describing a program. You're not actually writing instructions for a computer to execute. That's the compiler's job. In your C++ code, ra is just an alias...
63,017,415
63,017,495
Howto use non-static member function for template argument?
I have this minimal sample code: #include <functional> #include <iostream> #include <vector> template<class ReadFileCallback> void fileMgr_ReadWithCallback(std::string filename, ReadFileCallback callback) { callback("OK"); } void globalReadResult(std::string result) { std::cout << "ReadResult in global funct...
You can just wrap it into a lambda: class MyClass { public: MyClass() {}; ~MyClass() {}; void Read() { fileMgr_ReadWithCallback("file", [this](const std::string& result){ this->ReadResult(result); }); } void ReadResult(std::string result) { std::cout << "ReadResult in member function: result=" <...
63,017,620
63,017,847
What is n= n ^1U<<i?
The problem I am facing here is to understand the change in the value of n in each iteration of the loop. If you explain it by taking 2-3 iteration that will be awesome. correction -return value should be of 32 bit ....which is altering all bits 0->1 ans 1->0 . long fun(long n) { for(int i = 0; i < 32; i++) ...
i is counting. 1U << i is a single unsigned bit (LSB), which gets shifted in each turn by i to the left, i.e. it scans the bit positions, 0001, 0010, 0100, 1000 (read as binary please). n = n ^ 1U << i sets n to a XOR of n and the shifted bit. I.e. it XORs n bit by bit completely. The result is a completely inverted n....
63,017,719
63,118,360
can't include std::format
I have seen how useful std::format can be. But every time I try to include it on C++20 it does not work. it is apparently already included in its libraries but it does not appear, and there is no information online. Even cppreference has its example but it does not even run on its online compiler. I attached a snippet ...
As of July 2020 none of the standard library implementations provide std::format. Until they do you can use the {fmt} library std::format is based on: #include <iostream> #include <fmt/core.h> int main() { std::cout << fmt::format("Hello {}!\n", "world"); } godbolt
63,018,420
63,019,362
Error while integrating google test into existing CMake project
I have a working project and I want to add google test into it, but one difference is, my main() function is in a different file. This is my project structure: -test - include - file.h - file1.h - file2.h - file.cpp - file1.cpp - file2.cpp - main.cpp - CMakeLists.txt ...
The following line in your unitTest/CMakeLists.txt file is leading to behavior you may not expect: include(${CMAKE_CURRENT_SOURCE_DIR}/../CMakeLists.txt) From the documentation for include, this command will: Load and run CMake code from a file or module. This command is typically reserved for loading CMake Find Mod...
63,018,622
63,018,812
C++ thread lambda captured object can read but cannot erase
I'm new in c++ so my problem could be very simple but I cannot solve it. In my constructor I want to start detached thread which will be looping with class variable and removing old data. userCache.hpp struct UserCacheItem { long m_expires; oatpp::Object<User> m_user; UserCacheItem(const long expires, cons...
You cannot modify the map while you're iterating it for(auto &elem : m_userCacheItem){ if (curTimestamp > elem.second->m_expires){ std::cout << "Erasing element: " << elem.second->m_expires << std::endl; m_userCacheItem.clear(); } ...
63,018,847
63,018,894
C++ enum class with constructor
In Java, you can write a constructor for an enum, e.g. private MyEnum(String name, int val) { ... } And then you can write: public enum MyEnum { FIRST("A", 10), SECOND("B", 20), THIRD("C", 30); private MyEnum(String name, int val) { ... } } Is there any way you can do a similar thing for a C+...
No, C and C++ enums are just a bunch of constants grouped together. C++ enum classes are the same, but to access them you need to add the name of the enum class as a "namespace".
63,018,986
63,019,063
What makes a heap allocated object "referenced" in C++?
What, in C++, determines that a heap allocated object to be referenced? In his book, Data Structures and Algorithm Analysis in C++, Mark Allen Weiss writes "When an object is allocated by new is no longer referenced, the delete operation must be applied to the object (through a pointer)" I find this sentence a bit conf...
I wouldn't get too obsessed with the precise choice of language there. What he's trying to say is that if you allocate an object on the heap, it's your responsibility to de-allocate it when you're done with it. Otherwise, it will remain valid and waste memory. You can be completely done with an object even though it's ...
63,019,038
63,019,719
Is there a way to detect if object instance is deleted (in lambda)?
I have this small template function to store my callback function for later "callback". std::function<void(std::string)> stored_callback; template<class ReadFileCallback, typename Object, class ...T> void fileMgr_ReadWithCallback(std::string filename, ReadFileCallback callback, Object* object, T ...params) { std::...
Is there a way to detect if object instance is deleted Yes, so long as you manage its lifetime with shared_ptr, and optionally track it with weak_ptr when you don't want to extend that lifetime. There is no general way to do this for "unmanaged" objects, meaning those allocated and managed directly via raw pointers, ...
63,019,098
63,019,145
Object getting modified in Operator overloading
I've written this code to perform operations on complex numbers using operator overloading: #include<iostream> using namespace std; class Complex{ private: float real; float img; public: Complex():real(0),img(0){ } Complex(float real,float img):real(real),img(img){ ...
Your operator+ is modifying the left hand operand. Instead, you should create a new object and return that: Complex operator+(const Complex &other) const { //^^^^^ make sure not to change *this Complex ret; // create a separate object ret.real = this->real+other.real; ret.img...
63,019,101
63,019,228
C++ printing float as nan
This is a simplified C++ program converting 4 bytes into their IEE754 float representation. #include <iostream> #include <math.h> #include <memory.h> uint8_t bytes[4] = {0x40, 0xd5, 0xc6, 0x7f}; // 0x40d5c67f float f; int main() { memcpy(&f, &bytes[0], 4); printf("%.*lf", 5, f); } it's output is nan! isnan a...
If you are running this code on a machine that uses little-endian, higher digits of multi-byte numbers are stored in higher address of the memory. Therefore, on little endian machines, the 4-byte number on memory 0x40, 0xd5, 0xc6, 0x7f is treated as 0x7fc6d540, not 0x40d5c67f. Interpreting as IEEE754, the exponent part...
63,019,383
63,019,465
how to understand the syntax `Color (&EnumValuesColor())[3] {...}`?
this is an auto generated header (by flatbuffer serializer) and I've never seen any syntax like Color (&EnumValuesColor())[3] {...} could someone explain it ? enum Color { Color_Red = 0, Color_Green = 1, Color_Blue = 2, Color_MIN = Color_Red, Color_MAX = Color_Blue }; inline const Color (&EnumValuesColor())[...
It's not surprising that you don't recognise it; this is an example of some very arcane declarator shenanigans we inherited from C, relating to the so-called "spiral rule". What's happening here is: There is a function called EnumValuesColor It returns a reference to an array of 3 const Colors It's marked inline You ...
63,019,407
63,020,527
Arduino - Trouble with PROGMEM a avr/pgmspace.h
im trying to use progmem instead on static char to save some valueble space. Everything seems fine, but serial and lcd show some weird newline symbol instead of my text. What im trying to do: ... #include <avr/pgmspace.h> const static char PROGMEM textSDFailed[] = "Filesys failed"; const static char PROGMEM text...
You can use the print which takes a progmem string. The overloaded print for progmem string has __FlashStringHelper* as parameter. This is normally for the Arduino F() macro. For repeated use of the cast I do: #define FSH_P const __FlashStringHelper* Then I use it this way: lcd.print((FSH_P) textSDFailed); If you c...
63,019,455
63,021,633
How to fetch a row in an sqlite database in qt using cpp
How can I access a single row in sqlite database and return the data in a list. I have tried this QList<QVariant> DBManager::getUserData(QString usrNam, QString psswrd) { QSqlQuery query; query.prepare("SELECT First_Name, Last_Name, Email, Username, Password" " FROM Users WHERE Username = :usr...
If you want to access a single row, you don't need to use QSqlRecord. Just use QSqlQuery::first instead. Example: QList<QVariant> DBManager::getUserData(QString usrNam, QString psswrd) { QSqlQuery query; query.prepare("SELECT First_Name, Last_Name, Email, Username, Password" " FROM Users WHERE...
63,019,698
63,023,372
C++ have as parameters the subclasses of a given class
I'm making a threadpool and I have some methods that have to take as input objects that subclass the class Task. I have this class: struct Task { virtual ~Task() = default; virtual void run(); }; and the threadpool has a method like this: void submit(Task val); I would like to make jobs the threadpool has to exec...
A pure virtual class cannot be instantiated, because you would not have a definition for your pure virtual function. In order to take advantage of polymorphism, your submit function should take a pointer to Task as argument instead of instantiating a Task: void submit(std::shared_ptr<Task> val); I suggest you first re...
63,019,805
63,021,068
Logic behind v.size()-1?
I am learning C++ and the book said the last element in the vector is v[v.size()-1]. What is the logic behind this? Hows size-1 giving me the last element? Would it not give me second from the last element? Thanks
the book said the last element in the vector is v[v.size()-1] That's true, but only when v.size() > 0. If the vector is empty, its size is 0, but the value returned by std::vector::size() is of type std::vector::size_type which is an unsigned integer type (usually std::size_t), so that the result "wraps around" becom...
63,019,882
63,019,925
C++ code fails to compile with a min() function
I'm trying to make a calculator, that calculates the amount of pancakes you can make. You input the amount of eggs, milk and flour you have and it should output the amount of pancakes you can make, based on the values you input dived by the minimum amounts you need. To do that I have to find the smallest value you inpu...
If you want the minimum of more than 2 values, use the initializer_list overload from <algorithm>: std::cout << std::min({eggDiv, milkDiv, flourDiv});
63,019,949
63,020,021
Memory address of a pointer
I'm new to C++. I'm learning pointers, but I don't understand why this : cout << pointer <<endl; shows an address like this 0x171b20. My computer is 64bits, so a pointer needs 16 Hexadecimal digits to fully identify a single memory address. So I think that the c++ is only outputing a portion of the address ? Can you pl...
cout << pointer << endl will work to print out the full address of a pointer. However, the pointer does not have to have 8 non-zero bytes (16 hexadecimal digits). For example, in many programs, functions can have addresses like 0x0000000000401234, which will print out as 0x401234.
63,020,840
63,021,891
Why is it not possible to use Q_OBJECT with template classes?
There's a similar question here that was looking for a workaround and a nice guide here which describes the meta-object system in Qt.But that doesn't explain directly why is it not possible to use a template class in the meta-object system.That's an annoying restriction. Anyone know why ?
It is not possible* in standard Qt, as for Qt, as for these classes moc needs to be able to pre-process the class and generate the needed meta data structures. That is done before compilation, and for a template class that means that the type is not really defined yet. However, some things are possible: A QObject can ...
63,021,082
63,021,445
Word counter of a vector without map
How can I count the number of occurences of each word in a vector of words ? I was able to get all the words in the vector but now I can't count how many times each word occured. vector <Phrase> mots; // it's already filled with words of type Phrase (string) int count = 1; Phrase *word = &mots[0]; for (unsigned i = 1; ...
Well you can emulate a map<string, int> with a vector<pair<string, int>>, and you will ends up with something like this: std::vector<std::string> mots = {"a", "b", "c", "a", "c"}; // <- this is just for the example vector<pair<string, int>> counts; std::for_each(mots.begin(), mots.end(), [&](auto& el){ // <- for each w...
63,021,349
63,021,443
Does Visual Studio generate assembly from the C source or from the binary code it compiled into?
When I run my code (any code), in debug mode I have the option of "Disassembly". I know that "Disassembly" is the creation of assembly code from machine code ('1' and '0' that stored in object files). So, I can assume that when I compile my code in Visual Studio, there is no "Assembly/Assembler" stage between the C/C++...
When a debugger provides a disassembly option, it is generally examining memory of the running process, augmented by debugging information embedded in or associated with the executable file, which can include references that help the debugger identify associated source code. Separately, compilers usually have an option...
63,021,357
63,021,407
Validating if a JSON object is present in a file with nlohmann JSON C++ library
I have a project where I import JSON files to setup global variables. There are various possibilities to the JSON object names in the files, so I want to know how can I check if an object is there or not. The way I tried to do it (with an if statement as shown below) causes an error The program '..\..\build\jacky.exe' ...
if ( j.find("Shirt Size") != j.end() ) Or (this will create an entry if it does not already exist) if ( !j["Shirt Size"].is_null() )
63,021,685
63,369,348
Debug a C# dll called from C++ (with Mono embedded)
I have a runtime written in C++ (with Mono embedded) which calls functions in a dll written in C# using mono_jit_exec and mono_runtime_invoke. The glue code is generated with CppSharp - which I don't think is relevant here, but just to mention. So far all good, I can communicate in both directions. What I want now is ...
Ok, so the answer is that is currently not supported. A workaround would be to do remote debugging using a plugin for Visual Studio or Visual Studio Code, as Unity does. One available extension is VS Code Mono Debug, which is based on the SDB: Mono Soft Debugger Client.
63,021,846
63,232,859
How can I obfuscate an EXE file?
I have an EXE file. It comes from a Qt C++ Visual Studio project. I would like to obfuscate this EXE. The main reason is that my URLs (for version files, API etc.) that I use in the program and any other strings can be easily edited with a HeX editor. Thanks for your help.
I used UPX packer and it works well.
63,021,917
63,022,003
Why are declarations in a switch construct legal?
I have found multiple questions regarding the subject of defining variables inside a switch construct, but I have not yet found a clear answer to this question. Chapter 5.3.2 of the book C++ Primer says the following: As we’ve seen, execution in a switch can jump across case labels. When execution jumps to a particula...
Declaration is a compile-time thing, and what happens at runtime is irrelevant to that fact. i is visible at any point within the same or child scope after its declaration. There is nothing that causes a scope change between the two cases, so i remains visible in the false case regardless of whether the true case exec...
63,022,761
63,022,843
Cleanest method of inter-program communication on separate devices
I need to settle on a method of communication between multiple programs spread out over multiple machines. The data itself is fairly straight forwards, comprising of variable length vectors with some meta-data descriptors. Each program "type" will send data to 1 other program type, and expects to see a reply from it. T...
Perhaps taking a look at something well established (and therefore should be able to hook up to whichever language/s you end up using) like Redis or RabbitMQ would be wise seeing as you'll need to be able to communicate with a number of different devices over a network. Either way having some form of central hub that h...
63,022,791
63,022,864
generic lambdas in c++14
I'm trying to compile the following code in VS2019: auto moveToEnd = []<typename T>(std::vector<T>& into, std::vector<T>& from) { into.insert(std::end(into), std::make_move_iterator(std::begin(from)) , std::make_move_iterator(std::end(from))); }; However, I get an error: '<' skipping unexpected token/s be...
Those ain't the regular generic lambdas. Specifying the template parameter list for a lambda is a C++20 feature. The C++14 "generic lambdas" merely let you use auto in lambda parameters.
63,022,854
63,023,099
C++ Using MACRO without INCLUDE statement
In DirectX Graphics Samples MiniEngine sample, there is an "inline" source file Functions.inl that uses a macro INLINE that is defined in a header in same folder, Common.h . What mechanism/declaration permits Functions.inl to use INLINE without an #include "Common.h" statement? My specific issue is that I have created ...
"Math/Functions.inl" is not a source file. It is not compiled individually. It appears to be included, just like a header is. Let's take a look at how it is used: // Core/VectorMath.h #pragma once #include "Math/Scalar.h" ... #include "Math/Functions.inl" Unlike a header, it is not included into the top of the file, ...
63,023,161
63,023,570
How do I make a window inactive on Windows
I'm trying to create an C++ console app that shows itself when I press a button. However, when the app appears, it appears on top of all other windows. Is there a way I can prevent this from happening (i.e. have the window appear in the background)? Here is the part of the code that is important: ShowWindow(GetConsoleW...
You can call SetWindowPos in place of ShowWindow, specifying the SWP_SHOWWINDOW, SWP_NOZORDER, SWP_NOOWNERZORDER, and SWP_NOACTIVATE flags. This will show the window, without moving it up or down the Z order, or activating it.
63,023,230
63,023,582
How is linking failing: Undefined reference to library
I have inherited a code project that contains several individual libraries of code that compile separately and then are linked in the compiled tools. It's supposed to be a Chinese menu of what each tool wants. This all written on Linux, in C++, with Qt. There are several issues with the current design, but I'm learning...
You need to link the libraries in the right order - it sounds like Utilities.a needs to be linked last. I don't know how you do that in Qt but that's what you need to achieve.
63,023,879
63,024,167
Finding all the 3-combinations of the output of for loops
I feel like this is supposed to be very straightforward but I am unable to work it out. I have a very simple piece of c++ code. for (int k = 0; k < 2; ++k) { for (int a = 0; a < 4; ++a) { for (int b = 0; b < 4; ++b) { if (a != b) { ...
To make things easier, I'd group a k, a and b value together into a single object. Let's call it a K-A-B object, or a kab: struct kab { int k, a, b; }; Then, I'd make an increment function that'll take a kab and give us the next kab in the sequence. This'll allow us to condense all three of your loops down into on...
63,024,006
63,045,488
Cross compiling with CMake: linker errors
I am attempting to cross compile a project for my raspberry pi (32 bit armv8) on my ubuntu machine. I set up a toolchain using crosstool-NG and compiling works, but linking fails. My CMake toolchain file is as follows: SET(CMAKE_SYSTEM_NAME Linux) SET(CMAKE_SYSTEM_VERSION 1) set(CMAKE_SYSROOT /home/stone/development/r...
Alright I got it all figured out. The repo where I learned the tricks to getting this to work can be found here. I am grateful for this repo, without it I would not have gotten this to work. The issue lies with the linker. The linker that comes with plain old binutils that gets pulled in by crosstool-ng does not search...
63,024,251
63,024,818
Multiple instantiation points with different instantiations?
I have some code with multiple instantiation points, in which Stroustrup C++ states "A program is illegal if it is possible to construct two different meanings by choosing different points of instantiation. That is, if the bindings of a dependent or a nondependent name can differ, the program is illegal. ". Does anyone...
Does anyone know why the compiler is not catching this? From [temp.point]/8: A specialization for a function template, a member function template, or of a member function or static data member of a class template may have multiple points of instantiations within a translation unit, and in addition to the points of i...
63,024,389
63,024,431
how to create a 2D vector: first row of string and second row is integer
how can i make a vector where the first row is of string and second row is of integers ? where each number represents number of occurence of each word Example: this adam dad hello 2 4 1 6
There are some possibilities. If you care for the order of the elements: vector<pair<string, int>> occurrences; int main(){ occurrences.push_back( make_pair("this", 2) ); occurrences.push_back( make_pair("adam", 4) ); //access: occurrences[0].first or occurrences[0].second } Otherwise: map<string, int> o...
63,024,470
63,024,530
getting struct pointer to give to substruct
i am trying to get GameAPI pointer so that my substruct test can use it. Code: struct GameAPI { static GameAPI* Ptr; GameAPI() { Ptr = this; } struct { void func() { printf("%p",&Ptr); } }test; }; ERROR: unresolved external symbol "public: stat...
You've only declared Ptr but you forgot to define it outside the GameAPI definition. Add: GameAPI* GameAPI::Ptr = nullptr; // or another suitable value
63,024,589
63,025,168
how to use getprocadderss to a struct or STL
I am pretty new to DLL:s and I've tried using a DLL with static link and dynamic link but this is my first time using runtime link (which uses LoadLibrary in order to access) and now I am trying to use my global std::vector in my client.exe is it possible to do GetProcAddress() to get this STL? or is it possible to Get...
If the stl::vector is global to the application you can simply pass a reference to a function within the DLL. If the stl::vector is global with respect to the DLL then you can have a function in the DLL return a reference to it. However, as stated already, if there is a chance the DLL and the application could be comp...
63,024,739
63,024,886
how do i include a if else question in my code on visual c++
I'm new to coding, and for my first project I wanted to do something useful and wrote a code that calculates your grade at the end of the year (only works in Germany). My problem is that some students have 15 classes and some 16, and I want to include an if option, but I don't know how. Could someone help me? Here is t...
Prompt the user if there is a 16th class. If there is, read that score. Put all of the scores into an int[16] array and pass it to the average() function, along with a parameter indicating how many int values are in the array. Loop through the array that many times to calculate the average, and when printing the values...
63,024,760
63,025,579
Errors when using OptimLib in Rcpp
I encountered an error when using OptimLib library in Rcpp.First I copied sphere_fn function online in order to use it later in optim function. However, this shere_fn didn't work. Error: can not initialize a member subobject of type `'arma::Col<double>*'with an lvalue of type 'SEXP'(aka'SEXPREC *').` It seems the pro...
Well sometime you may need to put in the time to learn to walk before you can compete in races. In other words, you cannot just put semi-arbitrary signatures in there and expect Rcpp Attributes to translate it it all for you. What is void * supposed to map to? Ditto for arma::vec*. Just pass an arma::vec, it will use ...
63,025,116
63,025,461
Program terminates before to start the second input stream
After inserting names, and then terminating the input stream pressing CTRL+D (Unix) or CTRL+Z (Win), the program would to prompt another time, to insert ages, but it isn't so. Please, can you tell me why? Thanks. here, I use the reference for a printing function not present in this code. compile online https://onlinegd...
The behavior of Ctrl+D depends on your terminal. I tried it in VSCode and there it seems to close the input stream. I wasn't able to reopen it. In my Linux terminal (Tilix) Ctrl-D sends EOF. After std::cin.clear() the goodbit is set and I can read user input again. https://en.cppreference.com/w/cpp/io/ios_base/iostate ...
63,025,254
63,027,142
Syntax error: missing ';' before '*' with Item class
I'm encountering these errors: 1>...\inventory.h(9): error C2143: syntax error: missing ';' before '*' 1>...\inventory.h(9): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 1>...\inventory.h(9): error C2238: unexpected token(s) preceding ';' 1>...\inventory.h(15): error C4430: ...
If you're coming from a higher-level language like C#, #include doesn't work the same as a using. #include essentially copies and pastes the entire file inline. You can then see the problem of having Item.h include Includes.h which then includes Inventory.h, but then when Inventory.h tries to include Includes.h, it's ...
63,025,270
63,041,738
simplfied observer pattern with std::shared_ptr/weak_ptr
Here is a simplified observer pattern: one creator creates a profile when it starts and "destroy" it when it is done. zero, one or more observers try to "look at" the profile at any time. To implement it, the trick is that observers shall refcnt profile, so the last observer (or creator) can safely destroy it. I can ...
You have undefined bahavior when one thread reads from the shared pointer g_profile (observer) while the other thread writes to it (when creator calls std::shared_ptr::reset) If you want to use the shared_ptr from two threads you'll have to use a lock or atomic_shared_ptr. Also volatile does not guarantee any synchroni...
63,025,390
63,025,504
Win32 DatePicker setting max date not working
I have a win32 GUI application with a date picker control. I can set the minimum date, but the maximum date never takes. Here is the code I am using to set the max, and then check the max: void setMaximum(HWND hwnd, SYSTEMTIME st) { LRESULT rc = SendMessageW(hwnd, DTM_SETRANGE, GDTR_MAX, (LPARAM)&st); SYSTEMTI...
The DTM_SETRANGE and DTM_GETRANGE messages both expect the LPARAM to be a pointer to a SYSTEMTIME[2] array, but you are giving them both a pointer to a single SYSTEMTIME instead. That is why DTM_SETRANGE works when using only GDTR_MIN, since the minimum SYSTEMTIME is the 1st element in the array. The wParam of DTM_SET...
63,025,578
63,025,659
Is there anything redundant that I have done or am I, a C++ newbie, missing out anything here?
CODE: #include <iostream> #include <cmath> using namespace std; //To import packages we use #include. int integers() { //Math operations passed onto cout will automatically calculate itself. inum ++; dnum --; cout << inum << endl; //For example, pow() cout << pow(2, 6); //++ function makes v...
Your code missing main function, which starts the program; and You must declare you variables before use them; int main() { int inum = 0, dnum = 0; inum++; dnum--; std::cout << inum << std::endl; std::cout << std::pow( 2, 6 ); }
63,025,648
63,026,010
Why does C++ RTTI require a virtual method table?
Why does C++ RTTI require the class to have a virtual methods table? While it seems reasonable to use the table as a means for polymorphic upcasting, it doesn't seem like it is strictly required from a design point of view. For instance, the class could contain a hash or a unique identifier that conveys the information...
From a language perspective, the answer is: it doesn't. Nowhere in the C++ standard does it say how virtual functions are to be implemented. The compiler is free to make sure the correct function is called however it sees fit. So, what would be gained by replacing the vptr (not the vtable) with an id and dropping the v...
63,025,687
63,026,068
enable_if, SFINAE and template parameters?
I'm trying to understand enable_if and SFINAE. So far, my use of templates has been explicitly passed template arguments to the template parameters or deduction of template parameters during instantiation. I'm confused in the code below how the member of enable_if<>::type (typedef int type) can be a template paramete...
There are two kinds of template parameters: type template parameters non-type template parameters The name of the template parameter is optional A template parameter can have a default value Type template parameter named, non-defaulted template <class T> struct X {}; Usage: X<int> x{}; named, defaulted template <cl...
63,025,836
63,045,671
How to chain and serialize functions by overloading the | operator
I'm trying to figure out how to generically overload the operator|() for a given base class object to serialize or chain function calls that are similar to how pipes or operator<<() works... I'd like to chain them through the pipe operator... This way I can have a series of standalone functions, and call them on a sing...
First I assume you have some basics that look like this #include <iostream> struct vec2 { double x; double y; }; std::ostream& operator<<(std::ostream& stream, vec2 v2) {return stream<<v2.x<<','<<v2.y;} //real methods vec2 translate(vec2 in, double a) {return vec2{in.x+a, in.y+a};} //dummy placeholder implemen...
63,026,018
63,026,209
return value from reference of address in C++
Sorry if my wording is incorrect but here is the code: typedef struct { unsigned char bSaveRestore; unsigned short wPresetId; } uvcx_ucam_preset_t; ... uvcx_ucam_preset_t data; data.wPresetId = 0; data.bSaveRestore = 0; setProperty(&data); ... setProperty(void *data ...) { //How to access wPresetId and bSav...
data is an object of type uvcx_ucam_preset_t, &data returns the address of data, i.e. a pointer with type uvcx_ucam_preset_t*. setProperty is taking void* as parameter, when passing &data the pointer converts to void* implicitly. In setProperty, if you want to access data member wPresetId or bSaveRestore you need to c...
63,026,157
63,026,210
How to match complex strings with regular expressions
I am a newbie in C++, I am using the regular expression function, but I have not been able to get the results I want c++ code: #include <regex> std::string str = "[game.exe+009E820C]+338"; std::smatch result; std::regex pattern("\\[([^\\[\\]]+)\\]"); std::regex_match(str, result, pattern); // no result std::cout << ...
If you want to access the capture groups, it appears that the regex_match API requires a pattern which matches the entire input. Also, to avoid getting bogged down by a negative character class which includes a closing square bracket, I recommend using the Perl lazy dot instead. Putting all this together: std::string...
63,026,319
63,026,483
enable_if compilation question void = nullptr
Does anyone know why assigning type* = 0 doesn't work, while type* = nullptr does? In both cases typedef void type. Thanks #include <type_traits> #include <iostream> template <class T, typename std::enable_if<std::is_integral<T>::value>::type* = 0> void do_stuff(T& t) { std::cout << "do_stuff integral\n"; ...
Technically speaking, this is because a non-type template argument must be a "converted constant expression" of the parameter type. This means that the argument itself must be a constant expression, and its conversion to the required parameter type must use only the conversions specified in [expr.const]/4. According to...
63,026,448
63,152,403
Ncurses mvwprintw doesnt print
I have a simple program that has a main window and a small window on the bottom like (without the lines, thats just so you can see the two windows: +------------------+ | | | | | | +------------------+ | | +------------------+ I want the bottom area ...
Tidied it up for you a bit. Press 'q' to quit. You get the idea. #include <termios.h> #include <bits/stdc++.h> #include <ncurses.h> int main() { int...
63,026,600
63,030,823
runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
When I execute below code when value of parameter n is 2147483647, I get error(runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int') from if phase. But "INT_MAX" is printed. Can you explain why I am getting this error? class Solution { public: int myFunct(int n) { if (n...
From the snippet provided: #include <iostream> class Solution { public: int myFunct(int n) { if (n == INT_MAX) std::cout << "INT_MAX" << std::endl; return 0; } }; int main(void) { Solution s; // Here we are passing +1 than INT_MAX value // (i.e. overflowing 4-bytes int...
63,026,616
63,026,917
C++ second cin got eaten when the Input type isn't correct
I would like to ask a strange question. double Test1, Test2; cout << "Please Input the First Number: "; cin >> Test1; cout << "\nPlease Input the Second Number: "; cin >> Test2; cout << "\nHere is the Answer: " << endl; cout << Test1 << Test2 << endl; If my Input of Test1 is a char (for example 'A'), the second inp...
The input with >> is terminated as soon as an invalid character is detected. That invalid character is not removed from the stream, so it's still there when you do the second >>.
63,026,626
63,026,646
C++: If I want to enter a series of number into an array without being limited by the amount of number I need to enter. How should I do this?
int A[10] for (int i=0; i< 10; i++){ cin >> A[i] ; } I want the users to be able to enter a list of numbers, but right now I have to type in 10 numbers to break the loop. How can I make it so I can stop whenever I want? I'm a beginner and I am thankful for your time and help!
Than you should use a vector, your array will resize while you push back. std::vector<int> name; You can find more about it here Otherwise you will have to make a function to resize...Vector basically does the same thing for you. Your code would be than: int input; std::vector<int> A; for (int ...
63,027,040
63,028,726
How to make my code statements appear in one line with clang-format?
I created a .clang-format but I can not find the line that is causing this issue. I want the individual statements to be on individual lines even if they are long, and not break them into multilines. I tried to increase the ColumnLimit to 150 still unable to get the desired formatting. I am trying my code to look like ...
When using clang-format you should step away from the idea that your formatting is better than it's. Once you configured a style correctly, live with it and log bugs if there are changes that ain't correct. In this case, ColumnLimit is the right thing to change. Depending on your screen, you might want to have a differ...
63,027,107
63,027,674
Converting vector<char> that contains cbor data to const char *
I have a uint8_t vector which contains cbor bytes and I have to cast or copy the bytes to a const char * to use in a POSIX message queue. I've tried the following approaches vector<uint8_t> cbor_data{/*has some data*/}; const char *data = (const char *)(cbor_data.data()); and vector<uint8_t> cbor_data{/*has some data*...
Question: a better way to pass a vector of char/uint8_t to a posix message queue? The actual question is in your comment, I can pass the actual size but on the receiving end the buffer has size that is way greater than the actual message length. Since it's a raw pointer, and mq_receive has to be given a larger size...
63,027,119
63,027,899
Why Eigen MatrixXd::transpose() does permutation that is not transposition at all?
I am trying to transpose this 4x5 matrix using Eigen: |m00, m01, m02, m03| |0.00000, 0.33333, 0.66667, 1.00000| |m10, m11, m12, m13| |0.25000, 0.41667, 0.71200, 1.03078| |m20, m21, m22, m23| = |0.50000, 0.60093, 0.83333, 1.11803| |m30, m31, m32, m33| |0.75000, 0.82074, 1.00347, 1.25000| |m40, m41, m42, m43| |1....
The code below works well. #include <iostream> #include <Eigen/Core> void main() { Eigen::MatrixXd m_weight(5, 4); m_weight(0, 0) = 0; m_weight(0, 1) = 0.33333; m_weight(0, 2) = 0.66667; m_weight(0, 3) = 1.00000; m_weight(1, 0) = 0.25000; m_weight(1, 1) = 0.41667; m_weight(1, 2) = 0....
63,027,461
63,027,526
How to convert std::string::const_iterator type to int type in c++
I am a newbie in C++ I want to use c++ to implement the string split function, so I wrote the following code: #include <vector> #include <regex> #include <sstream> #include <string> std::string str = "1:2-3:4"; std::smatch result; std::regex pattern("[:-]"); std::string::const_iterator iterStart = str...
XY problem. You don't want an int type, you want that substring, and you can get it through the iterators you have just fine. Like this: splitList.emplace_back( iterStart, result[0].first );
63,027,589
63,877,402
Can't make instance of tesseract::TessBaseAPI in c++
I installed tesseract and opencv using vcpkg on macos, everyhitng went fine. Now i'm trying to make a simple tesseract project with cmake but: tesseract::TessBaseAPI text_recognizer; throws: libc++abi.dylib: terminating with uncaught exception of type std::runtime_error: collate_byname::collate_byname failed to const...
I wasn't able to find the answer so i started trying random things, and adding set(CMAKE_BUILD_TYPE "RELEASE") Solved the issue for some reason.
63,028,741
63,054,327
Make a transparent hole in a QT application
I've got a problem where I've got 2 Qt applications on top of eachother. The top Qt application needs a transparant hole in it to show the Qt application behind it. Is there any way to do this? or is there an example somewhere in the Qt library which could help me? To clarify, if I'd run the Qt application on a Windows...
Eventually after a lot of fooling around with Qt I've been able to do what I was trying to do. My solution is based on the clock example from Qt. I've changed the resizeEvent to the following: void Widget::resizeEvent(QResizeEvent * /* event */) { QRegion outsideMask(QRect(0, 0, 200, 200)); QRegion insideMask(Q...
63,028,853
63,032,351
c++ program not running properly from outside code::blocks
I am using Code::Blocks and MinGW to build c++ programs. When I run the compiled program in Code::Blocks, it works perfectly. But when I tried to run the same exe from outside Code::Blocks, the program is not running and giving two errors: The program can't run because libgcc_s_dw2-1.dll is missing from your computer....
Possible solutions: build a completely static version (--staticcompiler flag) build using -static-libstdc++ -static-libgcc as linker flags copy the files libgcc_s_dw2-1.dll and libstdc++-6.dll (and any other dependancies if any) to the same folder as your .exe file
63,029,096
63,031,147
Thread-safe singleton using atomic
Just want to know whether atomic_flag = 1; keeps the myclass_st assignment thread-safe or not. (I am sorry that my example has so many problems, so I have changed it.) myClass* myclass_st = nullptr; std::atomic<int> atomic_flag; std::mutex mtx; //err myClass* get_instance() { //std::unique_lock<std::mutex> lk(...
Just want to know whether atomic_flag = 1; keeps the myclass_st assignment thread-safe or not. No. Maybe I should modify the code like this ? myClass* myclass_st = nullptr; std::atomic<int> atomic_flag; myClass* get_instance() { if (atomic_flag.load() == 0) { myclass_st = new myClass(); atomic_f...
63,029,500
63,033,182
Simply including <opencv2/opencv.hpp> results in linking error
Simply including the OpenCV header results in linking error. Why is that? // test.cpp #include <opencv2/opencv.hpp> int foo(); int bar(); int main() { } If I compile the file with g++ test.cpp, the following linking error occurs: /tmp/ccugmQl4.o: In function `cv::String::~String()': test.cpp:(.text._ZN2cv6StringD2Ev...
If you tweak your example a little bit // test.cpp int foo(); int bar() { foo(); } int main() { } You would notice that it'd stop working because linker won't be able to understand what is foo(); The same thing happens when you include opencv header - there are references to functions which are declared but sinc...
63,029,722
63,029,868
comparison function causing problem in vector of vector sorting[leetcode]
I needed to sort a vector of vectors by first element of each element vector. Its for the merge intervals problem in Leetcode. I wrote the following code for the problem: class Solution { public: static bool comparison(const vector<int>& v1, const vector<int>& v2){ if(v1[0]==v2[0]) return v1[1]<...
The comparator needs to satisfy the named requirement Compare which requires a strict weak ordering. One condition you must satisfy is that: For all a, comp(a,a) == false But for example comparison({0, 0}, {0, 0}); yields true. Since your comparator does not satisfy all of the requirements you get undefined behaviou...
63,029,990
63,030,456
Pass non-static member function to member function of another class
I have two classes A and B. And I want to call the member function of class B from class A while passing a member function of A to said function of B. The setting: class B { public: int dopristep(std::function<int(int,int)> f, double t, double h); }; class A { public: void run(); int g(in...
As explained here, pass a lambda that calls the function on the enclosing A instance: mB->dopristep([&] (int a, int b) { return g(a, b); }, T, h); Additionally, you could modify dopristep to accept a functional which will avoid some overhead: template <typename F> int dopristep(F&& f, double t, double h);
63,030,180
63,032,442
Setting CPU Affinity and blocking CPU usage for background task
I am writing one application with openmp on a Arm based system. In which I am having 4 High Performance core (Arm Cortex A57) and 4 Low Performance core (Arm Cortex A53). Environment: Poky (Yocto Project Reference Distro) 2.4.3 #pragma omp parallel sections num_threads(3) { #pragma omp section { ...
Setting affinity for a process means that, only that process can run on a particular CPU. However, that CPU is still in use by kernel scheduler and kernel can schedule other processes to it. One option would be to use isolcpus kernel command line option like isolcpus=0-3. Now, 0-3 cpus will not be used by kernel and se...
63,030,378
63,035,544
CComBSTR::Detach and m_str differ
I converteted an old VC++6 lib to VC++17, now I have some issues with BSTR. See the method: void GetLastErrorStringInternal(BSTR *LastErrorString) { CComBSTR cbsErrMsg; /*cbsErrMsg gets determined here*/ std::wcout << "cbsErrMsg = "<< cbsErrMsg.m_str << std::endl; *LastErrorString = ...
*LastErrorString as in ... std::wcout << "LastErrorString = "<< *LastErrorString << std::endl; // dereference LastErrorString
63,030,440
63,030,700
Failed when using drawText() in main() function
This is my code: int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QRect r(0,8,32,16); QImage img(32,32,QImage::Format_RGBA8888); img.fill(Qt::Red); QPainter p; p.begin(&img); QPen pen; pen.setColor(QColor(0,0,0)); p.setPen(pen); ...
Font support must be part of GUI subsystem, both Qt framework-wise and platform-wise, assuming it's a XWindows application, Wayland or MS Windows. Try replace QCoreApplication with QApplication and add GUI to configuration. Sadly, in case of Linux platform, you would require an active GUI server available.
63,030,537
63,030,602
linux read() function from unistd.h doesn't work for me :(
I tried everything i could think of but for some reason it doesn't store the data from the file to "data", but the file has the written data. #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <stdlib.h> #include <iostream> using namespace std; int main() { char data[69]=" "; ...
From man write: For a seekable file (i.e., one to which lseek(2) may be applied, for example, a regular file) writing takes place at the current file offset, and the file offset is incremented by the number of bytes actually written. From man read: On files that support seeking, the read operation commences at the c...
63,030,968
63,031,771
C++ New Order for Structure Array
I have a structure array, where each structure has an id (int) and an value called aktiv (boolean). I want to pass the structure array to a function which sorts the structure. The structures in the array with an aktiv value of 0 (false) should be at the end of my array. I thought i create an second array where i save m...
Given what you've posted, if the goal is to move all aktiv items that are 0 to the back of the array, then std::partition can be used. #include <algorithm> void naende(Item itf[], int dim) { std::partition(itf, itf + dim, [&](const Item& it) { return it.aktiv == 1; }); } The code above places all aktiv entries e...
63,031,361
63,031,550
How to initialize an empty unordered map in C++?
I have to run a loop (the looping on t) on an unordered map in C++ and each time the loop is run, the unordered map gets updated. But what I want to do is, start with an empty map each time the loop is run. How do I initialise an empty unordered map? while (t--){ unordered_map<int, int> freq; //perform ...
Unordered maps are a bit tricky in the sense that they use two things: A chain of {key,value} pairs (STL uses a std::forward_list). An array of positions to the chain elements (hash table). When you insert elements to the map, the array gets filled (load factor increases) and hash collisions start to become frequent....
63,031,392
63,040,417
Does std::thread::join guarantee writes visibility
Std::thread::join is said to 'synchronize-with' the joined thread, however synchronization doesnt tell anything about visibility of side effects, it merely governs the order of the visiblity, ie. in following example: int g_i = 0; int main() { auto fn = [&] {g_i = 1;}; std::thread t1(fn); t1.join(); return g_i;...
[thread.thread.member]: void join(); Effects: Blocks until the thread represented by *this has completed. Synchronization: The completion of the thread represented by *this synchronizes with the corresponding successful join() return. Since the completion of the thread execution synchronizes with the return from thr...
63,031,426
63,031,534
auto deduction fails with message "inconsistent deduction for auto return type"
I have written the following test : #include <cassert> #include <iostream> #include <string> #include <cmath> #include <functional> // Works with std::function ! //std::function<double(double)> set_unary_operation(const std::string& unary) auto set_unary_operation(const std::string& unary) { if(unary == "EXP") ...
Every lambda expression yields unique closure type, The lambda expression is a prvalue expression of unique unnamed non-union non-aggregate class type, known as closure type, which is declared (for the purposes of ADL) in the smallest block scope, class scope, or namespace scope that contains the lambda expression. w...
63,031,673
63,031,782
Trying to get an int by wraping it into void* and again wrap it back into Integer but i am not successfull
#include <iostream> class Singleton { static Singleton instance; int num; Singleton() = default; Singleton(Singleton &) = delete; Singleton(Singleton &&) = delete; Singleton &operator=(Singleton &) = delete; public: static Singleton &GetInstance() { return instance; } void...
If you need to return an integer value as a generic pointer (void*) then you should really do the conversion in two steps: First to an integer type that is large enough to hold both an integer and a pointer, then in the second step to the generic pointer: void* get() { return reinterpret_cast<void*>(static_cast<std...
63,032,743
63,032,825
Why can't I write container.iterator?
Why can't I write code neither like this: int main() { std::map<std::string, int> m; m.iterator it = m.find("five"); //~~~^~~~~ // nor like this: m::iterator it = m.find("eight"); }
You can't write m.iterator, because iterator is not a data member or member function, you can't use member access operator (i.e. operator.) for it. (iterator is a nested type name.) You can't write m::iterator, because m is not a class name or namespace name, you can't use it with scope operator (i.e. operator::). You ...
63,033,270
63,033,444
Get time with milliseconds in C++17?
How can I get the current time in milliseconds in C++17 with boost or the standard library? I tried using std::chrono: int main() { const auto currentDateTime = std::chrono::system_clock::now(); const auto currentDateTimeTimeT = std::chrono::system_clock::to_time_t(currentDateTime); const auto currentDateTi...
So just print the milliseconds from the timepoint... const auto ms = std::chrono::time_point_cast<std::chrono::milliseconds>(currentDateTime).time_since_epoch().count() % 1000; std::clog << std::put_time(&currentDateTimeLocalTime, "%Y%m%d_%H%M%S") << "." << std::setfill('0') << std::setw(3) << ms << std::endl; H...
63,033,346
63,033,390
External code requires char* but I'm using const char*
I'm mapping a file to memory and returning a const char* to the first byte: Mapper(const char* path, const char*& firstByte, size_t& fileSize); but external code (I cannot change it) I'm using takes a char* (although it doesn't change the buffer): void externalCode(char* bytes); so I'm getting a compiler error (passi...
If externalCode for real, pinky-promise, doesn't modify the buffer, and if you cannot modify it, then I would write a wrapper using const_cast where the argument is fixed: void externalCodeFixed(const char* bytes) { externalCode(const_cast<char*>(bytes)); // NOTE bytes are not modified } If there is any doubt whe...
63,033,355
63,034,437
Get the hex values of a dd-image with CPP
I want to read the first 4096 Bytes as hex of a image file (dd from a luks encrypted device). So i tested at first with an unsigned long which has a value range from 0 to 18446744073709551615. But with this code int main() { unsigned long c; FILE *fp = fopen("C:\\image.dd", "r"); if (fp == NULL) { ...
You have four errors. Firstly, you are printing data without checking if reading is successful. Checking should be between c=fgetc(fp); and printf("%02x ",c); Secondly, you are passing wrong type to printf() and invoking undefined behavior. The format %02X requires unsigned int. (int in proper range is also OK, accordi...
63,033,566
63,050,672
Reason to add empty source file to a STATIC library?
I've seen this quite a lot in C++, that developers add an empty source file to the library in CMake. One example is here, with the empty source file found here. The CMake file has this line: # build the library add_library(${PROJECT_NAME} STATIC src/dependency-tracker.cc) This is only the case if there are no other so...
The project specifies CMake 2.8.11 as a minimal requirement: cmake_minimum_required(VERSION 2.8.11) This version lacks for INTERFACE library type, which nowadays is a standard representation of a header-only library. (Support for INTERFACE libraries firstly appeared in CMake 3.0). Without INTERFACE library available, ...
63,033,795
63,033,977
Using of const for std::pair in c++
For implementing binary search tree I am wandering why we put Const before K in std::pair ? template<class K,class V> class BST { public: class Node { public: pair<const K, V> data; // pair < data_type1, data_type2 > Pair_name; unique_ptr<Node> left; // Create a unique_ptr object through raw p...
Because, logically, the node keys in your data structure must be immutable: immune from change. That's to maintain the proper structural layout, which depends on the relative ordering (by key!) of the nodes. If a node needs to be renamed, higher-level algorithms need to be deployed in order to do that. Sure, there's no...
63,034,214
63,034,502
Something like #if #endif for AndroidManifest.xml
I develop 3D engine (c++ in visual studio) for windows/android/android oculus. On Android, I use AndroidManifest.xml, where I need <meta-data android:name="com.samsung.android.vr.application.mode" android:value="vr_only"> VR_ONLY for oculus, and <meta-data android:name="com.samsung.android.vr.application.mode" android...
I think if this works at all it's through gradle during the build process. check this links out: here or here
63,034,559
63,034,614
Why is the sprintf converting only half of my uint64_t data?
#include <iostream> using namespace std; int main() { uint64_t a = 0xffffffffffffffff; int c = 3; char b[16]; sprintf(b, "%X", a); cout << b << endl; return 0; } This is printing and storing half of the fs, i need the rest of them, how do i do this?
You are invoking undefined behavior by passing data having wrong type. The type format to print uint64_t in uppercase hex is PRIX64, defined in the header <cinttypes>. Also don't forget to allocate for terminating null-character. #include <iostream> #include <cstdio> // sprintf() #include <cinttypes> // PRIX64 (and ...
63,034,666
63,045,299
Prefix vs Postfix and table made of array?
Can you please explain this code, keeping in mind that the person who wrote it was using it to teach me the difference between prefix and postfix incrementations int main() { const int ROWS = 3;`enter code here` const int COLUMNS = 3;`enter code here` char board[ROWS][COLUMNS] = {{'O', 'X', 'O'}, {' ', 'X',...
The code doesn't seem to show any difference between postfix and prefix incrementation, anyway this is how it works: POSTFIXED int x = 10; cout<< (x++); //output: 10 //now x is 11 PREFIXED int x = 10; cout<< (++x); //output: 11 (and x is already 11) Basically, the postfixed increment will only show its effects after ...
63,034,920
63,043,556
Is it possible to default-initialize a temporary variable?
Consider this code: struct S { int m; }; S trick() { S s; return s; } void bar(S s) { /* observe s.m */ } void foo() { S s; // s.m is indeterminate S* p = new S; // p->m is indeterminate bar(S()); // bar() will observe S::m to be 0 bar(trick()); // bar() will observe S::m to be inde...
You can default initialize a sub-object of a temporary variable. template<typename T> class default_init_tmp final { T t; public: default_init_tmp () /*Intentionally left blank*/ {} default_init_tmp (default_init_tmp const&) = delete; void operator=(default_init_tmp const&) = delete; T* operator&() { return...
63,034,922
63,035,022
SIGABRT on std::ifstream close
1I am currently working on a project of creating my own game in OpenGL. My problem is right now, that if I read a file, that my function reading that file results in a SIGABRT, because of something inside the std::ifstream deconstructor (more specifically in "std::basic_ifstream<char, std::char_traits<char> >::~basic_i...
strcpy: Copies the character string pointed to by src, including the null terminator, to the character array whose first element is pointed to by dest. The behavior is undefined if the dest array is not large enough. The behavior is undefined if the strings overlap. c_str: Returns a pointer to a null-terminated char...
63,035,288
63,037,677
Why the thread may be blocked for longer than the specified duration when we use wait_for?
In 《c++ concurrency in action》page 387. template<typename Lockable, typename Rep, typename Period> std::cv_status wait_for( Lockable& lock, std::chrono::duration<Rep, Period> const& relative_time); NOTE The spurious wakeups mean that a thread calling wait_for() may wake even though no thread has call...
From cppreference:std::condition_variable::wait_for This function may block for longer than timeout_duration due to scheduling or resource contention delays. When the duration expires, the thread is asleep and needs to be re-scheduled. The kernel scheduler often runs on a timer or when some other event prompts it, an...
63,035,577
63,040,816
If I create an application using AVX2 will it run on other machines?
I am building an application that has an algorithm that takes a lot of time to complete at runtime, so I was thinking of using AVX2 to speed things up. But I don't know if the application would run in the same fast manner in a user's machine, or if it would run in their machine at all.
It will not run on CPU that has no AVX2 support. Therefore before you start the algorithm, you must query the CPU for AVX2 support. Your application must be able to proceed if the answer is no by running AVX or even just SSE2.
63,035,846
63,036,270
a 'for each' statement cannot operate on an expression of type "std::vector<Vertex *, std::allocator<Vertex *>>"
I am trying to make graph implementation in C++ using adjacency list representation. I am little new to "vectors" in c++. I am getting this error class Vertex { private: public: int node_id; string value; vector< std::pair<Vertex* , int> > adj_list; Vertex(int node_id, string value = "" ) ...
You can use something like this ranged-for loop (untested code) for (auto& var : vertex_list) { if (var->node_id==node_id) { throw runtime_error("This node id exist already! put another id"); } }
63,035,951
63,042,081
How to get format of video stream in ffmpeg (c++)
I have a function that reads frames from a stream. I want to find out what the format of the stream is (I'm testing with H264): StreamingResult MediaWriter::Open(const AVFormatContext *const inputFormatContext, const fs::path &destination) { // Save input stream data AVStream *vide...
Some good FFMPEG documentation would be appreciated, because I am getting lost in Doxygen generated documentation. Doxygen is th best ffmpeg documentation there is. Its just ffmpeg is a very large peroject and takes time to learn. What you are looking for is videoStream->codecpar->codec_id
63,035,954
63,036,198
How to return nullptr equivalent from a C++ function whose return type is pair?
pair<int, int> findEmpty(int bo[9][9], int n){ for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(bo[i][j]==0){ return (make_pair(i, j)); } } } //return nullptr; } If nullptr can't be returned, what are the alternatives?
Use an optional<T> type to represent potentially non-existent state. If you're using C++17 this can be done with std::optional<T>, if you use Boost then boost::optional<T>, etc. You can even implement your own version of optional. The point is to use a semantic type that indicates that there may, or may not, be a value...
63,036,139
63,036,922
Compute the similarity rate between two Images with opencv/c++
I'm using OpenCV/C++ to compute the similarity rate between two images. I want to tell the user how much % image A looks like image B. Let's take a look at the code below : double getSimilarityRate(const cv::Mat A, const cv::Mat B){ double cpt = 0.0; cv::Mat imgGray1, imgGray2; cv::cvtColor(A, imgGray1, ...
I suspect imgGray1.at<int>(rows, cols) should be imgGray1.at<uchar>(rows, cols) instead. Currently .at() function call has int as a template argument, but typically cv::Mat consist of uchar elements. Are you pretty sure that your image has int elements? If it does consist of uchar elements, then using int template argu...