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,378,018
63,394,687
Prevent boost::asio::io_context stopping on empty poll call
This code calls the posted handle boost::asio::io_context ioc; boost::asio::post(ioc, []{ std::cout << "lol" << std::endl; }); ioc.poll(); whereas this doesn't: boost::asio::io_context ioc; ioc.poll(); // empty, set internal state to stopped_ boost::asio::post(ioc, []{ std::cout << "lol" << std...
io_service/io_context are designed to stop when they run out of work¹. The docs for io_service and io_context contain: Stopping the io_context from running out of work Some applications may need to prevent an io_context object's run() call from returning when there is no more work to do. For example, the io_context ma...
63,378,690
63,379,485
Why am I getting a logic error in this Karatsuba Multiplication?
I've read many blogs and examples of code but I'm trying to implement the Karatsuba multiplication through a way that is currently not logically working. Only single digit number multiplications are working, but any digits longer than 1 are displaying completely wrong answers. It should be able to take in long numbers ...
The main problem is int p = (p0*(pow(10,length))) + (sum * (pow(10,length)) + p2); It should be int p = (p0*(pow(10,length))) + (sum * (pow(10,length - 1)) + p2); You shouldn't use std::pow for integers GCC C++ pow accuracy. I replaced it with my own version: #include <iostream> #include <string> #include <algorithm>...
63,378,914
63,378,999
classic array vs std::array
I try this simple program: int* getElement(int arrayy[], int index) { return &arrayy[index]; } int main() { int arrayy[4]{}; *getElement(arrayy, 2)=50; std::cout << arrayy[2] << '\n';// here it prints 50 ! return 0; } getElement() will return the address of an element of my array through a p...
In the case of passing a pointer by value, the pointed at values are the same in the function and the call site. So the first program does what you expect. In the second program, it's different because std::array has value semantics, so passing it by value means that you are passing a copy of all the underlying memory...
63,379,338
63,379,449
Passing an array to parameterized test in gtest
A parameterized test in gtest allows you to test your code with different parameters without writing multiple copies of the same test.seen here I have seen examples of passing values, std::pair, std::tuple etc. But I'm not sure how to pass an array/initializer_list into the test. Expected something like this : INSTANTI...
You can pass any type you want as the parameter. You provide type of parameters when you inherit your test fixture a from class template WithParamInterface (or TestWithParam): class FooTest: public TestWithParam<std::array<int, 3>> //class FooTest: public TestWithParam<std::vector<int>> //class FooTest: public TestWith...
63,379,417
63,379,986
Why do we need a copy constructor for reference members
I don't understand why we need a copy constructor (to begin with..) especially for the sake of reference members. Given a class class Foo { Obj &obj; }; I must now write a copy constructor and = operator (and maybe 5 other secret things), otherwise it won't compile. Why? Why would a compiler be able to figure out t...
The short answer is: because C++ standard says so. But this is not a very interesting answer. To have a more interesting answer, we can ask a different question: what might be the rationale for such behavior? While I do not claim to know the canonical answer to this, I would not be surprised if it is just to reduce con...
63,379,450
63,379,602
Initialize field with raw pointer to object after base class constructed with moved unique_ptr to same object
I have an object Foo owned by Owner and no one else. I create an object of class Derived that inherits Owner, passing it a unique_ptr to a newly created Foo. Derived has a member of class User that also needs to use Foo, but doesn't own it, so it gets only a raw pointer to it. #include <memory> #include <iostream> us...
You could delegate the work to a private constructor while duplicating the pointer: struct Derived : public Owner { User user; Derived(unique_ptr<Foo> _foo) : Derived(move(_foo), _foo.get()) {}; void use() { user.use(); }; private: // Implement the real logic here // As pointed by @Artyer in the comments...
63,379,479
63,379,620
Matrix not getting a value in some positions
The excercise requires me to make a matrix where the user chooses the size of the matrix. The matrix is filled with random numbers and then displayed on screen. For some reason the fourth slot is 0 every time no matter what the size of the matrix is. int main () { int matriz[100][100] , filas , columnas ; cout << "Ing...
Your problem is that you're declaring an int[][] but not initializing it. matriz[100][100] is declared but never initialized, by calling int matriz[100][100]{} you directly initialize it.
63,380,020
63,380,112
Why preprocessed file of simple C++ source file contains thousands lines of code?
I am learning C++. I learned a little about the C++ compilation process and the first step of the compilation process is preprocessing. I am curious what happens to source file after preprocessing so I wrote a few lines of code in C++. Here are my codes: #include <iostream> using std::cout; using std::endl; #define P...
Your hypothesis is correct: the entire contents of the iostream header are included in the preprocessor output. And this happens transitively: every header included by iostream is also included, and so on. This is essentially what #include means! However, this does not mean that your executable will be big: Headers ty...
63,380,091
63,380,929
golang alpine docker Cross compile C++
I have a golang project that relies on C for invocation and compilation. Now, I used the make all command to build in the docker image of golang:alpine and found the following error: /usr/lib/gcc/x86_64-alpine-linux-musl/9.3.0/../../../../x86_64-alpine-linux-musl/bin/ld: /go/pkg/mod/git.ipyker.com/combase/gowork@v0.0.0...
Compiling shared libraries is broken with -no-pie, which should be a noop in this case. go env -w CC="gcc -no-pie"
63,380,249
63,380,360
How can I overload a function for a concept?
Suppose I have a function template and various overloads that "specialize" the template. As overloads are a better match than the template version during overload resolution, they will always get priorized. template <typename T> void dispatch(T&& t) { std::cout << "generic\n"; } void dispatch(int) { std::cout ...
A constrained function template only beats an unconstrained function template when they have the same template-parameter-lists and function parameter types. So either make the generic one take a value (so that both take a T): template <typename T> void dispatch(T t) { std::cout << "generic\n"; } Or make the floati...
63,380,743
63,509,797
Member in a struct that isn't attributed to any type? and a struct to hold a lone variable
I'm trying to understand the code below, it is for a struct that holds XYZ and Intensity value in a pointcloud, The field PCL_ADD_POINT4D looks like a standalone statement which is not of any known type, what does that mean? is it a way to address the contents? struct EIGEN_ALIGN16 _PointXYZI { PCL_ADD_POINT4D; ...
Part 1: PCL_ADD_POINT4D refers to a macro PCL_ADD_POINT4D refers to the following lines #define PCL_ADD_POINT4D \ union EIGEN_ALIGN16 { \ float data[4]; \ struct { \ float x; \ float y; \ float z; \ }; \ }; \ here EIGEN_ALIGN16 is a SSE macro that help to optimise the point o...
63,380,757
63,380,878
Execution timed out (12000 ms): Is there a better way to do this problem?
I've had a long break from coding, so I've been doing some coding problems. In this one, I've passed the tests but the issue lies in my inefficient code. Here's the task: Given a vector 'arr' and a number n, create a new vector that contains each number of arr at most n times without reordering. For example if n = 2, ...
Is vector a list? You should do it in one pass, using an unordered_map<int,int> to count occurrences of different values; if it's below the threshold - copy it to a new list, if at the threshold - ignore and move to the next element.
63,380,801
63,381,048
How do I write a matrix in a recursive function?
when I declare a matrix inside of a function, Example: int recur(int mat[][], int....) Why the compiler return an error, but with an array it works just fine?
The compiler needs to know all dimensions except the first in order to compute an offset. Think of a two-dimensional array as having rows and columns. int mat[4][5] has 4 rows and 5 columns. In this case, this is what the array conceptually looks like. Each number is an index into the array where we'd find the corre...
63,380,811
63,380,991
How to declare Magnitude type in C++?
Say I have a template class that has to work with general types T complex and real but I also need a real type that I can store the abs(T) in. How do I get the appropriate type and make a type definition? I tried the following: template < typename T> class sth{ typedef std::invoke_result<*std::abs, Value>::type real_ty...
If you need to define in through result of expression, then it would be something like using real_type = decltype (std::abs(std::declval<T>())); declval would provide a proper argument of type T to function
63,381,196
63,382,190
Linker error when using static library with test applications in CMake
The project structure of my static library is exactly the same as defined in this question and my CMakeList.txt is exactly the same: cmake_minimum_required (VERSION 2.8) project (project_name) add_subdirectory (src) add_subdirectory (test) I want to build the test folder after my static library. I have also added...
The issue has been raised a couple times on the site, but there are some other issues with your CMake file that warrant explanation. The problem is that the linker doesn't know where to find the dal library, because you've only provided "-ldal", without a full path to the library or anything. You can fix this by simply...
63,382,055
63,382,663
How to create c++ equivalent of Objective-C completion block as param
Our iOS app depends on a c++ library. I'm new to c++, and I'm looking for the c++ equivalent of this: Definition: - (void)mySetter:(Thing)thing completion:(void (^)(BOOL))completion; Use: [self mySetter:thing completion:^(BOOL success) { // do something if successful }] I know this is a dumb question that's proba...
In C++ you would usually use std::function for this, which is a class template that can hold any kind of callable function/object including a lambda (caveat: as long as it's copyable): void mySetter(Thing thing, std::function<void(bool)> completion) { // ... completion(true); } mySetter(thing, [](bool success) { ...
63,382,145
63,382,822
CPP , creating array and i see only one parameter
i create an Array with 3 numbers; i see only one number instead 3 int *ArrayA; ArrayA = new int[3]; ArrayA[0] = 2; ArrayA[1] = 4; ArrayA[2] = 6; when i debugging and follows ArrayA i see only 2; what could be the problem?
This is not a problem. It's as expected because ArrayA is a pointer. So pointer base address and the address of the 1st element of the array are same. Hence you always see 2 in your debugger. Not sure which debugger you are using, you can try to add ArrayA[index] or *(ArrayA + index) then you can see other values as we...
63,382,179
63,382,331
inverse an oriented Graph
How can I reverse not transpose an oriented graph ? Graphe *Graphe::grapheInverse( void ){ Graphe *r = new Graphe (_adjacences.size() ); for (unsigned i = 0; i < _adjacences.size(); i++){ for (unsigned j = 0; j < _adjacences[i]->size(); j++){ //r->addArcs(j,i); this doesn't work ...
When making the reverse list, you don't want to use the index in the original list as the source vertex, you need to derefence the list. So you'll want to use r->addArcs((*_adjacences[i])[j],i); There are better ways to write that function (like range-based for loops).
63,382,266
63,383,461
UE4 C++ saving inventory TArray of item pointers across multiple levels
I have a basic inventory system in UE4 using a TArray of pointers to my custom Item class. It works fine in individual levels, but when I open a new level, the inventory disappears. I've looked at multiple tutorials and posts about this issue and tried various solutions including migrating my inventory array to the Gam...
I believe that you may have found out why the issue is occurring from our discussion in the comments, but I will try to finish our discussion with this answer. The problem is that you are trying to save an array of pointers to actors in a map. However, the actors in the map get destroyed once you call UGameplayStatics:...
63,382,610
63,387,206
SpriteBatch and SpriteFont (DirectXTK) throw an error (expected unqualified-id)
I'm using clang++ that links to MSVC. I compiled shaders (DirectXTK\Shaders) and included SpriteBatch and SpriteFont in my source code. If I include just the header files (.h), I get linking errors; if I include source files (.cpp; with or without .h), I get this: SpriteBatch.cpp:532:27: error: expected unqualified-id ...
The Windows headers define a 'min' and 'max' macro that interacts poorly with std::min/std::max from <algorithm>. In all my templates and tests, I define NOMINMAX before using Windows.h to avoid this problem. It's generally a better practice. If you still need to use a macro form while doing this, you can use __min/_ma...
63,382,853
63,385,052
Problem multiplying vec3 by model matrice (scaling problem)
in my 3D application I have an Object3D class which construct is bounding box at creation, this bounding box is a simple cuboid with a min and a max point : However, when I translate my Object3D, I want to update my bounding box using the Model matrix of my object : BoundingBox& TransformBy(const glm::mat4& model...
If I understand correctly how the result of GetModelMatrix() is supposed to look, i.e. that it is just a normal 4x4 transformation matrix, then I think I can guess what the problem is. I find it easiest to visualize/explain with an example, so hopefully that's alright. Suppose your result of GetModelMatrix() is the fol...
63,382,869
63,383,648
Error C2664 'HRESULT IUnknown::QueryInterface(const IID &,void **)': cannot convert argument 1 from 'const winrt::guid' to 'const IID &'
This error happens to me when I use the helper function from microsoft docs to migrate to winrt from cx. I see a similar question here, but the solution mentioned doesn't seem to work for me. The solution mentioned here add #include <Unknwn.h> before any other winrt headers in the file which has this error. template <t...
winrt::guid_of() returns a winrt::guid. Per What's new in C++/WinRT: Breaking change. GUID is now projected as winrt::guid. For APIs that you implement, you must use winrt::guid for GUID parameters. Otherwise, winrt::guid converts to GUID, as long as you include unknwn.h before you include any C++/WinRT headers. See...
63,382,910
63,382,995
g++.exe: installation problem, cannot exec `as': No such file or directory
I'm trying to learn C++, I downloaded and installed g++ on Windows using Cygwin, following this tutorial: https://www.cs.odu.edu/~zeil/cs250PreTest/latest/Public/installingACompiler/#installing-the-mingw-compiler Just like in the tutorial, at the end, I check that g++ is installed: PS D:\Desktop\coursera_ODS_in_c-\Week...
The message: g++.exe: installation problem clearly states that something's wrong with the installation of your G++ compiler. Also, 3.4.5 version is too old. The current stable release is 10.2 (released on July 23, 2020), reinstalling it with the latest version will probably solve your issue. (Since insufficient detail...
63,382,938
63,604,484
configure: error: Python.h not found when it exists in Ubuntu 18
I am trying to run a ./configure --with-python file (I can attach it but it's long) and I am getting these errors: checking for gtest-config... no File "<string>", line 1 import distutils.sysconfig; bl = distutils.sysconfig.get_config_var('BLDLIBRARY'); print bl if bl else '-lpython2.7' ...
You are missing CFLAGS ./configure --with-python=/usr/bin/python2.7 CFLAGS="-I/usr/include/python2.7/
63,383,272
63,383,800
C++ Opening file outside of directory via relative path not working
Opening a file in C++ outside of the working directory Using the format of the code in this post, I tried to open a file using a relative path. std::ifstream rules("/static/rules.txt"); Before I put "rules.txt" inside of folder "static", I was able to do this: std::ifstream rules("rules.txt"); without error.
Let say that your working directory is "/opt/usr1" You have to take into account few elements: 1) Path to files "/static/rules.txt" <---Absolute path from root "/" folder, meaning that your code will look for file "/static/rules.txt" "./static/rules.txt" <---Relative path from working...
63,383,300
63,383,805
what is the complexity of this power() function?
It is algorithm to find the power of a given number. How will the statements after the recursion affect the complexity if at all? int power(int b, int n){ if (n == 0) return 1; else { int p = power(b, n/2); if (n % 2 == 0) return p * p; else return b * p * p; } }
As, you're dividing n by 2 at each step, the algorithm runs until n reaches to 0. We can see what is happening: n1 = n / 2 n2 = n1 / 2 = (n / 2) / 2 = n / 4 = n / (2^2) n3 = n2 / 2 = n / 8 = n / (2^3) ... ... It runs as long as n >= (2^x), where x is any non-negative integer. So, we can say that, when 2^x > n, it stop...
63,383,312
63,383,392
Overload/specialization of a concept
Is there a way to overload/specialize concepts like templates? Consider the following pretty simple case where we just want to flag certain Types as 'simple': // overload/specialization for MyClass - WOULD BE NICE - BUT FAILS template <typename T> concept simple = false; class MyClass; template <> concept simple<MyCl...
Is there a way to overload/specialize concepts like templates? No. You cannot overload or specialize concepts. Concepts are what they are. This is by design. If I have a concept Frobnable, that concept always means what it means. The fundamental issue with template specializations is that that the specializations don...
63,383,953
63,384,235
How to parse std::string containing unicode literals?
I have std::string which stores characters encoded in UTF. Example: std::string a = "\\u00c1\\u00c4\\u00d3"; Note that the length of a is 18 (3 characters, 6 ASCII symbols for each UTF character). Question: How can I convert a into C++ string that have only 3 characters? Are there any standard functions (libraries) to...
There is nothing in the standard C++ library to handle this kind of conversion automatically for you. You are going to have to parse this string yourself, manually converting each 6-char "\uXXXX" substring into a 1-wchar value 0xXXXX that you can then store into a std::wstring or std::u16string as needed. For example: ...
63,384,940
63,384,987
Question regarding to char* function member function in class
I am trying to learn c++ from Udacity. I need some clarification if what I am understanding is correct or not. So the code is the following. TicTacToe Game: class Board {//the class tracks the game and the winner char positionsSelected[16]; char winner; public: //Constructor Board(); int setPos...
Since you are basically reading a sequence of characters, that's why it has to be char*. Better would be to make the member std::string positionsSelected;. Then you can just return std::string const & from your method. This is both safer and simpler to use. Why the parameter of getPositions(void) have to? Can t...
63,385,223
63,385,362
Run C and C++ on VS Code (and even a little problem with vs code bars)
i have some problems: i cant run c and c++ on vs code (or, i mean im trying by adding the path of MinGW on env vars, but no results by typing on cmd gdb --version, but i have by typing g++ --version) aaand i just hided this bar by mistake, how to adjust? thanks to everyone!
1- Add to the path variable the directory of the bin folder of MinGW. Ex: C:\Program Files\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\bin 2- Check that your Mingw-w64 tools are correctly installed and available, open a new Command Prompt and type: g++ --version OR gdb --version 3- Create helloworld.cpp: #inclu...
63,386,137
63,386,307
C++ Argument of type "const wchar_t" * incompatible with parameter of type "wchar_t"
Сan't call "GetProcessByExeName" DWORD GetProcessByExeName(wchar_t* ExeName) { PROCESSENTRY32W pe32; pe32.dwSize = sizeof(PROCESSENTRY32W); HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPALL, NULL); if (hProcessSnap == INVALID_HANDLE_VALUE) { MessageBoxW(NULL, L"Error CreateToolhelp32Snapshot", L"error"...
You are attempting to pass a wide character string literal which is not modifiable and should be a const wchar_t* to a function that is declared to take a wchar_t* which is not a const. Since you don't want to modify the string in your function you should change the signature of your function from DWORD GetProcessByExe...
63,386,189
63,386,263
What's the difference between a compiler's `-O0` option and `-Og` option?
When I want to do debugging of C or C++ programs, I've been taught to use -O0 to turn optimization OFF, and -ggdb to insert symbols into the executable which are optimized for using the GNU gdb debugger, which I use (or, you can use -glldb for LLVM/clang's lldb debugger, or just -g for general debugging symbols, but th...
@kaylum just provided some great insight in their comment under my question! And the key part I really care about the most is this: [-Og] is a better choice than -O0 for producing debuggable code because some compiler passes that collect debug information are disabled at -O0. https://gcc.gnu.org/onlinedocs/gcc/Optimi...
63,386,706
63,394,360
How to reverse an Adjacency list?
Let's say my adjacency list is as follows: 0 : 1 1 : 0 it's reverse should be empty because there is two arcs in the initial list: 0: 1: or 0 : 1 1 : becomes 0 : 1 : 0 another example: 0 : 1 : becomes 0 : 1 1 : 0 last example 0 : 1, 4 1 : 0, 4 2 : 0, 1, 3, 4 3 : 4 : 3, 1 becomes 0 : 2, 3 1 : 2, 3 2 : 3 : 0...
Just invert the adjacency matrix. Wherever you have a 0, replace it with a 1, and vice versa. Only exclude the diagonal, always put a 0 there.
63,387,535
63,387,633
Understanding nested array c++ in image scanning context
I came across this sample code on openCV library. What does the line p[j] = table[p[j]] do? I have come across multi dimensional arrays but not something like this before. Mat& ScanImageAndReduceC(Mat& I, const uchar* const table) { // accept only char type matrices CV_Assert(I.depth() == CV_8U); int channe...
It is doing color replacement by using a table where each pixel intensity maps to some other value. Commonly used for techniques like color grading, histogram adjustment, or even thresholding. Here, the table contains unsigned char values and is being indexed by the value of the pixel. The pixel's intensity p[i] is u...
63,387,740
63,392,695
Writing a function to check if a word is valid
I'm working on a binary search tree that reads from a text file, changes word to lowercase, removes punctuation and checks if word if valid then stores into the binary search tree. Here I've created a function called isValidWord() that checks if the word is lowercase, contains any digits, and contains any punctuation. ...
This question cries for the usage of a std::regex. The whole "isValidWord" function can be replaced by by a very simple one-liner: if (std::regex_match(word, std::regex("[a-z]+"))) { In the brackets, you can specify all valid characters. For example [a-z] means, all lowercase characters. Also your lines for (int i...
63,387,747
63,387,763
How to test if a string character equals a character
I'm allowing the user to insert a string time that contains a time. An example of the format would be 08:10:45AM. I'm testing if the 8th character is either "A" or "P". Here is my code: #include <iostream> #include <sstream> using namespace std; int main() { string time; cin >> time; if (time[8] == "A") ...
If you want to compare characters, compare characters: if (time[8] == 'A') Remember that in C++ 'A' is a character and "A" is a C string.
63,387,950
63,388,024
gcc error when trying to use Windows Midi API
The problem is simple I'm trying to use the Windows API for Midi but gcc can't find the references for the Functions. I'm using MinGW and gcc version 9.2.0. The only solution to a similar problem i found was adding winmm.lib but that as well didn't help. c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld....
As @dxiv notes, you need to link the winmm library. GCC does not understand MSVC's #pragma, so it does not know it is needed. Therefore, linking fails when it does not find the functions. See questions like How to specify libraries paths in gcc? to learn how.
63,388,369
63,388,647
In C++ block scope, is re-using stack memory the area of optimization?
I tested the following codes: void f1() { int x = 1; cout << "f1 : " << &x << endl; } void f2() { int x = 2; cout << "f2 : " << &x << endl; } void f3() { { int x = 3; cout << "f3_1: " << &x << endl; } { int x = 4; cout << "f3_2: " << &x << endl; } } int main() { f1(); f2(); f3...
A debug build is usually very unoptimized on purpose. It might be that each variable, regardless of scope, is given its own spot on the stack so that when your code crashes it can show you the state of each one. This wouldn't be possible if they all shared an address.
63,389,123
63,389,460
How to insert substring into main string in perticular index in CPP?
I want to insert the substring into the main string after sorting the main string. How can I do that?? Like, ilovecoding after sorting cdegiilnoov. And after that let say substring eco, it should be inserted as decogiilnov. #include <bits/stdc++.h> using namespace std; int main(){ int tc; string s,a; cin>>tc; while(...
I'm not sure if this is desired output or not, but you can check this function(include string header): string process(string& main,string& sub){ for (int i = 0; i < sub.size() ; i++){ size_t pos = main.find(sub[i]); main.erase(pos,1); } main.insert(1,sub); return main; } and check here: Why should I no...
63,389,162
63,389,296
Comparing 2 vectors using relational operators
I tried comparing 2 vectors using relational operators. vector<int>v1 {1, 2, 3}; vector<int>v2 {3, 40, 4}; cout<<(v1<v2)<<endl; // Prints 1 cout<<(v1>v2)<<endl; // Prints 0 What I am not sure of is on what basis is the comparison happening? It seems that it is comparing element by element. But I can't find any ...
What I am not sure of is on what basis is the comparison happening? The C++ reference says: template< class T, class Alloc > bool operator<( const std::vector<T,Alloc>& lhs, const std::vector<T,Alloc>& rhs ); Compares the contents of lhs and rhs lexicographically. Lexicographic order could be rough...
63,389,608
63,389,680
Alternative to realloc() in C++?
In C, we can simply use realloc() to increase/decrease the size of memory a pointer is pointing to. Is there an equivalent reallocation operator/function in C++ in the context of having used "new" to initially allocate the memory?
No, there is no renew call :-) And, to be honest, with all the rich (and auto-sizing) data structures provided by C++, there's little need for it. For example, while C strings might need to be resized to add more text, std::string just takes care of it for you. As does std::vector for other arrays, and so on. If you re...
63,389,788
63,391,348
Why is this not valid, but works locally? — The king's race problem in codeforces
Could someone help a new c++ learner? I'm trying to solve the king's race probem at https://codeforces.com/contest/1075/problem/A Definition of the problem: White king sits at point (1,1) and black king sits at point defined by first input, so (n,n). The first input also defines the board size. The next two inputs defi...
You use std::labs() which uses long integers. A long integer is most probably 32 bits on the target system. This means that your 64 bit long long variables will not get the correct result for big values. The easy fix to get the correct result is to use std::llabs(). You may also want to consider using types with fixed ...
63,389,916
63,389,993
Using delete[] on an array passed as an argument
So let's say that you wanted to make a realloc function in C++. I imagine it can work something like this: template<typename T> void realloc(T** arr, int size, int original_size){ T *newArr = new T[size]; for(int i = 0; i<original_size;i++) newArr[i] = (*arr)[i]; delete[] *arr; *arr = newArr; } Now my ques...
Now my question is wheter it is correct to use delete[] here? Yes, as long as *arr was allocated using new[]. From what I know allocated memory size is tracked at runtime so C++ knows how much to delete. Is that preserved when passing it like this [...]? I'm not really sure what you mean here. The runtime keeps tra...
63,390,165
63,396,315
GCC can not resolve method call with defaulted parameter and following parameter pack
Is GCC allowed to reject the following code due to ambiguity? To me it looks like a bug. It compiles fine with msvc, clang and icc. See here: https://godbolt.org/z/9fsnhx #include <iostream> class A { public: template<typename T> void Foo(int={}){ std::cout << "A"; } template< typename...
I think this is a gcc bug. As Oliv notes in the comments, if you provide an argument for the defaulted parameter, gcc accepts - but this should be irrelevant in this case. The relevant rules to point out here are [temp.deduct.partial], paragraph 3: The types used to determine the ordering depend on the context in whic...
63,390,271
63,390,357
Can I make a reference member no space taken?
Is there any way I can make reference members take no space? For example: #include <iostream> #include <glm/glm.hpp> struct MyClass : public glm::vec3{ float& rx = x; float& ry = y; float& rz = z; }; int main() { std::cout << sizeof(glm::vec3) << std::endl; std::cout << sizeof(MyClass) << std::endl; } the ...
Maybe this? struct MyClass : public glm::vec3{ float& rx() { return x; } float& ry() { return y; } float& rz() { return z; } }; Hard to say from your problem description if that is a possibility.
63,390,407
63,390,618
Why is it illegal to bind an r-value to a const l-value reference in special member functions?
For function parameters, it is possible to bind an r-value to an l-value const reference. However, this does not seem to apply to special member function like the copy-constructor, and copy-assignment operator in C++11 and C++14. Is there a motivation for this? When using C++17, it is possible to copy-construct, but no...
B(B{}); works since C++17 because of mandatory copy elision, the move-construction is omitted completely; the temporary object is initialized by the default constructor directly. (emphasis mine) Under the following circumstances, the compilers are required to omit the copy and move construction of class objects, even ...
63,390,851
63,391,173
What is the fastest way to check the leading characters in a char array?
I reached a bottleneck in my code, so the main issue of this question is performance. I have a hexadecimal checksum and I want to check the leading zeros of an array of chars. This is what I am doing: bool starts_with (char* cksum_hex, int n_zero) { bool flag {true}; for (int i=0; i<n_zero; ++i) flag &= (cksum_...
If you modify your function to return early bool starts_with (char* cksum_hex, int n_zero) { for (int i=0; i<n_zero; ++i) { if (cksum_hex[i] != '0') return false; } return true; } It will be faster in case of big n_zero and false result. Otherwise, maybe you can try to allocate a global array of characters...
63,391,002
63,396,564
Intersection points Point1.Y and Y should be equal. But there is a difference in Point1.Y and Y. WHY?
Suppose we have two lines. L1: y1 = m1.x1 +c1 L2: y2 = m2.x2 +c2 such that m1 != m2 intersection_X = (c2 - c1) / (m1 - m2) intersection_Y = m1 * intersection_X + c1 Also, if we calculate intersection_Y w.r.t L2 i.e. intersection_Y = m2 * intersection_X +c2 Both the intersection_Y should be equal. If you run the...
There is a finite number of double precision floating point numbers. This means there are infinitely many real numbers between two floating point numbers. There are huge gaps between floating point numbers - filled with numbers you cannot represent! When you define two lines, their intersection point is very unlikely t...
63,391,060
63,391,516
Calling base methods from member initializer list
Is it safe to call non-virtual base methods from member initializer list? And virtual?
It is not safe to call any member function (virtual or not virtual) before all base have been initialized. Bellow an example given in the standard ([class.base.init]§16): class A { public: A(int); }; class B : public A { int j; public: int f(); B() : A(f()), // undefined behavior: calls member function but...
63,391,065
63,392,132
Changing template arguments at runtime c++
I have a large and complex program that makes use of templates quite extensively. For the sake of simplicity, consider I have the following classes in my program: BronzeFork , SilverFork, GoldFork SimpleKnife , SerratedKnife, ButterKnife RedSpoon , GreenSpoon, BlueSpoon and then in main.cpp I call a function: Eating<Br...
This is not necessarily the best way to solve your problem. This is one way to generate a lot of instantiations in a compact manner. It may or may not suit your need. I assume each of your classes have some kind of ID for run-time selection, say a string. So BronzeFork::id would be "BronzeFork". I will use abbreviated ...
63,391,433
63,391,576
How to get available RAM on Windows?
I am looking for method that return available RAM and for this moment I have found only this answer https://stackoverflow.com/a/2513561/5709159 #include <windows.h> unsigned long long getTotalSystemMemory() { MEMORYSTATUSEX status; status.dwLength = sizeof(status); GlobalMemoryStatusEx(&status); return...
You can use the same call to GlobalMemoryStatusEx() and examine the .ullAvailPhys field of the MEMORYSTATUSEX structure to get the amount of available physical memory. The difference between this and the .ullTotalPhys value will be how much physical memory is in use.
63,392,144
63,392,901
When is ADL lookup is considered for unqualified dependent name?
I struggle with this example in cpp reference. I thought ordinary + ADL lookups would produce the following set in both cases: f(char) (ordinary lookup), f(int)/f(E) (ADL lookup as it takes into account visibility from the POI). Then overload resolution would select f(E) in the first case and f(int) in the other case. ...
ADL looks for function in the namespace (or class) associated to the type of the argument. So if you declare enum E in a namespace X, ADL will only look-up inside namespace X (see bellow).Fundamental types as int do not have any associated namespace. So ADL for fundamental types never find anything. void f(char); // fi...
63,392,578
63,393,164
Cannot pass shared_ptr argument to function pointer
I have a problem with the code that uses function pointer that takes shared_ptr argument. Here is a sample code. header.h #include <functional> #include <iostream> template <class T> class FuncWrapper{ private: void (*original_function)(T a); public: void setFunction(void *func); void ex...
The problem is not the shared_ptr, but mismatch between pointers to a function and a member function. Your function wrapper expects a pointer to a function (void (*)(std::shared_ptr<int>)), but you provide a pointer to a member function (void (ClassA::*)(std::shared_ptr<int>)), which is different. An implicit leading a...
63,392,584
63,392,795
Test of 8 subsequent bytes isn't translated into a single compare instruction
Motivated by this question, I compared three different functions for checking if 8 bytes pointed to by the argument are zeros (note that in the original question, characters are compared with '0', not 0): bool f1(const char *ptr) { for (int i = 0; i < 8; i++) if (ptr[i]) return false; return true; } ...
First of all, f1 stops reading at the first non-zero byte, so there are cases where it won't fault if you pass it a pointer to a shorter object near the end of a page, and the next page is unmapped. Unconditionally reading 8 bytes can fault in cases where f1 doesn't encounter UB, as @bruno points out. (Is it safe to ...
63,392,924
63,393,043
If dynamically allocated element used in templated class how can I deallocate or does it deallocate automatically?
I have this kind of templated class template<class T> class myClass { public: . myClass(const T & element); . private: T element; }; and I use dynamically allocated element as T in main struct Node { . . }; int main() { myClass<Node*> obj(new Node); } How can I free the space taken by new keyword or is...
No need to manage memory on your own. Use std::unique_ptr template<class T> class myClass { public: myClass(std::unique_ptr<T> ptr) : element(std::move(ptr)) { }; private: std::unique_ptr<T> element; }; And use it like this myClass<Node> obj(std::make_unique<Node>()); // note that I removed the *
63,392,964
63,393,071
Passing base class to function instead derived one
I have a problem with the inheritance, here's my example code: #include <iostream> struct Drawable { friend void draw( const Drawable &drawable ); private: virtual void print() const = 0; }; void draw( const Drawable &drawable ) { drawable.print(); } class Rectangle : public Drawable { virtu...
I'm not sure it is your intent but you can explicitly invoke the Rectangle specific version of print() from Square. // draw( dynamic_cast< const Rectangle & >( *this ) ); Rectangle::print(); std::cout << "Drawing square...\n"; Using the draw() function will always select the more specific version of print() (due to vi...
63,393,278
63,393,399
How come constexpr functions can not consume consteval functions while you can create constexpr objects from consteval functions?
You can have constexpr objects fron consteval but you can not consume consteval within constexpr. Why? I thought consteval should have been some kind of "narrow" constexpr. Please help me make a sense out of this design. constexpr int constexpr_sqr(int n) { return n*n; } consteval int consteval_sqr(int n) { return n*n;...
It's the argument. constexpr function aren't required to be constant evaluated. This means that n is not usable in a constant expression. I thought consteval should have been some kind of "narrow" constexpr. No, those are just functions that have to be constant evaluated. This means that their arguments must always b...
63,393,286
63,393,530
Crash due to mixing CRTP & interfaces?
I am experimenting with CRTP and mixing it with interfaces, and I cannot explain why this program crashes (in Clang, GCC and MSVC). In latest Clang and GCC it builds without warning with -Wall, -Wextra. My guess is that the virtual method call is not resolved but I cannot explain why (no crash if GetInt() is removed fr...
You're slicing n in your call to Foo2. Foo2 accepts its parameter by value. That means that a copy of n's MyNodeBase<Node<MyNodeBase>> sub-object is what gets passed to Foo2. Since n in Foo2 is not a Node<MyNodeBase>, calling GetInt through the pointer returned from the cast in CallGetInt results in your program exhi...
63,394,138
63,395,347
How can I connect a C# delegate to a boost::signal
I've try to connect in this way TextStore typedef boost::signals2::signal<VOID(TextStore*, RECT*)> signal_GetCompExt; signal_GetCompExt m_sigGetCompExt; Signal Handler delegate VOID GetCompsitionExtDelegate(TextStore* textStore, RECT* rect); VOID onGetCompsitionExt(TextStore* textStore, RECT* rect); Connect Sig...
typedef void (*GetCompExtCallback)(TextStore* ts, RECT* rect); m_TextStore->m_sigGetCompExt.connect(reinterpret_cast<GetCompExtCallback>(Marshal::GetFunctionPointerForDelegate(gcnew GetCompsitionExtDelegate(this, &AppWrapper::onGetCompsitionExt)).ToPointer()));
63,394,267
63,395,137
Arduino IC22 Display Countdown timer not transforming from double digit to one digit
So recently i started to learn C++ and Arduino. For my training i use an IC22 Display which I connected to my breadboard. I tried creating a simple countdown timer from 20 seconds all the way to 0. However I ran into a problem where the IC 22 Display would still display the number 0 everytime it the countdown goes belo...
try use lcd.clear() just before cursor setting inside your loop.
63,394,619
63,395,256
Can someone explain me this code which generates all the possible permuations of a given set?
I found a recursion code in the competitive programmer's handbook to do the same but I'm struggling to understand the logic behind it. It states that: Like subsets, permutations can be generated using recursion. The following function search goes through the permutations of the set {0,1,...,n¡1}. The function builds ...
I will try to give you some intuition . The main idea is to backtrack . You basically build a solution until you face a dead end. When you do face a dead end , go back to the last position where you can do something different than what you did the last time . Let me walk through this simulation I have drawn for n = 3 ....
63,394,625
63,394,877
Are my move constructor and move assignment operator written well?
I am adding move constructor and move assignment operator in this struct. Can someone tell me if they are written good? When I run the code without these two methods it is going ok, but when I add these two it is not working. Thanks a lot struct Data { Data() = default; Data(const unsigned int ...
Your code is correct. But there is also a pattern to implement move assignments using std::swap: Data& operator=(Data&& _d) { std::swap(data, _d.data); std::swap(s, _d.size); return *this; } Here the old data will be released when _d destructor is invoked. This is not a "more correct way" but it is easier ...
63,394,899
63,395,369
How to correctly link qt dialogs?
I need to bind the dialogs so that the "first_dialog" window opens from the mainwindow with two buttons "ok" and "close". Clicking on "close" simply closes the window. Clicking on "ok" should open "second_dialog" also with two buttons "ok" and "close". Clicking on "close" will close the "second_dialog". And if you clic...
It looks like you could make use of the accept and reject methods. In your dialogs call those functions when either of the buttons are pressed. And then just make sure you check the return value to know which one was clicked. // MainWindow.cpp void MainWindow::on_pushButton_clicked() { first_dialog* a= new first_di...
63,394,955
63,395,020
Namespace's class's friend that is not declared and defined in the namespace
Is it right to do so: void f(); namespace ns { class C { int m; friend void ::f(); }; } void f() { ns::C c; c.m = 2; } ? The code is compiled successfully in VS. But I can't find anything about qualifying a namespace for a friend declaration in the standard. Is it even legal? Can ...
Yes it's legal. A namespace is little more than a way of adding another layer of descrimination for functions, classes, &c.. Any function can be marked as a friend inside a class, even if that class is in a different namespace to the function. The function could be in a namespace too. There's no specific section in the...
63,394,965
63,395,162
Compile error with initialization of an std::shared_ptr of type std::unordered_map
I'm new to C++'s smart pointers and at some point in my code I need to have a shared pointer of an unordered_map. I realized that I can't initialize the shared_ptr in the following way: typedef std::unordered_map<std::string, std::string> JsonDict; std::shared_ptr<JsonDict> ret = std::make_shared<JsonDict>(new...
You don't allocate the object on your own, make_shared does it for you. The arguments it accepts are used to construct the object itself, not a pointer to it. So your line should read as std::shared_ptr<JsonDict> ret = std::make_shared<JsonDict>(); (Think of it as "make_shared is the new new", though it is said about ...
63,395,451
63,401,932
Why does GCC implement std::to_string using std::vsnprintf?
Recently, I looked into GCC's basic_string.h and noticed that all std::to_string overloads are implemented using std::vsnprintf like for example: inline string to_string(int __val) { return __gnu_cxx::__to_xstring<string>(&std::vsnprintf, 4 * sizeof(int), "%d", __val); } Wouldn't this introduce a lot of overhead? ...
This looked good enough considering they had lots of other stuff to implement for C++ 11. They optimized it recently with gcc 10 release.
63,395,535
63,401,081
C++ Implementation code in an interface declaration
I'm porting d2d1_1.h header file to Delphi and I'm stuck in an interface declaration. In the interface declaration, there are methods redeclared with actual implementation code which calls. Here is an example (I show only relevant part of the code): // d2d1_1.h line 1522 interface DX_DECLARE_INTERFACE("e8f7fe7a-191c-46...
Only the method marked with the PURE (defined as =0) attribute really exists in the final COM vtable. The other methods are utility methods/wrappers that contain C/C++ code that can only be used in C/C++ (they will be compiled), so you must not declare them when using another language (delphi, .NET, etc.)
63,395,569
63,396,546
Compiled libcurl and OpenSSL separately, is it the same as compiling libcurl with OpenSSL?
So, I have compiled the following: libcurl: x86/debug, x86/release, x64/debug, x64/release OpenSSL: x86/debug, x86/release, x64/debug, x64/release Now, I have setup visual studio for all those configs with both libcurl and OpenSSL included. I have seen people mention compiling libcurl with OpenSSL. Is it the same as wh...
You shouldn't need OpenSSL at all when building libcurl on Windows. libcurl by default uses Schannel (WinCNG, Windows native crypto) when built on Windows. If CURL_VERSION_SSL is reporting true then SSL support is enabled correctly.
63,395,570
63,396,332
Optimisation of the backtracking algorithm for all paths in a grid from top left to bottom right visiting each square just once
The problem statement: Calculate the number of paths in an nxn grid from the upper-left corner to the lower-right corner such that the path visits each square exactly once. For example, in a 7£7 grid, there are 111712 such paths. The algorithm and optimisation: We begin with a straightforward backtracking algorithm, an...
For every path (eg "RDDRRD") there is a mirror path where you swap D and R ("eg DRRDDR"). The text is saying that if you find all paths that start with D, you can trivially generate all paths that start with R by performing the inversion. Thus, you can simply assume the first letter is D and multiply the resulting numb...
63,395,573
63,396,775
Best practice to give access to std::array elements
I have a relatively complex project with many classes, I'll try to simplify it with a simplistic example. class item { // a class that holds useful members and methods } class user { public: user(item* i) { item_to_use = i; } void do_work() { //do some work using item_to_use } private: ...
Given that you have a storage class, I'm assuming it outlives all the users and usage classes and "owns" the items. If that's the case, you're fine to just pass a pointer to the items in the array around and shared_ptr would just add unnecessary overhead. Will you always be using a std::array? If you end up using a vec...
63,395,654
63,395,791
How to check whether an unsigned char vector contains all null characters
I need to check whether my vector contains all null characters and perform some operation based on that result. I found couple of questions in Stack overflow but they are not exactly matching my requirement. One solution that I can think of to decide a vector with all null characters is: if(Buffer[0] == '\0') { std::c...
You can use std::all_of() algorithm to check if all of the elements meets a condition. I hope you see std::any_of() and std::none_of() also. int BufferSize = 30; vector<unsigned char> Buffer(BufferSize, 0); bool is_clear = std::all_of(Buffer.cbegin(), Buffer.cend(), [](unsigned char c) {return c == 0; }); For the case...
63,395,714
63,396,124
Error when initialazing struct member array
I have this struct: template<int N> struct XYarr { double x[N],y[N]; int size() {return N;} }; When I try to intialize it (and return it by a function) return XYarr<size>{x2, y2}; //x2 and y2 are arrays double[size] I get the following error: cannot initialize an array element of type 'double' with an lvalu...
Compiler can't use member aggregate initialization because C-arrays can't be copied. To overcome this, provide a constructor for your struct: template<int N> struct XYarr { XYarr() = default; // default constructor if needed XYarr(const double (&x_)[N], const double (&y_)[N]) { memcpy(&x,x_,sizeof (doub...
63,396,032
63,396,229
How to calculate evenly distributed number of jobs for fixed number of threads?
Let's presume I have tasks number of tasks and threads number of threads to run them. Each thread can run only once, so I want to distribute those tasks evenly through existing threads. To calculate number of tasks per thread I wrote this simple app: #include <iostream> using namespace std; int main(){ int tasks =...
To calculate the number of tasks per thread in advance, you can use this formula: int tasks = 10; int threads = 3; for (int i = 0; i < threads; ++i) { int tasks_for_this_thread = tasks / threads + (i < tasks % threads); // do whatever you want to } For example, for 10 tasks and 3 threads, it distributes the ...
63,396,197
63,403,644
How can I use a structured binding to copy a tuple-like object with elements whose type is T&?
The origin of this problem is that I'm designing a 2-dimensional container implemented by std::vector. The result type of operator[] is a proxy class that has a fixed number of elements, and then I want to use structured binding with this proxy class, just like std::array. This is a simple example for it: template<size...
This is a very old C++ wart dressed in new clothes: std::vector<bool> x; auto& rx = x[0]; // does not compile Proxies are second class citizens. It is incompatible to return by value from operator[] and bind it using structured bindings with auto&. There are no solutions without trade-offs. To get the auto& bindings t...
63,396,784
63,396,850
How can I implement a function take as some optional parameters in C++?
I have a function that takes 3 determined parameters and one additional parameter. In Matlab, I can use nargin < 4 to distinguish the case with the addtional parameter and that without the addtional parameter. How can I implement a function in C++ imitating this behavior? I found parameter pack / variadic parameter may...
You can use std::optional. In the function declaration, assign the default value of std::nullopt to your optional argument. This is a special value designed to indicate that std::optional doesn't contain any value. Thus, you'll be able to call your function with 3 or 4 parameters. void function(int a, int b, int c, std...
63,397,077
63,397,448
How do I end up with a negative value in this chain of transformations?
I am displaying pressure values in the range of 0 - 5, with two decimal places. However recently I got a negative value -0.05 shown. Can someone explain how this tranformation chain can end up with a negative value? The only idea I have right now is an unreasonably high input value, but maybe I am not seeing something....
The conversion from double type to unsigned is undefined, when unsigned can't "represent" the value of double, for example the double value is negative. From cppreference implicit conversion emphasis mine: A prvalue of floating-point type can be converted to a prvalue of any integer type. The fractional part is trunca...
63,397,661
63,398,702
GCC doesn't like to make friends with anonymous namespace forward declarations, but MSVC does. What?
This code compiles on MSVC but not on GCC, when testing on GodBolt.org The Baz class is declared in the anonymous namespace, which makes GCC think it's a different class than what I then define below, but MSVC seems to connect them. namespace { class Baz; } class Foo { protected: int x; }; class Bar : public Foo { fri...
The problem is that you are using an elaborated type specifier for the friendship declaration and GCC use it to declares a class Baz in the global namespace. An elaborated type specifier is a declaration unless a previous declaration is found in the inner most enclosing namespace. Apparently it is not clear if the decl...
63,397,817
63,397,938
what is the Time complexity of this function
How to calculate time complexity of this function step by step ? This function converts an adjacency list to a matrix, manipulate the matrix and then convert the matrix back to a list Graphe *Graphe::grapheInverse( void ){ Graphe *r = new Graphe (_adjacences.size() ); std::vector<vector<int> > matrix(...
Note that the following all applies to big-O time complexity: Calculating the time complexity involves looking at how many times you iterate over the data. One for loop is N, as you touch each point once. A nested for loop (for i in data, for j in data) is N^2 because you touch each point once for each point there is....
63,397,902
63,445,079
QT live camera showing crashes due to out of memory
I am using QT Qpixmap to show the image captured from the camera using the OpenCV frame. I am doing following steps Capture image using OpenCV Convert the OpenCV image to QImage Convert QImage to Qpixmap Show it on Qlabel The problem I am facing is the memory start increasing at great speed and after few time the app...
After trying many things here is the conclusion and code is now working perfectly fine I removed the tic toc part time(&start); timer = double(getTickCount()); tic(); It was working but crashing then just to make sure that QImage is not NULL I removed the img = QImage(); // releasing memory with if(!img.isNull()) ...
63,398,208
63,398,437
boost::asio::read_until does not accept a socket as an argument
I've read that you can use boost::asio::read_until to read from a socket, so I tried to do that: using namespace boost::asio; ... boost::array<char, BUFFER_SIZE> buf; read_until(this->socket_opt.value(), buffer(buf), "\n"); But apparently, read_until cannot accept those arguments: error: no matching function...
boost::asio::read_until() requires dynamic buffer as second parameter. I hope the following code helps you. boost::asio::streambuf buf; boost::asio::read_until(this->socket_opt.value(), buf, "\n");
63,398,291
63,398,366
Can I make std::pair of two std::ostream-s?
I'd like to make a pair containing two std::ostream object. I need this so that I can pass a single object to various functions instead of two std::ostream objects. I was hoping I could do this: #include <iostream> #include <ostream> using namespace std; int main(){ std::ostream output( std::cout.rdbuf()); s...
The problem that you’re having is that ostream can’t be copied. The solution is to use a pair of references: using Logger = std::pair<std::ostream &, std::ostream &>; Logger logger { output, error };
63,398,434
63,399,187
Access pybind11 kwargs in C++
I have the following kwargs in python: interface_dict = {'type':['linear'], 'scope':['ascendant'], height:[-0.4272,0.4272], length:[27.19], 'flag':[True]} interface.py_interface(**interface_dict) I'm using pybind11 in C++ to access these python values. I'm trying to store these values in a variant multimap like this: ...
You can use py::sequence to access items by indices. Just be sure element exist under the given index: std::multimap<std::string, std::variant<float, bool, int, std::string>> kwargs = { {"type", (*(kwarg["type"]).begin()).cast<std::string>()}, {"scope", (*(kwarg["scope"]).begin()).cast<std::string>(...
63,398,451
63,400,437
How to remove something from a custom vector? C++
I am currently making a vector class in C++ and am just trying some stuff out. I am not sure if this can be done without causing a memory leak or leaving memory behind and not deleting it properly. I have commented the lines of code that I have questions for. Any help will be appreciated, thank you in advance! void rem...
Instead of realocating I changed it to do this and it works better and is better optimised. void remove(unsigned int toRemove) { unsigned int x = 0; for (unsigned int i = 0; i < size; i++) { if (i != toRemove) { array[x] = array[i]; // shifts the elements backwards } ...
63,398,580
65,948,711
reading arrays of json objects with nlohmann c++ library
I am ok using this syntax with the nlohmann library { "key1": {"subKey1": "value11", "subKey2": "value12"}, "key2": {"subKey1": "value21", "subKey2": "value22"} } But I have a new file, which is valid json too (I checked) and is written this way, it is made of a single array of repetitive objec...
You can try this: std::string ss= R"( { "test-data": [ { "name": "tom", "age": 11 }, { "name": "jane", "age": 12 } ] } )"; json myjson = json::parse(ss); auto &students = myjson["test-data"]; for(auto &student : students) { ...
63,398,905
63,407,531
Shadowmap blank with GL_LESS but not with GL_GREATER or GL_ALWAYS?
I've been working on shadowmapping for a few days now in my custom OpenGL engine. After reading a few guides, I've tried to stick to the basic method as closely as possible: create a shadowmap framebuffer with a GL_TEXTURE_2D for the shadowmap itself, render from the light's perspective using the framebuffer and a basi...
My guess is that you forgot to clear your depth buffer. You need to fill it with the maximum depth at the beginning of each of your frame glClearDepth(1.0); glClear(GL_DEPTH_BUFFER_BIT); it's very important to set it to 1.0 instead of 0.0 or nothing will be drawn
63,399,302
63,399,445
Create an array of a Class based on string
I have created a class called "letter": class Letter { char letter{}; bool guessed{ false }; public: void setLetter(std::string); }; and I would like to create an array of class "Letter". The size of the array should be the size of a user inputted string, and if possible, each letter of the string...
In modern C++, the tool you should first look to when thinking of a dynamic array is std::vector. Here, you would use a std::vector<Letter>. In this case you could write std::vector<Letter> test(word.length()); to make container that holds word.length() default constructed instances of the class Letter. std::vector beh...
63,399,521
63,400,124
Comparing two input files using only "char" in c++
I am looking for some help with an assignment question or more just a nudge in the right direction. We aren't allowed to use strings. We do need to use eof. Question: Two data files are required to evaluate a multiple-choice examination. The first file (booklet.dat) contains the correct answers. The total number of que...
This is one method to accomplish your goal, there are many others. const unsigned int MAX_ANSWERS = 50U; char answer_key[MAX_ANSWERS] = {0}; // Read in the answer key. std::ifstream answer_file("booklet.dat"); answer_file.read(&answer_key[0], MAX_ANSWERS); // Process the students answers char student_answers[MAX_ANS...
63,399,626
63,399,944
How can I call a derived class's method from a function expecting the a base class pointer?
It has been a very long time since I did a lot of C++ coding and I have forgotten much. Can comeone help to point me in the correct direction? Assume I have a the following classes: class A { // Normal Class Stuff bool doSomething( void); } bool A::doSomething( void) { return( true); } class B : private A { /...
The dtor() and the function of base class must be marked virtual. I changed class A's access keyword to public so that it can be called from class foo. class A { public: virtual bool doSomething(void); virtual ~A() noexcept; } and it is recommend that class B overriding its parent function to append override keywo...
63,399,695
63,399,730
Problem with C++ standard container not inserting new values
#include <iostream> #include<bits/stdc++.h> using namespace std; int main() { unordered_map<string,set<int>> map; set<int> s; s.insert(1); s.insert(2);s.insert(3); map.insert(make_pair("Screen1",s)); for(auto it : map) { cout<<it.first<<endl; it.second.insert(5); } f...
In this loop: for(auto it : map) the variable it is a copy of every element in map, so modifying it doesn't modify map. If you want to modify the elements, you need to do: for(auto &it : map) so that it is a reference to every element in map.
63,399,816
63,399,956
How to make a for loop variable const with the exception of the increment statement?
Consider a standard for loop: for (int i = 0; i < 10; ++i) { // do something with i } I want to prevent the variable i from being modified in the body of the for loop. However, I cannot declare i as const as this makes the increment statement invalid. Is there a way to make i a const variable outside of the increm...
From c++20, you can use ranges::views::iota like this: for (int const i : std::views::iota(0, 10)) { std::cout << i << " "; // ok i = 42; // error } Here's a demo. From c++11, you can also use the following technique, which uses an IIILE (immediately invoked inline lambda expression): int x = 0...
63,399,980
63,400,709
C++ undefined reference in Makefile
I created my Makefile for a simple program but it returns undefined reference for class functions constantly: g++ -c src/main.cpp -o lib/main.o g++ -c src/functions.cpp -o lib/functions.o g++ -c src/Circular.cpp -o lib/Circular.o g++ lib/main.o -o bin/app.exe c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bi...
I managed to create a Makefile from this source . The Makefile looks like this: CXX = g++ CXXFLAGS = -std=c++17 -Wall LXXFLAGS = -std=c++17 OBJECTS = main.o Circular.o functions.o TARGET = main $(TARGET): $(OBJECTS) $(CXX) $(LXXFLAG) $(OBJECTS) -o $(TARGET) main.o: main.cpp Circular.cpp Circular.h functions.cpp fu...
63,400,074
63,401,293
Cannot delete object pointed by stack.top() in template class
I have template class used for state machine, which is partial declared for the pointer type objects. In this class there is attribute: std::stack<T*> s; and there is a method used to pop top state: void SM<T*>::pop() { delete s.top(); s.pop(); } There is no error during compilation process, but when this met...
Any idea why? Most likely reason is that s.top() doesn't point to an object whose lifetime hasn't ended, and which was created using non-array allocating new . To avoid this problem, it is a good idea to avoid owning bare pointers.
63,400,120
63,405,039
How do I check the type of widget in GTK+3.0?
I saw this post but it was for Python so that doesn't help me too much. I'm programming in C++, working on a code-base that I didn't write. I see some checks like GTK_IS_ENTRY and GTK_IS_COMBO_BOX, but I'm not sure where this person found these or what other GTK_IS_... there are. Is there a reference to these somewhere...
The type checks macros are typically part of the API contract for a GObject, and they are conventionally provided by the library, so they don't end up in the documentation. All they do is call G_TYPE_CHECK_INSTANCE_TYPE with the given GType macro, like GTK_TYPE_ENTRY or GTK_TYPE_COMBO_BOX.
63,400,265
63,400,820
Assign char address to an int pointer, and consequently write an int-size piece of memory
from the book Stroustrup - Programming: Principles and practices using C++. In §17.3, about Memory, addresses and pointers, it is supposed to be allowed to assign a char* to int*: char ch1 = 'a'; char ch2 = 'b'; char ch3 = 'c'; char ch4 = 'd'; int* pi = &ch3; // point to ch3, a char-size piece of memory *pi = 12345; ...
char ch3 = 'c'; int* pi = &ch3; it is supposed to be allowed to assign a char* to int*: Not quite - there is an alignment concern. It is undefined behavior (UB) when If the resulting pointer is not correctly aligned for the referenced type, the behavior is undefined. C17dr § 6.3.2.3 7 Example: Some processor req...
63,400,475
63,405,844
'using' before a variable inside a namespace
I understand usingdirective can be used to refer to a namespace. Could anyone please tell what it means when it is used in front of a variable G4NtupleIterator or a class name G4AnalysisManager as in the following example? namespace G4Csv { using G4NtupleIterator = std::vector<tools::wcsv::ntuple*>::iterator; usi...
The using directive introduces a symbol into the current scope. If that scope includes a namespace, then it will be part of that namespace but not others, including the global namespace. In your example you could refer to G4Csv::G4NtupleIterator or G4Csv::G4AnalysisManager.
63,400,689
63,401,119
Checking if a character occurs at least N times in the string. Any solution in algorithms?
This question is not hard in terms of getting solution, but I would like to know if any C++ function or algorithm is available to solve it. I got this thought while going through this question Count character occurrences in a string in C++ So would like to know if we have any option other than writing a function from s...
You can use for example std::find_if. Here you are #include <iostream> #include <string> #include <iterator> #include <algorithm> int main() { std::string s = "a_b_c_d_e_f_g_h_i_j_k_l_m"; std::string::size_type n = 0; auto it = std::find_if( std::begin( s ), std::end( s ), ...
63,401,194
63,401,278
std::cin only runs once in while loop?
I'm sorry if this question is stupid, but it's been kind of bugging me. I have written a program that is supposed to accept user input 5 times and then print out the result each time (i am using a while loop.) Here is the code I wrote: #include <iostream> int main() { int x = 1; int number; while (x <= 5)...
You are trying to read an integer and "jakdfjaksdfjk" would be a string, that's why that happens. Type something like 1 4 8 35 42 and it'll work as you expect
63,401,452
63,401,539
Key already exists in unordered_map, but "find" returns as not found
I constructed an unordered_map using key type rot3d, which is defined below: #ifndef EPS6 #define EPS6 1.0e-6 #endif struct rot3d { double agl[3]; // alpha, beta, gamma in ascending order bool operator==(const rot3d &other) const { // printf("== used\n"); return abs(agl[0]-other.agl[0]) <= ...
Hash-based equivalence comparisons are allowed to have false positives, which are resolved by calling operator==. Hash-based equivalence comparisons are not allowed to have false negatives, but yours does. Your two "not 100% the same" keys have different hash values, so the element is not even found as a candidate for...
63,401,515
63,401,556
C++ Assign value of class member from a different function
Let's say I have a class: class Test { public: int x = 1; }; and within main I create an object of said class and call a function called setInt: int main() { Test example; setInt(example); std::cout << example; } void setInt(Test example) { (// random if statement) exampl...
You're just copying the integer and then assigning a new value but not manipulating with the original values. If you could've written: void setInt(Test& example) { // Now you are changing the original value here example.x = 5; } It could then work. There's an alternative of reference-to operator, that's called...
63,401,636
63,402,377
Efficient algorithm to produce closest triplet from 3 arrays?
I need to implement an algorithm in C++ that, when given three arrays of unequal sizes, produces triplets a,b,c (one element contributed by each array) such that max(a,b,c) - min(a,b,c) is minimized. The algorithm should produce a list of these triplets, in order of size of max(a,b,c)-min(a,b,c). The arrays are sorted....
OK, you're going to need to be clever in a few ways to make this run well. The first thing that you need is a priority queue, which is usually implemented with a heap. With that, the algorithm in pseudocode is: Make a priority queue for possible triples in order of max - min, then how close median is to their average....