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
62,576,373
62,576,768
operator over loading: "operator+"must take either zero or one argument
I have a matrix class called IntMatrix namespace mtm { class IntMatrix { private: int** data; int col; int row; public: IntMatrix(int row,int col,int num=0); IntMatrix(const IntMatrix& mat); //some functions IntMatrix ::operator+(int num) co...
Declaring a function with friend does not make it part of the class. The int+IntMatrix operator is not IntMatrix::operator+ - it's just operator+. // wrong - delete this part // vvvvvvvvvvv IntMatrix IntMatrix::operator+(const int &num, const IntMatrix& matrix) { return matrix+num; }
62,577,336
62,577,394
Recursive template packs
I'm having trouble with recursive template pack unpacking. What I currently have is: template<T> constexpr void register_types() { do_something<T>(); return; } template <class T, T2, class... Args> constexpr void register_types() { do_something<T>(); register_types<T2, Args...>(); } int main(int ar...
Is it possible to have an empty parameter pack as the base case? You can't declare a template function without template parameters. But you can declare a template function that accept an empty list of template parameters (using default values/types or variadics). For your case suggestion: try with template <int = 0> ...
62,577,647
62,578,185
How to develop to-point moving algorithm using Gps and compass
I am trying to develop an alghoritm for controlling the rudder of the boat... I got lost in geo algoritms... Function Does not work corectly. direction WhereToMove(double CurrentLatitude, double CurrentLongitude, double TargetLatitude, double TargetLongitude, double azimuth) { double azimuthHysteresis = 5; //st...
A few points: You could use the constant M_PI for pi I would imagine you want your angles to be measured clockwise from north. atan2 gives an angle counter clockwise from the x axis. This is simple to fix, use atan2( dLon, dLat) instead of atan2( dLat, dLon) The distance represented by a degree of longitude is, rou...
62,577,876
62,578,129
C++ string concatenation in compile time
I want to write logger and I need data about source file and line. Does this line of code work in compile time or not: constexpr std::string_view source = (std::string(__FILE__) + ":" + std::to_string(__LINE__)); If it doesn't work in compile time, how will I do it? Maybe is it impossible?
This would work without allocating, and also compile time #include <iostream> #define STR_(X) #X #define STR(X) STR_(X) int main() { //constexpr std::string_view(const char*) doesn't work in some versions of gcc, but is a better alternative if the compiler supports it constexpr const char* str = __FILE__ ":"...
62,577,956
62,578,818
What is the difference between `std::default_initializable` and `std::is_default_constructible`?
C++20 adds a concept called std::default_initializable. The difference in naming compared to std::is_default_constructible seems to be way too obvious to be accidental. Their specifications are worded differently as well (at least on cppreference), however I don't understand what the effective differences are. Here's a...
This is basically LWG 3149: DefaultConstructible<T> is equivalent to Constructible<T> (18.4.11 [concept.constructible]), which is equivalent to is_constructible_v<T> (20.15.4.3 [meta.unary.prop]). Per 20.15.4.3 [meta.unary.prop] paragraph 8: The predicate condition for a template specialization is_­constructible<T, A...
62,578,054
62,578,930
Why do gcc and clang generate so much code for std::find?
I entered the following code into godbolt.org, and compiled it with gcc 10.1 and clang 10: #include <algorithm> #include <vector> typedef std::vector<int> V; template<class InputIt, class T> InputIt myfind(InputIt first, InputIt last, const T& value) { for (; first != last; ++first) { if (*first == value)...
The reason is simple: the implementation of std::find for random access iterators is not a simple for loop, but something more complicated: template<typename _RandomAccessIterator, typename _Predicate> _GLIBCXX20_CONSTEXPR _RandomAccessIterator __find_if(_RandomAccessIterator __first, _RandomAccessIterator ...
62,578,093
62,578,619
Using clang or g++/gcc to print preprocessed code without including files from system paths
currently I'd like to debug my includes. To do this I want to get the preprocessed code, but without any system header files - just my own code. I tried it with flag "-E" and "-nostdinc". But then I get errors that for example <string> is missing. How to disable such preprocessing errors?
(It's not really an answer - just a "hack") To solve this I created a text file with all system headers by: rem my GCC STL-PATH cd Z:\usr\include\c++\10 dir /b > F:\DummySTL\files.txt Then I executed the following line of code: for /f "delims=" %F in (files.txt) do copy nul "%F" This creates an empty text file for e...
62,578,262
62,602,064
How do I iterate through multiple .txt files in C++ that all follow a similar format?
I have multiple text files that go by the name of "inX.txt", where X represents an integer. I want to go through each of these files (so, in1.txt, in2.txt, in3.txt, etc.), run my code on them, and produce the output files in the same format, so "outX.txt". My code to work on the files works right, as I get the right ou...
I ended up figuring it out (thanks /u/drescherjm). What I did was I just used the to_string() function to convert my loop variable from an int to a string so I can use it in another variable that contains my input and output files. Within my main() function: int main() { int fileNo = 1; while (fileNo < 6) { [.....
62,578,586
62,578,769
where should friend functions be written?
I have two friend functions in a class in a header file both of them are declared in the class but the problem is when I write their body in a .cpp file I get this error undefined reference to... and when I write the body in the .h file I get this error multiple definition of.. so I don't understand where should I wr...
where should friend functions be written? Same as member functions. Either inline in the header, or non-inline in a single translation unit. If inline, it can be outside or inside the class definition. If outside, then it must be declared inline explicitly. I get this error undefined reference to... See this: Wha...
62,578,822
62,594,464
C++ - How do I manage other user in Credential Provider V1 (Vista-Win7)
I develop a code to credential provider V2 for windows 10. I manage local users and active directory users also other user tile in windows 10 by V2 of credential provider. Now I develop an other code for use in windows 7. I use from V1 credential provider. I customize It for show local user. By follow code in _Enumer...
You must implement and enumerate your own Other User tile. This tile must accept and provide input field of type CPFT_EDIT_TEXT for User Name (UPN), password and any other credential you can need.
62,579,386
62,579,964
Casting a universal reference to a callable to void pointer and vice versa
I need to wrap a callback mechanism in a C interface in C++ accepting callables. In the C interface there is a method to set the callback: void c_set_callback(void(*callback)(void* context), void* context); Here is my attempt to wrap this with a callable: template<typename Function> void set_callback(Function&& functi...
Although it is legal to cast a lambda with no captures to a C-style function pointer, your lambda scope is limited to the call to c_set_callback. My approach would be to call once c_set_callback at the very beginning of your program, with a static C function as argument. That function, internally, calls a static std::f...
62,579,451
62,672,152
Creating .dll MFC Dialog from C++/CLI - Loader lock
There are a lot of "similar" questions but none exactly like this. My task is to connect existing MFC C++ app with AutoCAD via dotnet api. So I've created C# for AutoCAD, C++/CLI as middleman one more C++ for implementing abstract class and then there is MFC C++. Every project is compiled as .dll. MFC C++ has this clas...
As I found out, it was caused by creating "theApp" in mfc .cpp file on stack. So the dialog showed, wasn't even the one I called DoModal on, but the one created in InitInstance method. Solution was to comment out "theApp" variable and then all worked.
62,579,452
62,579,853
Input as a parameter (C++)
How do I make a function in C++ that can take an input as a parameter? For example, here is an addition function below. #include <iostream> using namespace std; double add(double a, double b) { return a + b; } int main() { add(3.1, 5.3); return 0; } The output will be 8.4. I specified what a...
You can write a function that reads values from standard input, and use that for either of the arguments to add, like this: auto input() // reads a double from cin { double d; std::cout << "enter a number "; std::cin >> d; return d; } double add(double a, double b) { return a + b; } int main() {...
62,579,652
62,579,771
Variable initialization in Macro - Multiple initialization
I need to implement some db check using macro. Lets suppose that we have something like this: #define DB_CHECK(prop, records) bool found = false; \ for(auto i : records) \ if(i.id == prop.id) found = true; break; \ ...
It is a Compile Error, caused by second call to DB_CHECK macro. It declares "bool found" again in the same scope of visibility. You can solve the problem by enclosing in brackets {}, this will separate the visibility scopes: #define DB_CHECK(prop, records) {bool found = false; \ ...
62,579,746
62,579,761
'Initializing': Cannot convert from 'const wchar_t[35]' to 'LPWSTR'
i am currently learning C++ and want to change my desktop wallpaper. However i am getting this error above. #include <string> #include <iostream> #include <Windows.h> using namespace std; int main() { LPWSTR test = L"C:\\Users\\user\\Pictures\\minion.png"; int result = SystemParametersInfo(SPI_SETDESKWALLPAPER, 0,...
LPWSTR is an alias for wchar_t*, ie a pointer to a non-const character. A string literal is a const array of characters, in your case a const wchar_t[35]. It decays into a pointer to a const character, pointing at the 1st character in the literal. You can't assign a pointer-to-const to a pointer-to-non-const. That woul...
62,579,762
62,583,690
Synchronize array over MPI processes: incorrect use of MPI_Allgather?
I am aware similar questions have been addressed previously, see below why they don't apply to my case. I have a piece of code that looks as follows: int current_rank; MPI_Comm_rank(MPI_COMM_WORLD, &current_rank); if (current_rank==ROOT_RANK){ ... #pragma omp for for (long i = 0; i < num; i++) { auto &cho...
So long as num is the same on each rank, this is close. It depends on what catalogue->get(); gives you. I am going to assume that it is an integer array. You should simply need: MPI_Allgather(choumbie,send_count, MPI_INT, rbuf, send_count, MPI_INT, comm);
62,579,822
62,579,985
Private function of parent class causes ambiguous call to public function in child class with same name and similar parameters
I have a situation where I am using a public API and need to "override" a function in a parent class, however this function has not been declared as virtual. Although it is hacky, I have decided that I am going to change the visibility of the parent class function using the code mentioned here: a way in c++ to hide a s...
Is this a bug? I am confused as to why the compiler is even searching in the parent class's namespace The compiler doesn't have to look in the parent class. You explicity told him that you want to use Parent::doSomething;. Moreover, overload resolution happens before private/public access (cf cppreference): Member a...
62,580,051
62,580,183
How does std::array bounds checking work?
I'm a little bit confused with std::array bounds checking. Here's the code: const size_t studentResponses = 10; const size_t surveyBound = 6; std::array<unsigned int, studentResponses> students{ 1, 3, 5, 5, 5, 4, 5, 4, 2, 2 }; std::array<unsigned int, surveyBound> survey{}; //initializes it to '0' ...
How is the array, survey, keeping a count of how many times of each element in students is counted? By using this statement: ++survey[students[answer]]; Note that the students array must contain only values between 0 and 5 (inclusive). Then the value of students[answer] is used as an index into survey. The value at ...
62,580,224
62,580,418
Should functions declared with `= default` only go in the header file
When defining classes, it is now common to use = default for the destructor/copy constructor and copy assignment. Looking at my code base, these are nearly always in the header files only but some colleagues have put them in the .cpp file. What would be the best practice in this case? Is the compiler generating these f...
An explicitly-defaulted function is not necessarily not user-provided What would be the best practice in this case? I would recommend, as a rule of thumb, unless you explicitly and wantonly know what you are getting into, to always define explicitly-defaulted functions at their (first) declaration; i.e., placing = de...
62,580,358
62,593,907
CANoe - Could not open .dll in CAPL script
I'm trying to include my own .dll file and export its functions to my CAPL script. I'm quite certain I've written my .dll file correctly, here is the relevant code, some of it is copy/pasted from the documentation: #include "pch.h" #include "CDLL.h" long CAPLEXPORT far CAPLPASCAL addCAPL(long a, long b) { return ...
Warning 2102 at (-1,-1): Could not open C:\Program Files\Vector CANoe 10.0\Exec64\LAD.dll One possible reason for this type of error is that you are mixing 32 and 64 bit. Remember a 64 bit application can't directly load a 32 bit dll. Same goes with a 32 bit application and 64 bit dll. You must not mix these. Alter...
62,580,402
62,580,484
How to print all nodes in Binary Search Tree only use iostream library?
I'd like to print all nodes in tree(nodes with low levels are printed first, for nodes with the same output level, the node has a small value are printed first) For example: Input Expected output: 10 6 20 1 8 18 21 7 25. I tried to code like this void print_Nodes(Node *root) { if(root == nullptr) return; c...
You are printing root->left->value and then call print_Nodes(root->left) which again prints root->value (where root is the previous root->left). Thats why they all appear twice. Moreover you are doing a Depth First traversal while you actually want a Breadth First traversal. To traverse all nodes on one level before yo...
62,580,566
62,581,064
Adding ASCII value to integer using pointers
I was working with pointers in C++. The snippet is given below. int i=97; char c='A', &cp=c; cp+=i; printf("%d",cp);` ASCII of 'A' is 65, then cp will become 97 + 32 which is 162. But the output I'm getting is -94. What might be the problem?
cp += i is like cp = cp + i; where cp + i sums to 162 and then 162 is assigned to a char. Assigning an out-of-range value to a char leads to implementation defined behavior. In this case the value wrapped by subtracting 256 and assigned -94. Yet this code does not look like C with char &cp = c;. More like C++. Hmmm.
62,580,895
62,581,396
Why would one wrap a struct in an anonymous union? (STL msvc implementation)
The STL <memory> header (MSVC implementation) contains a class called: template <class _Ty> class _Ref_count_obj2 : public _Ref_count_base This class has a member: union { _Wrap<_Ty> _Storage; }; where _Wrap is defined as: template <class _Ty> struct _Wrap { _Ty _Value; // workaround for "T^ is not allowed i...
First, embedding the _Storage member in a union will prevent default destruction of that object (which is, more than likely, a non-trivial type); this appears to be essential, as the class involved is a reference counter. (By default, unions have a deleted destructor; see, for example: Is a Union Member's Destructor Ca...
62,581,032
62,761,760
How do I build the SOCI library without errors?
I am having difficulties building the SOCI library. Relevant software: Boost ver 1.73.0 CMake ver 3.16 MSVC compiler ver 19.26.28805.0 MySQL ver 5.7 SOCI ver 4.0.0 Relevant paths: Path to Boost is E:\cpp\Lib\boost\boost_1_73_0. Path to CMake is E:\Apps\CMake\share\cmake-3.16. Path to MySQL server is C:\Program Files...
Turns out, most of the errors I was getting was from the included unit tests. Why? I do not know. However, if I ignore the errors and move on, everything seems to work fine.
62,581,472
62,581,598
long long v/s int in file input output in c++
I tried many different unsuccessful ways, the last of which I am describing below- #include<iostream> #include<fstream> //functions here using namespace std; int main(){ int n; long long A[300001]; ifstream myfile("sort.in"); myfile>>n; for(int i=0;i<n;++i){ myfile>>A[i]; } ...
It's most likely a stack overflow problem caused by large statically defined arrays. Instead of long long A[300001]; use std::vector<long long> A(300001);
62,581,736
62,582,757
Program SGILL's when linking OpenCV
I know this question is similar to may other ones but none of them seem to solve my problem. Symptoms Trivially build and run gdb_test with gdb. Program SIGILL's: ~/projects/gdb_test/build> gdb gdb_test GNU gdb (GDB; openSUSE Tumbleweed) 8.3.1 (...) For help, type "help". Type "apropos word" to search fo...
According to your comment: I downgraded from opencv-devel-4.2.0-4.1.x86_64 to opencv3-3.4.9-2.4.x86_64 and it is not crashing anymore.. I can only conclude the package is broken. In case you really need OpenCV 4, I suggest you to build from sources.
62,581,829
62,587,225
Satisfied and modeled concept?
Introduction The standard specifies that each concept is related to two predicates: predicate "is statisfied by": a concept is satisfied by a sequence of template argument when it evaluates to true. This is almost a syntactic check. predicate "is modeled by": A sequence Args of template arguments is said to model a co...
a concept is satisfied by a sequence of template argument when it evaluates to true. This is almost a syntactic check. No, it is not "almost" anything: it is a syntactic check. The constraints specified by a requires clause (for example) verify that a specific syntax is legal syntax for that type. This is all that "s...
62,581,974
62,595,840
Arduino: issue running the same code in loop() and in custom function
Practicing with some Arduino code, I've encountered an unexpected behavior trying to run the same code in loop() and in a custom myfunction(). After some long trial-and-error I prepared this minimal code to replicate the issue (tested with Arduino UNO). Essentialy, for each character of a given string, the code should ...
Essentialy, for each character of a given string, the code should return the corresponding index in a char array. const char* dict = "*abcdefghijklmnopqrstuvwxyz"; // ( a -> 1 ... z -> 26 ) int find (char c, const char* dict) { const char *p = dict; while (*p) { if (*p == c) return p-dict; else p++; ...
62,582,056
62,586,322
How to initialize a boost rolling window accumulator?
I would like to initialize a boost rolling window accumulator without having to do an assignment inside a function call. This is what I see everyone do: boost::accumulators::accumulator_set<double, boost::accumulators::stats<boost::accumulators::tag::rolling_mean>> acc(boost::accumulators::tag::rolling_window::window_s...
It's not an assignment, it's a named-argument idiom. C++ doesn't have that, really, so this why it looks like an assignment: it's an Expression Template You could of course figure out the type and use it, but that would not make any difference and just make it harder to use the library correctly: boost::parameter::aux:...
62,582,143
62,587,841
Build hangs with an even modest filesize
I have a C++ program with a large vector which is stored in a header file. This vector has a size of around 1 million floats. (approx 5MB filesize). I am unable to build this program in Visual Studio. The build files are generated by cmake. If I replace this vector by a smaller vector say of size 100, my program builds...
Since you've indicated in comments that you're using std::vector<float> with an initializer, you can replace that with a static array: static const float data[] = {...}; std::vector<float> bigvec {std::begin(data), std::end(data)}; that you declare once in a .cpp file. The static array can be completely constructed at...
62,582,253
62,593,095
Viewing variable values when hover mouse over it in debug mode in Visual Studio Code
I am debugging a C++ program in Visual Studio Code. When I hover my mouse over a variable, I expect to see it's value in the small popup that appears, but instead I get some strange looking information. See the image for details. How can I change this? All the video and text tutorials that I found online seem to have n...
So its something to do with pretty printing of gdb the debugger. With MinGW its not working for STL objects like vector, string, map etc. This issue is being faced by a lot of others, found a lot of questions from past 3 months itself. The only solution that worked for me was to uninstall the existing MinGW instlattion...
62,582,276
62,585,957
boost::hash for tuple containing boost units
I want to use a tbb::concurrent_hash_map with a key of std::tuple<A...> where A... will include boost unit types. The HashCompare struct I'm using at the moment looks like this: template<typename K> struct HashCompare { static size_t hash( const K& key ) { boost::hash<K> hasher; return hasher(ke...
Indeed Boost Units does not have hash support. You can add it: template <typename... T> size_t hash_value(boost::units::quantity<T...> const& q) { using boost::hash_value; // enable ADL return hash_value(q.value()); } Smallest demo: Live On Coliru #include <boost/functional/hash.hpp> #include <boost/units/unit...
62,582,294
62,583,147
How do i use okay and cancel buttons on QDialogbox
i have a QDialog box named "WinApp" , it looks like this , so , when i click ok , the values entered inside two lineedits must be assigned to two QStrings, How can i achieve this ? Because as of now , even if i click "cancel" the values are still being assigned to QStrings. but if i click cancel the values entered sho...
Once your dialog is closed you can get its result (i.e. the value of the button that the user clicked). Something like this: WinApp dialog; dialog.exec(); if (dialog.result() == QDialog::Accepted) { yourString = dialog.getDialogueValue(); } From the Qt docs: https://doc.qt.io/qt-5/qdialog.html#result In general r...
62,582,709
62,582,800
Allocating memory for different sizes
Allocating memory for different sizes. But sizeof pointers are same. Whats the difference? short * v = (short*)malloc(sizeof(short)); std::cout <<"....adress.."<< sizeof(&v) <<endl; v=(short*)malloc(sizeof(short)*999); std::cout <<"....adress.."<< sizeof(&v) <<endl; result is 8 for both. I expected 99...
sizeof(&v) is - since &v is a pointer - the size of a pointer. This is constantly 8 on a 64 bit machine (regardless of the size of allocated memory to which this pointer points). BTW: The C++ standard does not provide a way to find out, when only having a pointer at hand, how large the memory block to which this pointe...
62,582,730
62,589,671
operator overload with template specialization
This is one answer i see and got confused Based on the answer of this question, explicit specialization is needed because if a template function is changed, while the overloaded function did not change, then the overloaded function would get called silently. It is confusing, since I am wondering is that the only use ca...
A<T>::operator=(const T&) & is templated (because it’s part of a class template), but it is not a template. As such, it’s impossible to specialize it (except “as a member of A”, which is a rare and irrelevant case). Each specialization of A has two assignment operators; note that it’s impossible for T to be A (and ca...
62,583,109
62,583,770
sorted vector of pair (std::vector<pair<int, int>>) Search by first element of pair and update the second element value
I have a Vector of pairs (std::vector<pair<int, int>>) with sorted order by first of pair. I wanna update the second value of the pair by searching the first value of the pair. vector<pair<int,int>> v = { {1, 5}, {4, 26}, {5, 3}, {7, 13}, {12, 43}, {17, 31} }; I would like to update the second value of the pair as 27...
You can perform a binary search on a sorted vector using std::lower_bound. The result is the iterator to the first element greater or equal than the argument. You have to manually compare the result for an exact match. auto it = std::lower_bound(v.begin(), v.end(), std::make_pair(12, 0)); if (it != v.end() && it->first...
62,583,354
62,586,133
rvalue reference (expression) returned by function is xvalue - but no identity?
According to What are rvalues, lvalues, xvalues, glvalues, and prvalues? and some other explanations, my understanding is that xvalue is the expression which has identity and is safely moved (or is so marked). Some texts like this and this say that, if a function f()'s return type is rvalue reference, then the expressi...
Does prvalue suddenly have "identity" if it's returned from a function as an rvalue reference? Yes, actually. The standard pretty much says that outright: [conv.rval] A prvalue of type T can be converted to an xvalue of type T. This conversion initializes a temporary object ([class.temporary]) of type T from the prv...
62,583,617
62,650,967
Exit statements won't exit all processes
I'm currently running a mini shell with a C++ program, and when the user types "exit", the main_func() returns -1. At that point, the print statement (in the child process) will print, which is followed by exit, yet the loop (in the parent process) continues to run. Only time it'll actually end is if I use the kill she...
Fundamentally, fork() creates a separate process (child). Most of the actions taken in the child process are not reflected in the parent. exit() is one such action. After calling exit(), the child is terminated, and the parent remains unaffected (well, SIGCHLD is passed to the parent who is mostly ignored). So to notif...
62,583,636
62,583,870
Is there a way to allow inheritance only for final classes in C++
I have a base class that I want to be inherited from only by classes marked as final (or classes that are not themselves inherited from). The underlying idea is that I want to forbid inheritance from this class by other superclasses, at compile time. For example: class O { /* Some compile time check here */ }; class A ...
You can use CRTP and std::is_final together. #include <type_traits> template <typename CRTP> class Base { public: ~Base() { static_assert( std::is_final<CRTP>::value ); } }; // This will trip a compile time static_assert when the class is instantiated. class Derived : Base<Derived> { }; class Derive...
62,583,886
62,592,681
1d.exe can't find SFML files?
I am trying to use SFML for the first time. I have installed everything correctly but I keep getting these same errors: 1d.exe: Cannot find -lsfml-window-s-d I'm using Code::Blocks and it cannot find ANY of the files. Does anyone know how to fix this?
Just copy all files from "SFML/bin" to your project folder where main.cpp is.
62,584,835
62,584,919
Array of different types of user defined classes
So basically I am trying to figure out a way of creating array where each element could be a different type (I am creating an Equipemnt which contains all items owned by player where each item is separate class) Each of classes (B,C,D) has one method of exactly same name which is used when particular tab[] element is c...
Use std::variant type like std::vector<std::variant<B, C, D>>
62,585,289
62,585,463
Is there a difference between use const keyword inside typedef and outside typedef?
I have written a typedef like the following: typedef wchar_t *cString; and I put the const keyword independently as follow: void func(const cString) But when passing wstring::c_str() to the previous method func(wstring::c_str()), it tells me there's an error argument of type "const wchar_t *" is incompatible with par...
typedef wchar_t *cString; declares cString as a mutable pointer to mutable data. const cString declares a const one of these, which is therefore a const pointer to mutable data. The matching typedef for this would be typedef wchar_t(*const cString);, I think. (One wouldn't normally typedef a const pointer like this, s...
62,585,295
62,585,337
How to solve for each loop compiler error in c++?
Hi I am using this as my compiler Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/4.2.1 Apple clang version 11.0.3 (clang-1103.0.32.62) Target: x86_64-apple-darw...
Well, it actually told you. Compile with G++ -std=c++11 2dForEach.cpp EDIT: Sorry, mis-copied arg :)
62,585,310
62,585,378
Converting strange string to double C++
I need to convert data from a file to a double and sometimes the data is in the form: 0.3387000000D+02 0.6067999217D-02 0.5095000000D+01 0.4530799416D-01 0.1159000000D+01 0.2028219738D+00 0.3258000000D+00 0.5039029350D+00 0.1027000000D+00 0.3834209505D+00 How would you tackle handling the D here? This is scientif...
Replace the D, with an E with std::replace, after that it's straight forward: Live demo std::string s = "0.3387000000D+02"; std::replace( s.begin(), s.end(), 'D', 'E'); std::cout << std::stod(s); Or std::replace_if: Live demo bool isD(char c) { return c == 'D'; } std::string s = "0.3387000000D+02"; std::replace...
62,585,924
62,591,972
Two classes referencing each other with hash template specialization
I have two classes, A and B, which both need to be able to reference each other, as shown below. // A.h class B; // Forward declare B template<> struct std::hash<B>; // Forward declare hash template specialization for B class A { std::unordered_map<B, int> map; }; // B.h #include "A.h" class B { A object; }...
For forward declaration of class B, the compiler has the name of class B, but no nothing about its attributes (size). So that you can't use it, to defined std::unordered_map<B, int> map;, but you can make undefined std::unordered_map, using pointers (*) or reference (&) static std::unordered_map<B, int> &map; or std::...
62,586,825
62,587,021
What is expr[{ ... }] for?
This page on cppreference says: Built-in subscript operator The subscript operator expressions have the form expr1 [ expr2 ] (1) expr1 [ { expr, ... } ] (2) (C++11) … 2) The form with brace-enclosed list inside the square brackets is only used to call an overloaded operator[] Other than this, there's no example o...
Its purpose is to allow initialization of any argument type from a brace-init-list. It's added in C++11 to go along with the new initialization syntax, where braces were allowed as initializers for all types (as opposed to just for aggregates). An example std::map<std::pair<int, int>, double> m { // content }; // lat...
62,586,900
62,598,351
Am I right for using a shell script instead of AX_CHECK_COMPILE_FLAG in my build system?
I am currently working on a simple virtual machine project and have been using Autotools to reach as many systems as possible! Originally, I utilized AX_CHECK_COMPILE_FLAG to enable -Wall -Wextra -pedantic -g3, yet I feared that this would prevent the user from setting their own flags through $CXXFLAGS variable. Thus, ...
AX_CHECK_COMPILE_FLAGS just checks whether the selected compiler supports the specified flags. It does not, itself, cause the flags in question to be used in any particular compiler or linker invocation, nor does it make any persistent modification to any of the flag variables designated for the user, such as CXXFLAGS...
62,587,357
62,588,131
How to calculate the required scale of a rectangle to fit the screen
I want to fit my rectangle to the screen size with regards to the camera position. This is the VBO data for the rectangle. width = 50.0f; height = 50.0f; verticesRect = { // Positions // Normal Coords // Texture Coords width, height, 0.0f, 0.0 , 0.0, 1.0 , 1.0f, 0.0f, // Top Ri...
At perspective projection, the projected size on the viewport depends on the distance to the camera (depth). aspect = width / height height_vp = depth * 2 * atan(fov_y / 2) width_vp = height_vp * aspect In your case the object is drawn around (0, 0, 0) and the distance of the camera to the origin is 500. The filed ...
62,588,083
62,595,218
Lua kills multithreading performance as thread count increases (Bar Graph Included)
My Qt/C++ app uses worker threads (QThread) to improve performance for users with multicore processors. Each worker's job is to manipulate some data. Each worker minds it's own business and does not need to communicate with any other workers. They also don't perform any IO operations. Perfect use case! The use of multi...
I was able to figure out the issue, and it was unrelated to Lua, QThread, or CPU caching. It's actually really unexpected. The problem lies with QMetaType lookups. When comparing QMetaMethod parameter types to determine which native functions the Lua script was attempting to call, I make use of the method QMetaType::Ty...
62,588,340
62,588,732
Why local int variables inside `main` function will be initialized automatically?
I'm new to C++ and have that problem while learning C++. Here is the code #include <iostream> using namespace std; void another_func() { int a; cout << a << endl; } int main() { int a; cout << a << endl; another_func(); } I'm using g++ (GCC) 10.1.0 and I found that everytime when I run the code, ...
Uninitialised doesn't mean non-zero, it could have any value. On many OSs freshly allocated memory pages are filled with 0 so in non-debug code uninitialised values are often 0 too. The behaviour of your program is undefined but what is likely happening is that a in main is either the first use of the stack or you just...
62,588,433
62,589,035
Is a "catch all" block which deallocates dynamically allocated memory and then rethrows a valid/good design choice?
I am usually making use of modern C++'s features like smart pointers and rarely using raw pointers as handlers for dynamically allocated objects. Therefore, I don't have much experience with deallocation. I've wondered whether the following code example would be a valid choice of design to prevent exception induced mem...
What you suggest will work, however, I would recommend against it. C++ is one of very few languages that has the concept of RAII, which is created to do exception safe code. In short, of you have a call, it gets/creates the owning thing it's constructor and does the cleanup in it's destructor. Some very good examples o...
62,588,831
62,589,180
What exactly is the 'vertexPosition_modelspace' attribute
I am new to OpenGL and was doing this tutorial. This was in the vertex shader code: layout(location = 0) in vec3 vertexPosition_modelspace; I understand what layout is doing, but could not find anything about vertexPosition_modelspace
Explained by m-zayan: It's an attribute, it's not a keyword (syntax), same as defining variable This line could be interpreted as follows, I am going to use a buffer (x) specified by layout to add some value (vec3 type) to vertexPosition_modelspace
62,588,859
62,711,532
Button hover is not working in Tab widget with vertical layout in QT
I am working on GUI application in QT C++. I have a form with grid layout. One of the cell of grid filled with tab widget with some buttons, combo box and text boxes. All the widget in this tab are not working with mouse hover effect. I am using style sheet, I applied it one centeralwidget stylesheet and also for indiv...
I solved this problem as follow. I removed all the styles related to pushbutton from all widgets i.e. mainWindow, pushbutton, centerWidget etc. Put the style QPushButton { background-color: #ffc000; } and QPushButton:hover { background-color: #66c011; } in the tabWidget (instance of tab on which you are working) It w...
62,588,995
62,638,732
meta-qt5 do_populate_sdk does not create qmake on yocto zeus
I'm trying to create cross-compiling tools for my c++ application to compile it and push binaries to arm64 device (jetson-nano) during image building. I've added inherit populate_sdk_qt5 line to my own recipe and bitbake -c populate_sdk <my-recipe>. I've got no errors so I run .sh file I've got as an output. It works f...
Try to sync your meta-tegra. There was an update just a few days ago.
62,589,726
62,589,878
use of: index & 0x01
I want to know about what is the use of that (index & 0x01) in the code? if(((arr[index] >= 0) && (!(index & 0x01))) || ((arr[index] < 0) && (index & 0x01))) { outofplace = index; }
A number is odd if and only if its last digit is odd, regardless of the base. So if we want to know the number's oddity, it's enough to check if the last bit is set. index & 0x01 will be 1 if and only if index is odd.
62,590,096
62,590,233
What does "while(node!=NULL&&node->next!=NULL)" signify in linked list. How to use it efficiently
I'm confused about this while condition. My thinking is that if I already check node!=NULL then what is the use of checking node->next!=NULL in this case... Removal of every kth node in the linked list Node* delete(Node *A,int k) { if(A==NULL) return NULL; if(A->next==NULL&&k==1) return NULL; if(k==1) retur...
head->next checks if there is any node next to the head. It is important to check here, because you are assigning head->next = head->next->next; In case you don't check head->next != NULL and suppose there is no next node to the head or head->next = NULL, then it will lead to segmentation fault as it will try to find ...
62,590,196
62,593,107
How best to implement the "newtype" idiom in C++?
Since learning Rust, I've become a fan of the newtype idiom which I gather Rust borrowed from Haskell. A newtype is a distinct type based on a standard type which ensures that function parameters are of the correct type. For example, the old_enough function below must be passed an age in Years. It will not compile with...
If you have boost, BOOST_STRONG_TYPEDEF does exactly what you want as already seen in this answer. There is nothing in the c++ language (yet) that can do it directly as you want. But then again, detailed needs could be different, eg. someone might say it's ok to do an implicit construction where as another might say i...
62,591,019
62,593,390
C++: Issues with handling Errors in Abstract Class
Iam currently working on an assignment wherein; I have to create my own array and array exception class. SetElement(int arg) and GetElement(int arg) part of Array class, need to account for out of bound exceptions by throwing OutOfBoundsExcpetoinObject(Derrived) part of the Array Exception class (Base)., I have to cat...
You should catch by reference to base, which can bind to a derived object: catch (ArrayException const& abc) Then just throw OutofBoundsException(index) directly,
62,591,234
62,592,560
Debugging types with MSVC
Consider the following code: template<class T> void foo() { T x; } How can I find the type of x while debugging? Adding typeid(x).name() is invalid in the watch list. How do people generally debug template metaprogramming?
Just add x itself to the watch list. The third column of the watch window will list the actual type of x, i.e. the T used to instantiate foo<T>
62,591,304
62,591,588
Move constructor called twice when move-constructing a std::function from a lambda that has by-value captures
When move-constructing a std::function object from a lambda, where that lambda has by-value captures, it appears that the move-constructor of the object that is value-captured is called twice. Consider #include <functional> #include <iostream> struct Foo { int value = 1; Foo() = default; Foo(const Foo &)...
This is caused by how std::function is implemented. Consider the following much simpler example: struct Lambda { Lambda() = default; Lambda(const Lambda&) { std::cout << "C"; } Lambda(Lambda&&) { std::cout << "M"; } void operator()() const { } }; int main() { auto lambda = Lambda(); std::function<void()> f...
62,591,352
62,592,722
configure: error: Didn't find the MySQL include dir
I am getting an error with configure. This is the cmd I am running ./configure --with-mysql-lib=/lib64 --with-ev-lib=/usr/lib64 The full error: checking for MySQL include directory... no configure: error: Didn't find the MySQL include dir in '/usr/include/mysql /usr/local/include/mysql /usr/local/mysql/include /usr/l...
so it turns out that mysql++ 3.2+ was need i had 3.1 installed
62,591,472
62,591,583
What does #define Dbg(fmt,...) (0) mean? warning: expression has no effect
I am working on removing warnings from legacy code when I encountered the below macro #define DISBALE_DEBUG #ifdef DISBALE_DEBUG #define Dbg(fmt,...) (0) #else #define Dbg print #endif and used in the below code: #ifdef __arm__ Dbg("\n %s %s %d %d \n", __FILE__, __FUNCTION__, __LINE__, mode); #endif for...
If you enter the DISBALE_DEBUG #ifdef branch, the Dbg macro will be defined as a variadic macro which just consumes its variadic arguments and does nothing with them. I.e., a call such as Dbg("\n %s %s %d %d \n", __FILE__, __FUNCTION__, __LINE__, mode); will resolve to (0); which, as the compiler accurately warns yo...
62,591,790
62,593,623
C-style casting references
Consider the following: template<class T> struct call_fn; template< > struct call_fn< void( ) > { using sig = void ( ); void * fn; void call() && { static_cast< sig * >( fn )( ); } auto && change() { return (call_fn<void __vectorcall( )>&&)(*this); } }; template< > stru...
(since it cannot be done any other way using c++ casting) (s<int>&&)(s<float>()); This cast can be done with C++ style cast. The equivalent is: reinterpret_cast<s<int>&&>(s<float>()); is this a well defined cast Reinterpret casting reference to another is well defined. Accessing through the reinterpreted referen...
62,591,808
62,612,273
Is there a way to add elements to this vector?
I have a class Column.h, a template ColumnImpl.h and a Tab.h class Column { public: Column() {} virtual ~Column() {}; virtual string getType() = 0; }; template <typename T> class ColumnImpl : public Column { public: ColumnImpl() : Column() {} void addElem(const T& elem_to_add); protected: vect...
You are getting this error because all of the switch blocks need to compile even if only one is taken. p_int->addElem(data_to_add); can only compile when the type of data_to_add matches the corresponding ColumnImpl template type, and that's only true in one of the cases. Since you know what S is, you don't actually ne...
62,591,892
62,591,994
What is the linux equivalent of openning a handle to PhysicalDrive and writing to MBR in c/c++?
In Windows, you can easily open a handle to PhysicalDrive (or even \\.\c:) and write to the first sector of disk using WriteFile from user-mode, was wondering what is the equivalent c/c++ code of doing this Linux which requires the lowest privilege possible? is it possible to do this in Linux without running the code w...
In linux, every device is a file. So your first, physical harddrive could be /dev/sda . If you have sufficient permissions you could communicate (open, read and write) directly with your harddrive. After all .. it's just a file. As for the privilege: Any user could do that, provided he/she has the required permission t...
62,592,611
62,741,975
Opencv stops when aruco::detectMarkers crashes is called
I am trying to track my aruco markers but when I call the detectMarkers() function my application stops and I have absolutely no idea why. So I am using it like this : aruco::detectMarkers(colorMat, markerDictionnary, markerCorners, markerIds); The variables are declared like that : vector<vector<Point2f>> markerCorne...
As you see there: colorMat = Mat(colorHeight, colorWidth, CV_8UC4, &colorBuffer[0]).clone(); You're creating a cv::Mat that has 4 channels, that are the Blue, Red, Green, and alpha channel; so your Mat is holding a BGRA image. Like you see in the error, detectMarkers want either a BGR (or RGB) image (3 channels) or a ...
62,592,670
62,594,068
QML access C++ model from parent component in nested object
I have a C++ list model, where I can read data properly model.h class Animal { public: Animal(const QString &type, const QString &size); //![0] QString type() const; QString size() const; private: QString m_type; QString m_size; //![1] }; class AnimalModel : public QAbstractListModel { Q_OBJE...
Ok, that's really funny bug. First of all, according to the Qt docs the property definition is: [default] [required] [readonly] property <propertyType> <propertyName> as you see the keyword property is mandatory. The another issue is setInitialProperties says: Note: You can only use this function to initialize top-lev...
62,592,717
62,592,932
Getting Error Debug Assertion Failed: Expression c >= -1 && c <= 255
I have following code which works well on my ubuntu system: #include <algorithm> // ... other functions bool IsHexPrefixed(const std::string& input) { return input.substr(0, 2) == "0x"; } std::string StripHexPrefix(const std::string& input) { return IsHexPrefixed(input) ? input.substr(2, input.length()) : inpu...
The reason is just what the assertion says. isxdigit is undefined if it's argument is not represented as unsigned char or EOF(see notes here). Since it takes an int argument, it's highly likely your string contains chars in range 129-255 (probably by containing non-ASCII text), so they get promoted to negative integer ...
62,592,795
62,592,928
Exceptions Using Inheritance?
I wrote the following code: class GameException : public mtm::Exception { }; class IllegalArgument : public GameException { public: const char *what() const noexcept override { return "A game related error has occurred: IllegalArgument"; } }; class IllegalCell : public GameException { public: cons...
The error is because char [] + std::string yields a std::string but the method is delcared to return a const char *. To avoid problems with returning a pointer to temporary, I would suggest this: class GameException : public mtm::Exception { std::string message; public: GameException(const std::string& pref) ...
62,593,093
62,593,667
Is it legal to declare a type as part of the template-argument for a type template-parameter?
All standard references below refers to N4659: March 2017 post-Kona working draft/C++17 DIS. The following snippet successfully compiles for all standard versions(1) for both Clang and GCC. template<typename Tag> struct Tagged {}; Tagged<struct Tag1> t1; Tagged<struct Tag2> t2; [temp.arg.type]/1 requires that A tem...
(It seems the OP (myself) did not initially go deep enough down the type-id grammar rabbit hole) Is it legal to declare a type as part of the template-argument for a type template-parameter? Yes, this is legal. If so, which part of the standard (say, C++17) governs this? A class-key and identifier grammar sequence...
62,593,147
62,593,760
C++: browse filenames in Windows which have dots inside the names
Let's take as example the following file name: abc.def.txt. I'm using FindFirstFileA() and FindNextFileA() in order to browse a directory. The function looks like this: std::vector<std::string>* readDir(std::string pattern) { auto v = new std::vector<std::string>; pattern.append("\\*"); WIN32_FIND_DATAA dat...
It looks like you're finding the old 8.3 name. You'd want FindFirstFileEx with level FindExInfoBasic. This ignores 8.3 names.
62,593,683
62,593,816
Integer is uninitialized in VSCommunity2019,windows10
I am making a calculator in c++ and I have everyting done except factorial which has one issue: my int number is "uninitialized" this is a console application on vscommunity2019 on windows10 if that helps. Everything works perfect except factorial,when I test it theonly error is the int number. #include <iostream> usin...
Well, number is uninitialized. int main() { int number; //uninitialized local variable [...] //no usage of number case '!': for (i = 1; i <= number; i++) { //first usage of number, before initializing it! fact = fact * i; } std::cout << number; break; [...] } Luckily you get a compilation error...
62,593,966
62,594,142
How to access method of class stored in std::variant
I am trying to access method of class held in std::variant. Unfortunately it throws and following error: class ’std::variant<A, int>’ has no member named ‘function’ Code: class A { private: int number = 0; public: A() {}; void function(int i) { number += i; } }; // ... main ... std::variant<A,...
To initialize a value in std::variant you can use std::get, or since C++17, emplace(): array[0][0].emplace<A>(); To access a value, use std::get: std::get<A>(array[0][0]).function(3); In addition, the template argument of std::get must be known at compile-time, so std::get<t> when t is a variable, won't work. You ca...
62,594,233
62,786,155
WinVerifyTrust only works when using a file not a memory blob
I am trying to the WinVerifyTrust function to verify the signature of a msi. And while this works for files on the file system I cannot get it to work with a memory blob. This basis of my example to show the problem is the example program from microsoft BOOL VerifyEmbeddedSignature(LPCWSTR pwszSourceFile) { std::bas...
The WIN_TRUST_SUBJTYPE_RAW_FILE is not the suitable subject GUID. You could The function CryptSIPRetrieveSubjectGuid retrieves a GUID based on the header information in a specified file.
62,594,298
62,601,972
Byte Array Initialization Causes DirectX to Crash
So I'm trying to gain access to vertex buffers on the GPU. Specifically I need to do some calculations with the vertices. So in order to do that I attempt to map the resource (vertex buffer) from the GPU, and copy it into system memory so the CPU can access the vertices. I used the following SO thread to put the code t...
There was no Vertex Buffer bound, so your IAGetVertexBuffers failed to return anything. You have to create a VB. See Microsoft Docs: How to Create a Vertex Buffer As someone new to DirectX 11, you should take a look at DirectX Tool Kit.
62,594,672
62,595,244
Placement new depends on iostream
Why does placement new depend on #include <iostream>? Sounds absurd? Well, this code only compiles if incommenting the include: // #include <iostream> struct Alignas { void* ptr; }; alignas(Alignas) static char storage[sizeof(Alignas)]; int main() { new(storage) Alignas; } Gcc error (same with Clang): alignas.cpp:7...
Why does placement new depend on #include <iostream>? It doesn't. Placement new depends on <new>. And it depends on it because the language says that it depends on it. It has to do with operator new overloads which are called by placement new and are declared in <new>. <iostream> just happened to include <new> for yo...
62,594,688
62,594,781
Using a c++ builder application with an external dll
I'm trying to use an external dll in my c++ builder application. The dll (let.s call it X.dll) was created with Qt Creator (using MingW 32 bit compiler, tried gcc as well ) and consists of a single functon to keep things simple (besides X.dll, an import library X.a is also created). The dll header (Dll_lib.h) is basica...
C++ environments have a habit of name mangling to support overloads, different arguments with the same name, like: int use(int x, char y); // mangles to something like use__Int__Chr. int use(double x); // mangles to something like use__Dbl. This allows the correct one to be linked depending on the arguments. You ...
62,594,762
62,611,163
Linking glade file with program g++
Glade files and the program files can get a bit messy, this becomes a problem when you want your program to be portable. Is there any way to bind your program with your glade files? Source code (unfinished but working project): https://github.com/caelwithcats/valuator
You can use Gio Resources to include the contents of your .glade files in the application, and then use GtkBuilder's add_from_resource() to load them: https://developer.gnome.org/gtkmm-tutorial/stable/sec-gio-resource.html.en
62,594,898
62,594,942
How to link/include c++ libraries correctly
I tried to compile program with https://github.com/yhirose/cpp-httplib "one-header" library. I wrote #include "httplib.h" /* example code from main github page */ and when i tried to compile program g++ -std=c++11 -o test test.cc i got this error: /usr/bin/ld: /tmp/ccYMj4l8.o: in function `std::thread::thread<httplib...
It's gcc's known particular feature, its std::thread implementation is built upon pthreads so it requires specifying -pthread to correctly link programs with threads.
62,594,924
62,639,357
How to unite several models into one?
I've created two models and now it's need to be united in one. Both of them are inheriting QAbstractListModel and contains only roles and simple data as QVector<QMap<..., ...>> backing; what I pass to data() function There's any way to unite them into one model and pass to Qml page through delegate? Here my models: Ext...
You are probably better of writing a plain class with Q_PROPERTY to ExtraModel class MainModel : public QObject { Q_OBJECT Q_PROPERTY(ExtraModel* extra READ extraModel CONSTANT) public: MainModel(); ExtraModel* extraModel() const { return extraModel_; } private: ExtraModel* extraModel_ = nullp...
62,594,961
62,595,021
Never ending file reading loop (C++)
There's some code I wrote that should read all new lines in a text file, but it gets stuck on one of the loops it runs. The code is as follows: #define MAX_MESSAGE_LENGTH 200; fstream("some/random/file.txt", ios::in | ios::out); streampos fileSizeReference = 0; vector<string> messages; vector<string> onDisplay; char...
You have two errors (at least). do { fileReader.getline(message, MAX_MESSAGE_LENGTH); string newMsg = message; messages.push_back(newMsg.substr(0, MAX_MESSAGE_LENGTH)); } while (!fileReader.eof()); should be while (fileReader.getline(message, MAX_MESSAGE_LENGTH)) { string newMsg = message; messages...
62,595,690
62,596,676
Initialize multiple dimension array
How can I initialize array with variables like int x[row][col]; int myArray[7][4] = { {1,2,3,4}, {5,6,7,8}, {5,6,7,8}, {5,6,7,8}, {5,6,7,8}, {5,6,7,8}, {5,6,7,8} }; i want to initialize array as this = int myarray({2,3,4},{12,4,5},{2,2,2})
The exact answer is you cannot initialize an array like that, i.e., without providing both row and col at compile time, though std::vector can do the job for you. You can use some code like this: #include <iostream> #include <vector> void print_vector(std::vector<int> &v) { std::cout << "{ "; for (auto &&i : v...
62,595,785
62,595,832
How do you use std::make_shared to create a smart pointer of a base class type?
What am I doing wrong here? I cannot believe the below doesn't compile. Do you need to use a shared pointer cast or something? struct Base { }; class Child : Base { }; int main() { std::shared_ptr<Base> p = std::make_shared<Child>(); } The error I get with Microsoft compiler is error C2440: 'initializing': canno...
It does work. It's just that Base has private inheritance. struct Child : Base{}; or class Child : public Base{}; are fixes. Interestingly std::static_pointer_cast and company do exist; but you don't need them here. See https://en.cppreference.com/w/cpp/memory/shared_ptr/pointer_cast
62,595,969
62,596,174
C++ declaring double-linked list, traverse list both ways with two for-loops and print
Just beginning with C++ (be gentle, please). I have some code and I have to: Add Element* to make doubly-linked list Add insert_before() and insert_after() methods to Element Traverse list both ways with two separate for-loops Print operating number inside each loop Code I tried the following: #include <cstdio> stru...
In your insert functions, you are not linking up all the pointers correctly: void insert_after(Element* new_element) { new_element -> previous = this; new_element -> next = this -> next; this -> next = new_element; if (new_element -> next) // this check needed // to correctly link the next -> p...
62,596,105
63,760,343
gtkmm load from resource plain text file
I have a simple resource xml file looks like <?xml version="1.0" encoding="UTF-8" ?> <gresources> <gresource prefix="ui"> <file preprocess="xml-stripblanks">ui.glade</file> </gresource> <gresource prefix="text-data"> <file>definitions.txt</file> </gresource> </gresources> And UI loade...
You are able to retrieve the file contents with one of two static methods of Gio::Resource class: open_stream_global or lookup_data_global. Here are their signatures: Glib::RefPtr< InputStream > open_stream_global (const std::string& path, ResourceLookupFlags lookup_flags=RESOURCE_LOOKUP_FLAGS_NONE) Glib::RefPtr< cons...
62,596,331
62,627,975
why I search in map stl time difference is a lot?
When I use a std::map, it seems that accessing elements takes a different amount of time based on the method used. First Method: Direct Access cnt += umap[t]; Second Method: if (umap.find(t) != umap.end()){ cnt += umap[t]; } The second method seems to be quite a bit faster than the first method, and I don't under...
Each of the code snippets is doing a different thing. The first snippet takes more time because it inserts a key t to umap, if it does not exist (and initializes it with zero), before adding it to cnt. In second snippet no key is inserted. Because of the if condition, umap[t] is (called then) added to cnt only when uma...
62,596,989
62,597,118
c++ async keyboard input(standard way)
I'm trying to make a c++ snake game in linux using ansi escape codes but i can't figure out a way to get async keyboard input. Im a beginner and i'm currently reading a c++ book, so i didn't cover multithreading yet. Is there any chance to achieve this result in a "simple" way.(and standard if it's possible, i saw the ...
C++ does not offer a standard way to asynchronously read the keyboard status. boost asio, as in read from keyboard using boost async_read and posix::stream_descriptor is one way. Some people consider boost like a "standard" or "normal" C++ extension. Another way is to use a game library like SDL or SFML. You include th...
62,597,346
62,597,596
C++ VISUAL STUDIO: GLFWwindow not initialized even if it is written in the docs and worked before
VS2019 says that GLFWwindow* is not initialized. It says it as a warning and then does not compile. Also it worked before and it says it only in the start_window function. ...main.cpp(19): error C4700: uninitialized local variable 'window' used ...Done building project "CityEngine.vcxproj" -- FAILED. I tried: (Advice ...
C4700 is usually a warning and only behaves like an error when "Treat warnings as errors" is enabled To get rid of this warning, you should initialize the variable with: GLFWwindow* window = nullptr; makes the window invisible and not responding This happens because the window parameter of start_window does not do w...
62,597,471
62,601,159
Why don't we write assemblers and linkers that can handle C++ identifiers?
My understanding of why we use name mangling is that assemblers and linkers can only handle C identifiers. "int foo::bar::baz<spam::eggs>(const MoreSpam&)" can't be used as a label by any existing assemblers, and existing linkers won't recognize it as a valid function signature, so it becomes something like "_ZN3foo3ba...
You can actually use int foo::bar::baz<spam::eggs>(const MoreSpam&) as an identifier with the GNU assembler, you just need to put the name in quotes: "int foo::bar::baz<spam::eggs>(MoreSpam const&)": ret $ as -o test.o test.s $ nm test.o 0000000000000000 t int foo::bar::baz<spam::eggs>(MoreSpam const&) $ ld te...
62,598,528
62,598,881
How is this recursive function working even though it is not being called?
I am learning c++ and I am having trouble understanding this recursive method I will try to explain line by line long factorial (long a) { if (a > 1) return (a * factorial (a-1)); else return (1); } so here is my explanation long factorial (long a) this function returns a long...
Say you call factorial(2) somewhere in the code. The following happens: The factorial function is invoked with a equal to 2. The function calls factorial (a-1). The current execution of factorial is suspended and a new instance executes. In this instance, a is 1. This instance returns 1 to the original instance. The o...
62,598,549
62,598,625
confused with a variable within a for loop
int getTo(int value) { int total{}; for (int count{ 1 }; count <= value; ++count) total += count; return total; } int main() { getTo(5); return 0; } first time post, please excuse any formatting issues. im struggling to understand where the variable total is used within this for loop, wh...
In the function getTo(), total is first default-initialized (meaning that it takes a value of 0). The for-loop sets a variable count = 1, then constantly increments it until it reaches value, adding it to total each iteration. For getTo(5), it would do this: getTo(5) initializes total to 0 getTo(5) initializes count ...
62,599,046
62,599,094
What is pointer pointing to when there's no element in that array's index?
I created an array of int A[5] = {2,4,6,8,10}; and made two pointers int *p=A, *q=&A[5]; since there's only five elements in the array, as far as I understand in c++, when there's nothing it's supposed to be zero. When I try to print out cout<<"*p = "<<*p<<endl; cout<<"*q = "<<*q<<endl; I got this one instead *p = 2...
As far as I understand in c++, when there's nothing it's supposed to be zero. You've misunderstood. cout<<"*q = "<<*q<<endl; Here you indirect through a pointer that points outside the bounds of the array, and attempt to access a non-existing element. The behaviour of the program is undefined. Can someone explain...
62,599,133
62,599,441
how to solve invalid type argument of unary ‘*’ (have ‘char’) error?
Running the code snippet below, generates this output error. can somebody explain WHY? Output Error error: invalid type argument of unary ‘*’ (have ‘char’) if(* i =='<') The Code string a; for(auto i:a) { cout<< i <<endl; if(*i=='<') { //... } }
Understanding the error: error: invalid type argument of unary ‘*’ (have ‘char’) Unary operator is an operator with only one operand. In this case it is *. It has an invalid argument i.e., char. Because a std::string contains chars and not char*. So : if(*i=='<') *i is char here. When you dereference it, you get the...
62,599,389
62,599,628
How do vectors and other containers work on the disk?
I'm having trouble finding information regarding this online, likely because I don't know what terms to use. When I create a vector, array, unordered map, etc. in C++ or any similar language, what happens on the disk? I always imagined that the vector acts as a list of pointers pointing to memory addresses on the disk ...
Normal containers do nothing on disc, they are purely memory constructs. An array (std::array) is simply a wrapper around a native array type which is a sequence of objects of all the same type. A vector object will generally directly contain a base pointer and either an end pointer or a size, as well as an allocator (...
62,599,402
62,599,487
Can I calculate modulus of large number by taking modulus of each digit and taking sum?
The problem is, I got all digits of a very large number, I need to find whether it is divisible by 3. I tried my approach which I suppose is wrong but I don't know why This is my approach for example problem is (159%3) I could write it as (100+50+9)%3 the above statement can be written as (1%3+5%3+9%3)%3 by (a+b)%c=(a%...
To check for divisibility by 3, you only need to check if a number's digits sum to a number that is divisible by 3. For example, 159 is divisible by 3 because 1+5+9 = 15, which is divisible by three. Note that this approach only works for 3 and 9, so don't try using this for other modulos!
62,599,431
62,601,036
boost::asio data owning `ConstBufferSequence`
The last days, I read alot through the asio examples and other questions here on SO regarding lifetime management of buffers passed to asios initiating functions. One issue that strikes me, is that there seems to be no "by value" solution, but instead the caller of the initiating function always needs to ensure that th...
I've seen a shared_buffer before (I think it was in the Asio docs/exmples, will search later). Furthermore there's obviously boost::asio::streambuf the Beast buffer models (flat_buffer, multi_buffer, vector_buffer) Of course, it just moves the problem from an ownership issue into a life-time issue. The upside of havi...
62,599,514
62,604,178
How to wrap (compose) a boost hana map and access the bracket operator (operator[])?
I'm using a hana map (created using hana::make_map). I have a very simple class that would inherit from the hana map, and expose a second map as such auto values = hana::make_map( ... ); auto uncertainties = hana::make_map( ... ); template< typename Values, typename Uncertainty > struct map: Values{ Uncertainty unc...
It's typically preferred to use an aggregate vs inheritance. As "Mooing Duck" stated in the comments, you can just use a function to forward the operator[] to the values map. Looking at the implementation of operator[] in Boost.Hana you'll notice there is an overload for each value type since this cannot be deduced. (T...
62,599,941
62,600,112
Make all files in a folder accessible to all projects (subdirectories)
I have multiple projects (subdirectories) inside my repository. All projects have only one executable file named main.cpp and they all use libraries from the common folder with #include statements. The folder structure looks like this: root | ├────common | ├──── example.h | ├──── example.cpp | ├──── *.h ...
Add a CMakeLists.txt to your common/ directory: root | ├────common | ├──── CMakeLists.txt <-------- Add this | ├──── example.h .... common/CMakeLists.txt file(GLOB_RECURSE CommonLibsFiles ${CMAKE_CURRENT_SRC_DIR}/*.cpp) add_library(CommonLibs ${CommonLibsFiles}) ... root's CMakeLists.txt ... ### NO NEED FOR TH...
62,599,961
62,600,219
Using [][] operator with vectors?
I have created a one dimensional vector of int, how may I treat it like 2 dimensional one? While I can write arr[1]; I can't write arr[1][2]; Why I need this: Instead of defining a vector of vectors [3x5] I defined a vector whose length is 15, so every time I have a function that takes coordinations of a place in matri...
Assuming you want to treat a 1D array of size N as a 2D array with M columns, then you can write a helper function that computes the 1D index given 2D indexes: auto in = [M] (int i, int j) { return i * M + j; }; and then use it like this: arr[in(i,j)]; This is at least preferable to saying arr[i * M + j] everywhere, ...
62,599,977
62,655,693
Pattern "allocate memory or use existing data"
I have field std::map<std::string, std::map<unsigned int, float>> widths; I copy data to widths[key] from another map or insert custom data to widths[key] depending on runtime criteria. However, copying is too slow. I am going to use pointer to std::map<unsigned int, float> as widths::value. Thus(depending on runtime c...
Following wrapper is created: class Widths { public: Widths() : widths(new std::map<unsigned int, float>), to_be_deleted(true) { } Widths(const std::map<unsigned int, float> *arg) noexcept : widths(const_cast<std::map<unsigned int, float>*>(arg)), ...