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
69,402,542
69,402,573
Using #define for text replacement in the code
Apparently, I can set #define LIMIT 50 to say that LIMIT, wherever it occurs in the code, is replaced by 50. Is it possible to use #define ui "unsigned int" to define my variables in such a way? ui foo = 42 ui bar = 99
Using the preprocessor for replacement is not recommended and can lead to unexpected problems. For your use-case there is the typedef or using statement: Use: using ui = unsigned int; Or: typedef unsigned int ui;
69,403,464
69,403,797
C++ Qt : push_back doesn't work correctly
I'm trying to write a code which reads .stl files, and gathers the informations in an std::vector<Triangle*>triangles. When I'm using push_back, it erases all the previous values in triangles and replaces all of them by the last value I'm trying to push_back. Here is my code : Mesh.h: struct Triangle { Node* nodes[...
The problem is that you create the triangle once and keep pushing the pointer to that triangle into the vector. Meaning any change to the pointer will affect all items in the vector (because they all point to the same instance). You should move the construction of the triangle in the while loop (Triangle *triangle = ne...
69,403,564
69,406,769
Unable to create image bitmap c++
My goal is to analyse image by pixels (to determine color). I want to create bitmap in C++ from image path: string path = currImg.path; cout << path << " " << endl; Then I do some type changes which needed because Bitmap constructor does not accept simple string type: wstring path_wstr = wstring(path.begin(), path.end...
Either Gdiplus::GdiplusStartup is not called, and the function fails. Or filename doesn't exist and the function fails. Either way img is NULL. Wrong filename is likely in above code, because of the wrong UTF16 conversion. Raw string to wstring copy can work only if the source is ASCII. This is very likely to fail on n...
69,403,575
69,403,889
Why can't we use square brackets in the code below?
vector<int> mergeKSortedArrays(vector<vector<int>*> input) { vector<int> ans; //min priority queue priority_queue<int, vector<int>, greater<int>> pq; for(int i = 0; i < input.size(); i++){ for(int j = 0; j < input[i] -> size(); j++){ pq.push(input[i][j]); //THIS LINE ...
With this declaration: vector<vector<int>*> input; input is not a vector of int vectors but it's a vector of pointers to int vectors. Therefore you need this: (*input[i])[j] input[i] is a pointer to vector<int> *input[i] is a vector<int> (*input[i])[j] is an int This being said, you should not use pointers in the fi...
69,403,853
69,448,204
Using C++14 with AVR-GCC (Arduino Uno)
I'm trying try get my Arduino code to compile with -std=c++14 instead of the default -std=gnu++11. To this end, I added to my platformio.ini: build_flags = -std=c++14 build_unflags = -std=gnu++11 However, when I then try to compile, I get the following linker errors: <artificial>:(.text+0x20a4): undefined reference to...
After some searching around it turns out that C++ from C++14 on defines two additional delete operators: void operator delete ( void* ptr, std::size_t sz ) noexcept; (5) (since C++14) void operator delete[]( void* ptr, std::size_t sz ) noexcept; (6) (since C++14) 5-6) Called instead of (1-2) if a user-defin...
69,403,895
69,403,930
Calling template function inside function C++
I have similar case but more complex. I am trying to call a template function inside a normal function but I can't compile... #include <iostream> using namespace std; template<class T> void ioo(T& x) { std::cout << x << "\n"; } template<class T, class ReadFunc> void f(T&& param, ReadFunc func) { func(param); } ...
ioo is a function template, not a function, so you can't take its address. This would however work since it instantiates the function void ioo<int>(int&): f(x, &ioo<decltype(x)>); and as noted by Jarod42 in the comments, you could make it into a lambda: f(x, [](auto& arg){ioo(arg);});
69,403,902
69,405,220
Print only at the end of all the input c++
I want to add values to a binary search tree taking input from user until -1 is encountered. It must then continue to read numbers and delete from the tree until I encounter a -1 again. After taking both inputs it should print the pre-order, in-order and post-order traversals after each number was removed. My code belo...
Yes, your code writes the traversals after it reads each number to be deleted. I gather you want the writing to be done after all the reading is done. As commenters say, there's two ways. Either you can buffer the input, or you can buffer the output. The input buffer is a bit simpler, so I'll demonstrate that way. The ...
69,404,038
69,404,585
Does .NET initialize struct padding to zero?
When .NET initializes a struct to zero, does it zero out the padding as well? I ask because I'm wondering about the limitations of doing bitwise comparisons on unmanaged structs. Note how CanCompareBits not only checks that the type is unmanaged (!mt->ContainsPointers()), but also that it is tightly packed (!mt=>IsNotT...
Struct padding is explicitly documented as being indeterminant. From https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/unsafe-code: For alignment purposes, there may be unnamed padding at the beginning of a struct, within a struct, and at the end of the struct. The contents of t...
69,404,394
69,404,524
C++ weird instantiation of struct
I have a struct in a header file as shown here struct GraphNode { Id id {}; std::string name {}; long long int passengerCount {0}; std::vector<std::shared_ptr<GraphEdge>> edges {}; // Find the edge for a specific line route. std::vector< std::shared_ptr<Graph...
is FindEdgeForRoute a vector of shared pointers to type GraphEdge, but instead of a normal vector it's an iterator? What you see in the struct definition is that it declares a const member function called FindEdgeForRoute that takes one parameter (a const std::shared_ptr<RouteInternal>&) and returns a const_iterator ...
69,405,207
69,405,435
I'm having doubts about how C++ is handling an array
I was messing around just trying to understand how c++ works, when I got "crashed" by the int arrayF[0]; on line 6, and int arrayF[input]; on line 21. In the computer memory the first version of this arrayF shouldn't be overwrote by the one on line 21? I know that int arrayF[input]; is in another scope, but still do wh...
int arrayF[0]; This program is ill-formed. The size of an array variable must not be zero. if(i == n) return arrayF[n]; Even if we pretend that empty array variables were allowed, then all indices to such array would be outside the bounds of the array. Regardless of what the value of n is, this would read outside...
69,405,208
69,411,585
Compiler error c2237 when working with modules
I am trying to change a project to use modules in visual studio. I have changed a simple class to generate a module as follows: #pragma once export module FieldData; namespace Serializer { class FieldData { public: bool nvConverted{ false }; }; } I've also changed the item type to 'c/c++ comp...
I figured it out. The problem was that I hadn't changed the 'Compile as' option in the project properties -> Configuration properties -> C/C++ -> Advanced. The value it needs to be is: 'Compile as C++ Module Code (/interface )'
69,405,241
69,405,441
Why can't we use square brackets in case of dynamic vectors?
#include <iostream> using namespace std; #include <vector> #include <queue> int main(){ vector<int> *v = new vector<int>; v -> push_back(1); //min priority queue priority_queue<int, vector<int>, greater<int>> pq; pq.push(v[0]); //Able to do pq.push(v -> at(0)) } So why is this giving an erro...
A std vector already manages its buffer dynamically. In 99.9% of cases, new std::vector is a mistake. vector<int> v; v.push_back(1); //min priority queue priority_queue<int, vector<int>, greater<int>> pq; pq.push(v[0]); this works. If you are really in the 0.1% of cases where new on a vector makes sense, change v[0...
69,405,274
69,405,318
Using copy algorithm to copy from vector to set
As a purely learning experience I want to be able to use the copy algorithm to copy from a vector to a set. This is what I am trying to do: vector<int> myVector = {0, 1, 1, 2, 2, 3, 3, 4, 5, 6}; // set<int> mySet(myVector.begin(), myVector.end()); // This works, no issues set<int> mySet; copy(myVector.begin(...
You need to use std::inserter in this way, indicating the insertion position as second argument: copy(myVector.begin(), myVector.end(), inserter(mySet, mySet.end()));
69,405,805
69,405,878
Why does a rising integer with no influence crash my program
This is my code and it works as expected. But after adding a rising integer (even though it has no influence on the code) my code doesn't work as expected #include <iostream> int i; int j = 0; int nums[] = {}; int co = 0; void rq1() //rq = request { std::cout << ("How many numbers?"); std::cin >> i; } void ...
int nums[] = {}; This array variable has no elements. This isn't allowed in C++. The program is ill-formed. std::cin >> nums[n2]; Here you access the empty array outside of its bounds. The behaviour of the program is undefined. I don't know why my outputs changes. It's because the behaviour of the program is un...
69,406,084
69,406,401
Is it possible to use a custom allocator to allocate an arbitrary sized area?
I have a container class that manages the underlying memory in different chunks. The number of chunks varies with the number of objects stored in the container. I allocate a new chunk of memory whenever the container is about to exceed the currently available memory. And also, deallocate a chunk whenever it is no longe...
what is the proper way of allocating/deallocating the space for storing the chunk pointers? Any correct way of allocating memory is a proper way. Each have their benefits and drawbacks. You should choose based on which benefits and drawbacks are important to your use case. You could use static storage if you wish to ...
69,406,591
69,407,318
How to edit some parts of text files c++? (Mac OS)
Lets say I have a .txt file that says: Date: 01:10:21 Hi My name is Jack and I want to change My name is Jack to My name is John! but instead of change everything like: file.open("yourname.txt", ios::out); if (file.is_open()) { file << "Date: 01:10:21 \nHi \nMy name is John"; file.close(); } I want to edit only t...
Can't say I know a proper C++ way, but there is a C way using <cstdio>. Here is a snippet how this is achieved, however you need to implement your own logic for the problem, like finding where and how much to replace, ex. use indexes or string buffer to hold your needed data. Here is a minimum snippet: #include <cstdio...
69,406,741
69,407,018
Ordering in unordered_map in C++
So I have an array as : arr[] = {5, 2,4,2,3,5,1}; How can I insert them in this order with the number of times they occur in unordered_map? #include<bits/stdc++.h> using namespace std; void three_freq(int arr[], int n){ unordered_map<int, int> m; for(int i=0;i<n;i++){ m[arr[i]]++; } for(aut...
If you don't care about efficiency (that much), then you can just change the for loop which is printing the output. for(int i=0; m.size(); i++) { auto it = m.find(arr[i]); if (it != m.end()) { cout<<arr[i]<<":"<<it->second<<"\n"; m.erase(it); } }
69,406,779
69,407,511
c++ Increase pointer size without return new pointer
My teacher has me complete this(the main is hidden) and i wonder why i got an infinite loop with this solution. Task: Complete this function: void pad_left(char *a, int n) { } // if length of a greater than n, do nothing // else insert '_' util a 's length is n Some case i got an segmentfault I try realloc but it ret...
Okay, you need some background information. void pad_left(char *a, int n) { } char a[5] = "test"; pad_left(a, 10); This is going to be a significant problem. First, you can't realloc for two reasons. First, char a[5] is a fixed array -- not an allocated array. When you pass it to pad_left, that doesn't change. realloc...
69,407,691
69,440,791
Does substitution failure block special member function generation?
I am trying to understand at a non-superficial level why the following code does not compile: #include <vector> template<typename T> struct wrapper { T wrapped_value; wrapper() {} template<typename... Args> wrapper(Args&&... args) : wrapped_value( std::forward<Args>(args)... ) { } }; struct A {...
Substitution is not failing and special function generation is not being blocked. Template substitution leads to a constructor that is a better match than the compiler-generated copy constructor so it is selected which causes a syntax error. Let's simplify the problem illustrated in the question by getting rid of usage...
69,407,692
69,408,051
What may be the reason for this constructor failing to initialize with the given values?
I have been trying to solve an example question from a book and I encountered this problem while initializing the constructor with the values given below. Normally constructor initializes the variables beforehand. When I run the function from a function like Rational_Caller, the member function file given below gives a...
The proble is in void Rational::reduction() function. What happens when if (numerator % loop == 0 && denominator % loop == 0) is false? You should have initlise gcd to 0 for each iteration of for-loop or even batter, do't use gcd variable at all. See it here in action: for (int loop = 2; loop <= largest; loop++) { ...
69,407,697
69,408,321
Missing return statement after if-else
Some compilers (Intel icc, pgi/nvc++) issue "missing return statement" warning for functions like below, while others (gcc, clang) do not issue warnings even with -Wall -Wextra -pedantic: Is the code below legal according to the standard? This is a minimal reproducible example of my code that gives the warning. Simplif...
The C++ standard says this, see [stmt.return]/2: Flowing off the end of a constructor, a destructor, or a function with a cv void return type is equivalent to a return with no operand. Otherwise, flowing off the end of a function other than main results in undefined behavior. Your operator != does exactly that. It ne...
69,408,216
69,408,308
How does this line of code negate a std::uint64_t value?
I'm trying to understand what this code does. This is supposed to negate the coefficient coeff of type uint64_t* of a polynomial with coefficients modulus modulus_value of type const uint64_t: std::int64_t non_zero = (*coeff != 0); *coeff = (modulus_value - *coeff) & static_cast<std::uint64_t>(-non_zero); What's up wi...
non_zero will be either 1 or 0. -non_zero will turn that into -1 or 0. static_cast<std::uint64_t>(-non_zero) will tell the compiler to treat the signed number as unsigned, which will turn 0 into 0, and -1 into 0xffffffffffffffff. Then the bitwise AND will either clear all bits of (modulus_value - *coeff) (if non_zero i...
69,408,691
69,408,839
Variable with same name as type gives no compilation error when placed in function, struct or class
Given the Code: #include <iostream> typedef int Integer; Integer Integer = 1234; int main() { std::cout << "Integer: " << Integer; } Compiling the code with the gcc 11.2 Compiler will result in compilation errors: error: 'Integer Integer' redeclared as different kind of entity 4 | Integer Integer = 1234; ...
The difference is one of scope. In the first example, both Integers are declared in the global scope: typedef int Integer; Integer Integer = 1234; In the second example, one is declared in the global scope, whereas the other is local to main: typedef int Integer; int main() { Integer Integer = 1234; ... } It ...
69,410,277
69,417,486
"Directory listing failed" when execute "dart pub publish --dry-run"
I'm trying to publish a flutter plugin and I got this error when I perform a dry run. The plugin can be compiled and it works well, source code is here How do I fix it? Thank you. PS F:\Armoury\SourceCode\window_interface> dart pub publish --dry-run Publishing window_interface 0.1.0 to https://pub.dartlang.org: ... Dir...
I recreated the project and the problem doesn't appear, additional, the project needs to be cleaned before publish
69,410,312
69,410,535
std::forward not allowing lvalues to be accepted
Below is an implementation of the insert() member function of a max heap. I tried to use std::forward as I think it can be alternative to writing an overload of this function that accepts lvalues. However, the code is still not working for lvalues. Any ideas why? Note: values is a private vector<T> in the max_heap clas...
To create a forwarding reference, your argument's type must exist as a template parameter of the same function template. (See (1) of forward references for more information.) In your case, the template parameter T is from the class max_heap and not from the function's template argument list, so item serves as an rvalue...
69,410,954
69,411,421
Dereferencing struct pointer in pthread
I need to pass a structure to a pthread and be able to change the values of the struct from the function the pthread will execute. This is my code: #include <stdio.h> #include <stdlib.h> #include <vector> #include <pthread.h> void *deal_cards(void* deck); int main() { struct t_data { std::string name; ...
There are numerous mistakes in your code: The t_data structure type is defined local to main(), so deal_cards() can't use it. main() is exiting, destroying its local variables, while the thread is still running. the syntax you are trying to use to access push_back() in deal_cards() is all wrong. You are not referen...
69,411,620
69,411,700
C++ headers inclusion order, strange behaviour
I'm writing some library and want to have some "optional" class methods (or just functions), declared or not, dependent on other library inclusion. Say, I have a class SomeClass with method int foo(std::string). Sometimes it's very useful to also have similar method(s) which uses classes of another library the project ...
a.c includes a.h that does not include <SFML/System/String.hpp>, thus SFML_STRING_HPP is not defined. Usually, what to include is set through compiler -D options. For example -DUSE_SFML_STRING main.cpp #include <SFML/System.hpp> // FIRST, I include SFML base lib in the very first line. #include "a.h" ...
69,411,635
69,411,835
How do we read from file and store it into different objects in c++?
I am working on a project to store class objects in a dynamically allocated array. Now instead of users setting objects' values, I am trying to read object's values from a text file. There are 10 objects stored in the file and I want to read 8 objects and then insert them in my dynamic array. This is my class: class Pe...
It appears you have not actually compiled the code provided, since there are problems with it. There are different ways to serialize/deserialize data. Here is one way, which may be sufficient for your needs. This code allows constructing a Person from an istream&. Another way to provide a static class factory functio...
69,411,836
69,411,903
C++ Stack around variable corrupted and issue with the size of an array
I have a program that has been stumping me for the past few weeks. It asks the user to input how many rolls they want from two six sided dice, then runs a function that rolls those numbers and adds them together. The sums go into an array and then from that array, the amount of each sums is counted. Next, the odds of e...
You're using finitely sized arrays, in particular int countingArray[] = { 0 }; is an array with enough memory for one integer. When you fill the array, you are indexing into whatever memory lies beyond the end of the array! This is totally scribbling over who knows what. for (int rolls = 0; rolls < input; rolls++) { ...
69,412,140
69,414,345
Can't sort model by QDateTime with using QSortFilterProxyModel sort by role
I am stuck with simple problem but I can't figure it out why my model is not sorted. I have SimpleModel class that inherits from QAbstractListModel and I want to sort it by DateTime role. This is how I am setting the Proxy in my main.cpp: SimpleModel m; ProxyModel proxyModel; proxyModel.setSourceModel(&m); proxyModel....
as you say it works after calling proxyModel.sort(0, Qt::DescendingOrder); after setSortRole
69,412,498
69,412,839
Why my assigning an object itself doesn't work properly?
AFAIK, for an operator that doesn't guarantee the order of evaluation of its operand(s), we should not modify the operand more than once. Here I have this snippet that I wrote: I'm compiling it using gcc with the C++20 standard: -std=c++2b. int main(){ std::string s = "hello"; auto beg = s.begin(); *beg =...
All of these results are correct. Your misunderstanding comes from not knowing how postfix increment works. *beg = *beg++; By the rules of C++ operator precedence, postfix operators happen first. So this is *beg = *(beg++). C++17 forced assignment operators to completely evaluate all expressions on the right-hand si...
69,412,552
69,432,240
CGAL: Which headers to include
What is the standard workflow to figure out which headers are needed to make the program compile? Take the following simple example #include <iostream> int main() { std::cout << CGAL::square(0.002) << '\n'; return 0; } The function square is defined in Algebraic_foundations/include/CGAL/number_utils.h. Question 1:...
Almost all reference manual pages such as this one of the class Triangulation_2 give as very first information which header file to include. All higher level data structures are parameterized with a geometric traits class for which they in most cases pass a kernel, e.g., the Exact_predicates_inexact_constructions_kerne...
69,412,579
69,412,714
Assign value in ternary operator
When using std::weak_ptr, it is best practice to access the corresponding std::shared_ptr with the lock() method, as so: std::weak_ptr<std::string> w; std::shared_ptr<std::string> s = std::make_shared<std::string>("test"); w = s; if (auto p = w.lock()) std::cout << *p << "\n"; else std::cout << "Empty"; If I w...
auto p = w.lock() is not an assignment. It's a declaration of a variable. You can declare a variable in the condition of an if statement, but you cannot declare variables within a conditional expression. You can write: auto p = w.lock(); std::cout << ( p ? *p : "Empty" );
69,412,746
69,419,780
Matlab C++ integration, what is libting?
I have written some c++ code that I want to integrate with matlab in the following method https://www.mathworks.com/help/matlab/matlab_external/publish-interface-to-shared-c-library-on-linux.html The first step: Generate Interface on Linux goes well. The second step: Define Missing Constructs is not really necessary, ...
It turns out that you should make the first three letters of your .so file lib. So I changed testing.so to libtesting.so and reran the same steps and it worked. Thank you for your help Cris Luengo, who answered this question.
69,412,907
69,412,948
Why does the compiler say this macro function needs a closing parenthesis?
The code is below. The compiler says "Expected a )", but I do not get it: ( and ) are matching. What did I do wrong? #define CR_SUCCESS 0 #define EXIT_IF_FAILS(varResult, callString) \ (\ varResult = callString; \ if(varResult != CR_SUCCESS) \ { \ return -1; \ } \ )...
Expanding, your main looks like int main() { int result; ( result = testFunction(1, 2); if(result != CR_SUCCESS) { return -1; } ) } This is invalid, since you cannot have parentheses around statements. For some things you might do when you want a macro which acts...
69,412,970
69,440,589
arrays of arrays writing to a file using rapidjson
Using below function I am writing vector of vector into a file and getting this: [[[1, 2, 3],[1, 2, 3],[1, 2, 3],[1, 2, 3]]] However I want the output to look like this: [[1, 2, 3],[1, 2, 3],[1, 2, 3],[1, 2, 3]] Code: void resultToJson(std::vector<std::vector<int>> &result, const char *fileName) { rapidjson::Docume...
You have globalArray to which you push a single element. It is not needed. Eliminating it and using d.SetArray().PushBack(myArray, allocator); instead should work just fine, and avoid creation of an extra level in the JSON tree.
69,413,174
69,413,264
How to print in a file and with cout with same function in c++?
I have a simple print function like this: template <class T> void ArrayList<T>::print() const { //store array contents to text file for (int i = 0; i < length; i++) { cout << *(list + i) << endl; } } It prints the value in the array. I want it to work like this: If the ArrayList ‘print’ function is...
What you can do here is take an std::ostream& as your parameter. Then the print function doesn't care where the data is getting output to. static void print( std::ostream& os ) { os << "I don't care where this data is going\n"; } int main( ) { // Pass it std::cout. print( std::cout ); // Or pass...
69,413,986
69,414,523
Parameter pack extraction
I have a function2, which can be called with or without a second argument == char. If so, I want to modify that char-Argument. Given void function1_caller(int x) { char ws=7; function2_modifyArg(x, ws); } This works: template <typename ... WS> void function2_modifyArg(int x, WS ... ws) { function3_end...
You don't need the parenthesis you just need to put the operation you want to do before the pack expansion: template <typename ... WS> void function2_modifyArg(int x, WS ... ws) { function3_end(x, ws / 3 ...); }
69,414,070
69,414,099
Why does size of array differ in main and other function?
I am not new to C++, but today I found that the size of the array is different in the main function and in other functions. Why is that? I suppose it's something related to pointers. #include<bits/stdc++.h> using namespace std; void func(int arr[]){ cout<<"func size: "<<sizeof(arr)<<"\n"; } int main(){ int ar...
Because the array is decayed to a pointer What is array to pointer decay?. you can pass the array by reference to see the same size, as follows #include <iostream> template <class T, size_t n> void func(T (&arr)[n]) { std::cout << "func size: " << sizeof(arr) << "\n"; } int main() { int arr[5]; std::cout ...
69,414,335
69,414,376
How do I act upon a class in C++ from a class method?
In the realm of psuedocode, if I wanted to act upon something in Java, I could go class Dragon { //some code here defining what a Dragon is } class Knight { //some code here defining what a Knight is public void Attack(Dragon dragon) { // <----- specifically this //define an attack } } class M...
In C++, when a class or any other identifier is declared below, as far as the compiler knows it is undeclared. You will need to declare Knight below Dragon. Also notice the distinction between passing a class as an argument by value, reference or pointer. In most cases you will want to pass a class by reference such as...
69,414,350
69,414,403
Why is my string not printing in a function?
Here is the code: #include<iostream> using namespace std; int lengthOfLastWord(string s) { int i,j,n=0; for(i=0;s[i]!=0;i++){ n++; } string s1; for(i=n,j=0;s[i]!=' ';i--,j++){ s1[j]=s[i]; } cout<<s1; }; int main(){ string s; getline(cin,s); lengthOfLastWord(s); ...
First and foremost, your lengthOfLastWord() function doesn't return anything so have its return type be void: void lengthOfLastWord(string const& s) { // ^^^^^^ Preferably use const reference here to avoid making unnecessary copies at each invocation to 'lengthOfLastWord()' /* ... */ } No...
69,414,827
69,415,000
How to terminate my cpp program after 3 attempts of asking for pin?
My program should terminate after 3 wrong attempts but mine would still proceed to the menu even if the attempts were wrong. I've tried using return 0, but I didn't know why it still not worked. Is there any way to fix my program? #include <iostream> #include <string> using namespace std; int main () { string pin; in...
first you have to do change this like that if ( attemptCount == 2) { cout << "3 pins were unsuccessful."; return 0; } else if ( pin != "1234" ) { cout << "Pin is incorrect." << "\n" << endl; attemptCount++; } what happening here you are checking first pin is correct or not if it goes there i...
69,414,958
69,415,093
defaulting to using braces enclosing each case in switch statements in Visual Studio Code
In C++ or C#, it's generally a good practice to enclose each case within curly braces (e.g., see C# switch statement with curly braces for each case/default block within the switch statement?). But Visual Studio Code defaults to creating a template that leaves them out. What UI preferences can I change so that they are...
You should add a snippet by yourself. Select Command palette (F1) -> Preferences: Configure User Snippets -> C++ and add the following code. "switch2": { "prefix": "switch2", "body": "switch (${1:expression}) {\n\tcase ${2:/* constant-expression */}: {\n\t\t${3:/* code */}\n\t\tbreak;\n\t}\n\tdefaul...
69,415,046
69,415,600
Clang issues -Wunused-value depending on whether the code is called from a macro
I use a special assertion macros called CHECK. It is implemented like this: #define CHECK(condition) check(condition).ok ? std::cerr : std::cerr The user can choose to provide additional information that is printed if the assertion fails: CHECK(a.ok()); CHECK(a.ok()) << a.to_string(); Notice the ternary operator in ...
I don't think that this is a good solution what I suggest here but you could change your code so that you will always use your std::cerr, by changing your check(condition).ok ? std::cerr : std::cerr to check(condition).ok ? std::cerr << "" : std::cerr << "": #include <iostream> struct CheckResult { CheckResult(bo...
69,415,139
69,415,346
reinterpret_cast between char* and std::byte*
I'm reading type aliasing rules but can't figure out if this code has UB in it: std::vector<std::byte> vec = {std::byte{'a'}, std::byte{'b'}}; auto sv = std::string_view(reinterpret_cast<char*>(vec.data()), vec.size()); std::cout << sv << '\n'; I'm fairly sure it does not, but I often get surprised by C++. Is reinterp...
The code is ok. char* and std::byte* are allowed by the standard to alias any pointer type. (Be careful as the reverse is not true). ([basic.types]/2): For any object (other than a base-class subobject) of trivially copyable type T, whether or not the object holds a valid value of type T, the underlying bytes ([intro....
69,415,271
69,415,622
I got 'fatal error: opencv2/core.hpp: No such file or directory' but there is it
I'm trying to use opencv 4.x library on C++. When I run a test code on vscode, the error occured 'fatal error: opencv2/core.hpp: No such file or directory' But there is the file in the directory. I checked vscode's json file and I set the include path correctly. I don't know why. Can you tell me anything i missed? { "c...
C:\\minGW+opencv\\opencv\\build\\include is the wrong include path for your project. (it only contains cmake scripts, no actual headers) assuming you did a proper mingw32-make install before (well, did you ??), it should be: C:\\minGW+opencv\\opencv\\build\\install\\include
69,415,361
69,415,571
Can requires-expression in C++20 be of type implicitly convertible to bool?
In the following example the requires-expression of second f-function overload has the type std::integral_constant<bool,true>, which is implicitly convertible to bool: #include <type_traits> struct S { static constexpr bool valid = true; }; template<typename T> int f() { return 1; } template<typename T> int f() r...
I believe GCC is correct—the type must be bool exactly per [temp.constr.atomic]/3 (note that E here is std::bool_constant< T::valid >()): To determine if an atomic constraint is satisfied, the parameter mapping and template arguments are first substituted into its expression. If substitution results in an invalid type...
69,415,408
69,418,230
BOOST C++ get rotation or orientation of a linestring
i'm trying to find the rotation of a linestring. Basically i have a linestring like typedef boost::geometry::model::linestring<point_type> linestring_type; linestring_type line; line.push_back(point_type(xx1,yy1)); line.push_back(point_type(xx2,yy2)); and i would like to know if we can know the rotation of a linestrin...
You can lookup the arc-tangent in a "wind-rose" table. The raw output will be [-π,+π] so assume that we want to divide that in 8 segments: double constexpr segment = 0.25; struct { double bound; char const* name; bool operator<(double index) const { return index > bound; } } constexpr table[] = ...
69,415,801
69,415,849
Why is my exception sliced to base class if I catch it with reference to base class?
So I've written a small C++ class as follows: class bad_hmean : public std::logic_error { const char *nature_; char *what_; public: bad_hmean(const char *fname); ~bad_hmean() { delete[] what_; } const char *what() { return what_; } }; inline bad_hmean::bad_hmean(const char *fname):nature_("BAD H...
bad_hmean doesn't override what() correctly. It should match the signature of the base class what as: const char *what() const noexcept { return what_; } // ^^^^^ ^^^^^^^^ BTW: It's better to use override specifier (since C++11) to ensure that the function is overriding a virtual function from a base c...
69,416,291
69,416,342
Why the array is not printing without the pointer? Is the following code correct?
I'm new to coding. I'm working on pointers. The following code is correct, means there is no syntax error in it but still the second while loop is not printing anything. #include<stdio.h> #include<stdlib.h> int main(){ int arr[]={10,20,30}; int *ptr=arr; int i=0; //Printing Array with Pointer wh...
Write i = 0; just above the while loop. After completing for loop then value i=3 so you have to again i=0 so that while loop start printing Hope you will get it
69,416,636
69,417,510
C++ pmr polymorphic memory resources choice supports to release as needed
My program is a daemon and runs for a long time. Only some of the time it will needs a lot of memory resource. I want to increase my program performance by increasing memory locality. And PMR seems like a good tool for this purpose. However, it seems that the memory resources provided by the standard does not return th...
A memory resource can be written to do whatever you want. However, since what you've described (returning memory that is unused) is what the default allocator does (and is one of the main reasons to use it), there wasn't much point in adding more standard library memory resources that do this. Most of the defined memor...
69,416,724
69,417,250
JsonCPP throwing a logic error:requires objectValue or nullValue
void exp::example(std::string &a, std::string &b) { if (m_root.isObject() && m_root.isMember(a)) { if (m_root[a].isMember(b)) { m_root[a].append(b); } } else { m_root[a] = Json::arrayValue; m_root[a].append(b); } } (m_root is defind in ...
On the 4th iteration you access the m_root["hey"] object which is of type arrayValue. Those values are not supported by the isMember method. You'll have to find the value in the array in another way. I suggest iterating over the array, in something like: bool is_inside_array(const Json::Value &json_array, const string&...
69,416,805
69,417,190
Why does the same algorithm result in different outputs in C++ & Python?
I am running a small code in which there are periodic boundary conditions i.e.,for point 0 the left point is the last point and for the last point zeroth point is the right point. When I run the same code in Python and C++, the answer I am getting is very different. Python Code import numpy as np c= [0.467894,0...
I took your code, added the missing closing bracket of the large "for" loop and also changed the length from "50" to "1000000" as in the python version. Then I replaced all "float" with "double" and the resulting output is: 0.505749 0.505749 0.505749 0.505749 0.505749 0.505749 Thus, of course, implementing the same cod...
69,416,953
69,417,169
vector of a template class with unknown parameters
I am working on a program that has to use std::vector, while the types of elements are unknown. The std::vector can hold different types of elements. Specifically, these types are enumerated from a template class. What I want to do is something like below, #include <vector> template <size_t N> class Element{ int arr...
I could suggest two approaches for this. Ditching Templates You could ditch the template parameter in your Element class and have it contain a std::vector whose size is set upon construction and never changed. Something like this: class Element { public: Element(std::size_t size) : m_vector(size) {}; private: ...
69,417,062
69,417,230
SFML not drawing multiple Circles
I am trying to program Tic Tac Toe in C++ with SFML. I have programmed it to draw a circle, once the left mouse button is click. Then when I click again, it redraws that circle in another position, instead of drawing another circle. I want to make it draw another circle in a different place. I draw the Circle with the ...
Analyze that part of your code: window.clear(); if (draw_o) window.draw(CreateO(x_pos, y_pos)); // Called here. window.display(); It clears the whole window and draws one circle given from the function. You only draw one circle in the game loop. To have multiple circles I recommend creating a circles vector, for examp...
69,417,112
69,417,171
Using curly brackets instead of make_pair giving error
It gives no instance of overloaded function "lower_bound" matches the argument list error. I don't understand this behavior as curly brackets work fine in general while making a pair. Using curly brackets: vector<pair<int, int>> a; auto ptr = lower_bound(a.begin(), a.end(), {2, 3}); Using make pair: vector<pair<int, i...
Compiler has no possiblility to deduce {2, 3} to std::pair<int, int> in this context. See the declaration of lower_bound: template< class ForwardIt, class T > ForwardIt lower_bound( ForwardIt first, ForwardIt last, const T& value ); Compiler cannot assume that T should be equal to decltype(*first), because it doesn't ...
69,417,797
69,418,002
C++ using switch-case return value as a condition for if statement
May one write something like this in c++: // ... if(value <= switch(secValue){ case First: return 1; case Second: return 2; return -1; }){ //... do some logic ... } // end if Thanks
Exactly this, no. But you could get close with a lambda expression. Example: #include <iostream> int main() { // dummy types and values needed for demo enum test_enum { First, Second } secValue = First; int value = 1; if (value <= [secValue]() // ^ Capture secValue...
69,418,500
69,430,909
Am I using the correct undistort routine? Is photo wide-angle or fisheye?
I am experimenting with undistorting images. I have the following image below, and using the undistort function have the result. The fisheye module doesn’t work. Is this because my image isn’t a fisheye but wide angle instead? And in either case how do I reduce the perspective distortion? FYI I have lost the specs on t...
The image seems just wide-angle, not fisheye. Images from fisheye camera usually have black circle borders, and they look like seeing through a round hole. See picture c) below (from OpenCV doc): The normal method of distinguishing wide-angle from fisheye is to check the FOV angle. Given the camera intrinsic parameter...
69,418,554
69,418,572
What is the meaning of: Base(int x): x{x}{}?
I was going through some tutorial online and found one c++ snippet which i am unable to figure out what exactly that snippet is doing. I need info like what this concept is called and why it is used. Code is: class Base{ int x; public: Base(){} Base(int x): x{x}{} // this line i am unable to understand. }; ...
Lets start off with the following: the : after the corresponding constructor in the definition represents "Member Initialization". x is an integer C++ you are able to initialize primitive datatypes utilizing curly braces. See: https://www.educative.io/edpresso/declaring-a-variable-with-braces-in-cpp So therefore th...
69,418,580
69,418,658
Incorrect result of arithmetic operations using LLVM-based compilers
Code: float fff = 255.0f; float a0 = (fff / 255.0f) * 100.0f; If I use LLVM-based compilers (for example Intel C++ compiler or clang) variable a0 equals 100.000008, but if I use g++ compiler I get the right result - 100. Why do LLVM-based compilers return the wrong results? How to fix that? I can't just switch to g++ ...
I don't know much about LLVM compilers, it is odd that you get 100.000008 though, since you have only whole numbers in there, even in the intermediate results. However even with G++, you should still not rely to get an accurate result on floating point types calculations due to the (binary) rounding errors in the calcu...
69,418,628
69,418,800
I want to find the asymptotic complexity f(n) for the following C++ code
for(int i=0; i<rows; i++) { for(int j=0; j<cols; j++) { statement; } } I observed that the outer loop runs rows time and the inner loop runs rows * cols times and the statement runs rows*cols times as well. How should I put all them together to find a general function f(n) to find the number of ste...
Complexity of this code is O(n²). But in your case complexity is counted as a number of steps inside the code. So if you have rows and columns (a matrix actually) then complexity is just a product of members rows*cols. In more detailed way its better to count all the code that is executed in your statement. But for the...
69,418,652
69,614,728
Cmake undefined reference when linking with a library that uses another library built with a Python script
I am new to cmake and I am trying to port a project of mine previously built with handwritten makefiles. The executable uses a lib "core" that I build that needs the lib "xed" (written by intel). Xed uses a python script to be built so in the CMakeLists to build my lib core, I used an "add_custom_command" to build xed ...
There are two problems at once here: when trying to porting to cmake I tryed to mimic the way my makefiles worked. When I was thinking about how to embed libxed into my libcore I thought I was doing it in my makefiles but I wasn't, I was linking the final executable with my libcore and libxed. So the two problems are :...
69,418,973
70,617,938
Problem building C++ code with Eigen3 and CMake eigen3/Eigen/Core' file not found
I have simple C++ project that is organized like this: project |-- Input | |-- data.cpp <-- this file used eigen3 | |--- CmakeLists.txt |--- main.cpp |--- CmakeLists.txt Basically I am trying to create .so library from input and have main.cpp calls functions in it. CMake under project looks like this ...
The include directory defined in Eigen3::Eigen already includes eigen3 (e.g., /usr/include/eigen3 on Ubuntu). So you should use #include <Eigen/Core>. You can check this by: find_package(Eigen3 REQUIRED CONFIG) # checking property of the target get_target_property(inc_dir Eigen3::Eigen INTERFACE_INCLUDE_DIRECTORIES) m...
69,419,141
69,419,162
Array Sorting Issues in C++
I am trying to make a program that sorts an array without using the sort function (that won't work with objects or structs). I have made the greater than one work, but the less than one keeps changing the greatest element in the array to a one and sorting it wrong, and when used with the greater than function, the firs...
You are not looping correctly. Looks like you are trying bubble sort which is: void min_sort(int array[], const unsigned int size){ for(int k = 0; k < size; k++) for(int i = k+1; i < size; i++) if(array[i] < array[k]){ int temp = array[i]; array[i] = array[k]; ...
69,419,229
69,419,278
What type do I use in the constructor to initialize a member variable defined by a nameless enum?
I have a struct containing a member variable category which I guess is of type "nameless enum". struct Token { Token(); enum { NUMBER, VARIABLE, PLUS, MINUS, PRODUCT, DIVISION, POWER, SIN, COS } category; union { char variable; double number; }; }; As you can see I also...
Something like this? struct Token { enum EN { NUMBER, VARIABLE, PLUS, MINUS, PRODUCT, DIVISION, POWER, SIN, COS } category; union { char variable; double number; }; Token(const EN c, const double n) noexcept : category(c), number(n) {} //... Other constructors... }; ...
69,419,300
69,438,924
VkKeyScanExA all TCHAR option list
I need to make a dll which will simulate a key press. For this I found out you can use an INPUT in combination with SendInput. If you know from the start which key to simulate it is easy because you can look in the list of Virtual-Key Codes and code it from the start with those keys, but I actually need to be able to c...
After a lot of trial and error, and reading the source code from JavaFX, I found a better way to do it. I can simply get the int value of KeyCode from JavaFX and send that in a native function to C++ and not needing to send a String value I also don't need VkKeyScanExA at all. I'm not used to see an int value in this f...
69,419,349
69,419,414
reading and writing from structs with integer types only with c++ not working
I am using the below code to read and write to struct using the ifstream and ofstream classes. But for some reason I am not able to read back from the file. #pragma pack(1) struct test { int m_id; int m_size; //changed to integer test(int id, int size) :m_id(id), m_size(size) {} test() {}; }; #include ...
out.write(reinterpret_cast<char*>(&s1), sizeof(s1)); This will place the indicates bytes to std::ofstream's internal buffer, rather than the actual file. Like all efficient input/output frameworks, iostreams -- both input and output -- uses an internal buffer to efficiently read and write large chunks of data. When wr...
69,419,792
69,419,882
Why can't C++ infer array size with offset?
This code fails to compile template<unsigned n> void test(char const (*)[n + 1]) { } int main() { char const arr[] = "Hi"; test(&arr); } with error note: candidate template ignored: couldn't infer template argument 'n' However, if you change n + 1 to n, it compiles just fine. Why can't the compiler deduce n ...
From cppreference, in the " Non-deduced contexts" section: In the following cases, the types, templates, and non-type values that are used to compose P do not participate in template argument deduction, but instead use the template arguments that were either deduced elsewhere or explicitly specified. If a template par...
69,421,509
69,421,572
What value explicit constructor brings when arguments passed are custom type?
I understand the value of keyword explicit when used in cases where there is a chance of creating ambiguity, like the examples I am seeing here and here. Which I understand as prevents implicit conversion of basic types to object type, and this makes sense. struct point {explicit point(int x, int y = 0); }; point p2 = ...
The point of explicit has nothing to do with the parameter list, it has to do with the type being constructed, especially if there are side-effects. For example, consider std::ofstream. void foo(std::ofstream out_file); // ... foo("some_file.txt"); Without explicit, this will attempt to open some_file.txt and overwri...
69,421,674
69,521,901
Can't get_to vector of object inside itself with Nlohmann's JSON
I've got the following code (simplified): namespace nlohmann { // https://github.com/nlohmann/json/issues/1749#issuecomment-772996219 template <class T> void to_json(nlohmann::json &j, const std::optional<T> &v) { if (v.has_value()) j = *v; else j = nullptr; } template <class T> void from_json(...
I was doing some thinking on @Niels's answer and I realized that friend void from_json is taking an already-constructed Component& but Component doesn't have a default constructor. I added Component() : components(std::nullopt) {} and we're off to the races!
69,421,849
69,421,883
C++ header file class declaration
So in my C++ project, I have my "cards.h" and "cards.cpp" file, and the "cards.h" file declares 3 classes: Card, Deck, Hand class Card { private: // some private attributes public: // some public methods //..... void play(Deck& deck, Hand& hand); // This method plays the card, removes it ...
You are correct. C++ needs the declarations to go from top to bottom. A side note you have incorrect syntax for the class declarations. Each class needs to be terminated with a semicolon after the last closing curly brace. I tested your example and it works fine. You can separate the classes into their own files and ...
69,421,880
69,421,921
std::function inside template class giving object creation error
Getting below error for the code given below. Trying to have 3 std::function inside an template class and then initialize them with different functions from different classes. Why is this error happening? What's wrong with below code? template <typename T> class CFuntion { public: std::function<void()> callback_1;...
Look at this part: unique_ptr<CFuntion<void>> ptr1 = make_unique<CFuntion<void>(std::bind(&Impl1::do_something1, &Impl2::do_something1, &Impl3::do_something2)); // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Here, you pass onl...
69,422,376
69,422,767
Compile-time comparison of pointers to local variables after their end of life
Starting from C++17, it is possible to define a constexpr function that will return a pointer on its local variable. The caller will so get a pointer on an object after its end of life. Clearly such pointers cannot be dereferenced to avoid undefined behavior. But is it legal to compare them on equality? Consider an exa...
This is, oddly, implementation-defined per [basic.stc]/4: the pointers returned by f are invalid, so comparing them might do something bad. Of course, it’s not really clear what the space of possibilities includes here: a footnote mentions a runtime fault, which is usually lumped with undefined behavior, but during co...
69,422,822
69,423,268
What should be the proper declaration of array while finding the largest number in array?
C++ This is my code in C++ for finding the largest number in array. When I was running in my IDE then there was no compilation error but it was not giving me output. I think the problem is in the declaration of array at line 8. I replaced the array declaration from line 8 to line 11 then it is working fine in my IDE. ...
You declare int arr[n]; before the user has entered a value into n. n has an indeterminate value when you read it and create arr. You don't check that the user enters a positive value into n. Zero and negative sized arrays are not valid. Other points: bits/stdc++.h is not a standard header which makes your program n...
69,423,225
69,423,376
C++ Linked list unit test returns segment fault
My algorithm for implementing a linked-list as follows Function to add a new node and returns location pointer. One core function to handle adding a node front,end operations. linkedList.hpp #include <cstddef> class LinkedList{ public: int value {0}; LinkedList* nextNode {NULL}; }; LinkedList* addNewNode(...
newNode in addNewNode was never initialized, so it's a pointer to nowhere: LinkedList* addNewNode(int nodeVal) { LinkedList *newNode; // Uninitialized, so undefined newNode->value = nodeVal; // `->` dereferences the pointer, but it goes nowhere! One way to initialize it is using heap allocation, i.e., operator n...
69,424,015
69,424,050
glm rotation in ortho space
I set up my ortho projection like this : transform = glm::ortho(0.0f, width, height, 0.0f); this works pretty well, but when I want to use the glm::rotate function like this: transform = glm::rotate(transform, glm::radians(45.0f), glm::vec3(0, 0, 1)); my object rotates around 0 : 0 : 0. my vertices look like this: GL...
If you want to rotate around its center you have to: Translate the object so that the center of the object is moved to (0, 0). Rotate the object. Move the object so that the center point moves in its original position. GLfloat center_x = 606.0f; GLfloat center_y = 115.0f; transform = glm::translate(transform, glm::v...
69,424,025
69,425,305
Clang compiling for iOS (arm64) with -shared LDFLAG - Exec format error
Newbie alert here, sorry in advance if this question duplicates (didn't find the answer elsewhere)! I run into problems with simple hello binary for iOS (arm64) build on macOS machine (x86_64). The problem is that when I add LDFLAGS with shared framework (i.e. "-shared -framework CoreMedia" or other framework) to build...
-shared means you're building a shared library. You cannot run a shared library.
69,424,209
69,424,472
How can I split a string with multiple data into separate vectors - C++
I am trying to store data from a single vector into different vectors and I would like to separate each line into it's respective vector. A240 001 KERUL 41.857778 52.139167 A240 002 TABAB 40.903333 52.608333 A240 003 KRS 40.040278 53.012222 A240 004 KESEK 39.283333 55.566667 A240 005 INRAK 39.000000 56.300000 A242 001 ...
Regex would be good for this, here is an example : I think you can change it to your specific case, e.g. reading your input line by line from a file. #include <iostream> #include <string> #include <regex> // helper function for showing the content of a vector. // used to show you the content of each of the 5 vectors g...
69,424,237
69,424,353
Trying to return a function from a function with an argument function within it
I am curious if that's even possible to create a static function in another function and then return that static function with an argument function within it. So far what I've tried doesn't work at all, and when I use raw function pointers the code fails to compile. #include <iostream> #include <functional> //both do ...
The problem with your commented func is that a lambda which captures anything cannot convert to a pointer to function. Lambda captures provide data saved at initialization to be used when called, and a plain C++ function does not have any data other than its passed arguments. This capability is actually one of the big ...
69,424,363
69,424,708
Is it allowed to name a global variable `read` or `malloc` in C++?
Consider the following C++17 code: #include <iostream> int read; int main(){ std::ios_base::sync_with_stdio(false); std::cin >> read; } It compiles and runs fine on Godbolt with GCC 11.2 and Clang 12.0.1, but results in runtime error if compiled with a -static key. As far as I understand, there is a POSIX(?) f...
The code shown is valid (all C++ Standard versions, I believe). The similar restrictions are all listed in [reserved.names]. Since read is not declared in the C++ standard library, nor in the C standard library, nor in older versions of the standard libraries, and is not otherwise listed there, it's fair game as a name...
69,424,538
69,425,326
How can I iterate through the last element of the vector without going out of bounds?
The expected output is 1a1b1c but I only get 1a1b If I try putting '-1' next to input.size() in the for loop but that will just ignore the bug. What I'm looking for is that I want to be able to iterate through the last member of the string without going out of bounds. std::string input = "abc"; for (unsigned int i = ...
Few points for you to consdier: 1: for (unsigned int i = 0; i < input.size(); i++) specifically i++. This is a postfix operation meaning it returns i then increments the value of i. Not as big a deal here with integers but with iterators this can get very expensive as you create a copy of the iterator each time. Prefer...
69,424,945
69,425,044
How to detect integer overflow?
Write a program that reads and stores a series of integers and then computes the sum of the first N integers. First ask for N, then read the values into a vector, then calculate the sum of the first N values. For example: “Please enter the number of values you want to sum:” 3 “Please enter some integers (press '|' to...
You can do this with some arithmetic: So you want to know if acc + x > INT_MAX, where acc is the accumulator (the sum so far) and x is the next element. Adding them together may overflow though. But acc > INT_MAX - x is equivalent and x is already stored in an int. So this can also not underflow, bc. x can be at most I...
69,425,009
69,458,300
Activating and deactivating `while` loop with 2 mouse buttons
I want to activate a while loop with 2 mouse buttons. The first button should start and stop it and the second one should stop and reset it. It works, but I can't reset the first button. I tried a lot of GetKeyState() and GetAsyncKeyState() variants. bool loopy = false; int main() { while (true) { if (Get...
the solution if anybody is interested :) bool loopy = false; LRESULT CALLBACK LowLevelMouseProc(int nCode, WPARAM wParam, LPARAM lParam) { if (wParam == WM_XBUTTONDOWN) { if (HIWORD(((PMSLLHOOKSTRUCT)lParam)->mouseData) == XBUTTON2) { loopy = !loopy; return true; } ...
69,425,186
69,427,142
How to skip reading the first line of file?
How can I ignore the first line of the text file and start at the second line when I called it in the code? I was wondering how. Also, how can I sort the file according to first name, last name and grade? I just have the first name sorted but not the last name and grade accordingly. If you have any idea, I hope you can...
When I saw this post it reminded me of a similar task completed at uni. I have rewritten your code to perform the same task but using classes instead of structs. I have also included a way to sort the vector by using the function here. I have included the "ignore first line" method @Scheff's Cat mentioned. Here it is: ...
69,425,292
69,425,372
Array and pointers to structures
So I have this structure struct Data { int id; string message; }; I am trying to create an array of struct pointers and fill it with values using this Data *stack[10]; for(int i=0; i<10; i++){ stack[i] = (struct Data*) malloc(sizeof(struct Data)); stack[i]->id = i; stack[i]->message = "message" + i; } how...
Below is the working example. You can use smart pointers for automatic memory management, that is the destructor will be called automatically when reference count goes to zero. #include <iostream> #include <memory> using namespace std; struct Data { int id; string message; Data() { std::cout<<"default consructor"<<...
69,425,307
69,425,505
How do I define __cpp_exceptions for gsl:narrow to compile?
I am getting confused again :( I have looked at this discussion: detect at compile time whether exceptions are disabled I am new to trying to use GSL. I have copied the GSL folder to my PC and added a #include to my stdafx.h file. But the gsl:narrow command is not exposed. I then see it refers to the __cpp_exceptions m...
Whether or not the __cpp_exceptions macro is pre-defined by the MSVC compiler depends on your Visual Studio project's settings (i.e. whether or not C++ Exceptions are enabled). You can check/change the relevant setting by right-clicking on the project in the Solution Explorer pane and selecting the "Properties" command...
69,425,365
69,450,143
How do I port C++ code to Esp8266 and Esp32 using interrupts from code written for older boards
I am trying to port some C++ Arduino code to more recent ESP8266 and ESP32 boards. I have checked already the Arduino Stack Exchange forum unfortunately without results Porting this C++ code from older Arduino to Esp8266/Esp32 does not work, I have added also the compiling errors at the bottom of this question: /* rcT...
All ESP32 GPIO pins are interrupt-capable pins. You can use interrupts, but in a different way. attachInterrupt(GPIOPin, ISR, Mode); Mode – Defines when the interrupt should be triggered. Five constants are predefined as valid values:HIGH, LOW, CHANGE, RISING, FALLING void IRAM_ATTR ISR() { Statements; } Interrupt se...
69,425,693
69,425,784
Reversing a vector using recursion in C++
I'm using the below code to reverse a vector (modify it). void revArr(int i, vector<int> arr) { int n = arr.size(); if (i >= n / 2) return; swap(arr[i], arr[n-i-1]); revArr(i + 1, arr); } int main() { vector<int> arr = {2, 13, 5, 26, 87, 65, 73}; revArr(0, arr); for (auto i: arr) { ...
As pointed out by richard-critten you are passing a copy of the vector to revArr this copy is reversed not the original arr If you want the function to modify the value passed to it you have two options: Pass by reference or pass by pointer. It will be up to you to decide which is more appropriate for your use case but...
69,425,717
69,425,764
Switch statement with integer value
I am new to C++ and I am stuck on the switch statement because it doesn't seem to give an output when the value in the parentheses is an integer (Console-Program ended with exit code: 0). Although, the same code works fine when I change the type to char. Thank You. int main() { int num1; // argument of swi...
You are switching on an int, which is correct, but your cases are not integers - they are char since they are surrounded in '. '0' is never equal to 0, nor is '1' ever equal to 1. Change the case values to integers. int main() { int num1; cout<< "enter either 0 or 1" << "\n"; cin>> num1; switc...
69,425,941
69,427,565
Mixing cuda and cpp templates and lambdas
Example code: https://github.com/Saitama10000/Mixing-cuda-and-cpp-templates-and-lambdas I want to have a kernel in a .cu file that takes an extended __host__ __device__lambda as parameter and use it to operate on data. I am using a .cuh file to wrap the kernel execution in a wrapper function. I include the .cuh file i...
There are two problems with your approach. First, each lambda has it's own type even if parameters and function body are the same. For example, the following assertion fails #include <type_traits> int main(){ auto lambda1 = [](){}; auto lambda2 = [](){}; static_assert(std::is_same<decltype(lambda1), declt...
69,426,096
69,437,908
How to serialize and deserialize an object into/from binary files manually?
I've been trying to write the below object into a file and got lot of trouble since strings are dynamically allocated. class Student{ string name, email, telephoneNo; int addmissionNo; vector<string> issued_books; public: // There are some methods to initialize name, email, etc... }; So I got to know t...
I have found a solution serialize and deserialize an object into/from a file. Here is an explaination As I told you this is my class. And I have added two functions which overload the iostream's write and read. class Student{ string name, email, telephoneNo; int addmissionNo; vector<string> issuedBooks; pub...
69,426,322
69,426,733
Why is the template specialization function not being accessed
Problem Description In the following code we have 2 classes A and B whereB inherits from A. We also have 2 template functions test(T &t) and test(A &a). The output of the code is "A1". Why the test(A &a) function isn't being used in this example? // Online C++ compiler to run C++ program online #include <iostream> cl...
You're trying to pass a value of type A* to a function accepting A&. These are incompatible types, a pointer is not a reference. So the specialization test(A&) isn't considered, and the main template is used with T deduced as A*. If we change the call test(a) to test(*a), then the program will print A2. #include <iostr...
69,426,330
69,426,598
Declaring lambda with int type not working
I wanted to use the lambda function somehow, but it doesn't work, and I don't know why. vector<int> v; /* ... */ int median = [](vector<int> a) { sort(a.begin(), a.end()); return a[a.size() / 2]; } I created a lambda function, but how can I call it? int median = [](vector<int> a) { ... } (v)? But it doesn't...
Can I make it work in my case somehow? Yes you can. You can either call it immediately after the definition: int median = [](std::vector<int> a) { std::sort(a.begin(), a.end()); return a[a.size() / 2]; }(v); //^^ --> invoke immediately with argument See for reference: How to immediately invoke a C++ ...
69,426,729
69,426,785
Can't use operators properly when taking integer inputs from user in classes and constructors [OOP]
I'm trying to do multiple calculations on same 2 integer variables and display their results separately. It works fine if I already set values to the variables. But if I try to take input from users then it gives me random numbers instead in the output. Here is my code in which I try to take the input/values from the u...
In your constructor: calculation() { int num1 = 0; int num2 = 0; cout << "Write your numbers" << endl; cin >> num1>>num2; } You have created two local variables names num1 and num2. They have the same names as your member variables, but they are not the same. They are new ...
69,426,758
69,429,113
How to implement 1 or 2 frames lag between the main and the render thread?
I've read that engines skip 1 or 2 frames and keep this distance to ensure that the render thread and the main thread won't go too much forward. I've got a very simple command queue that allows the main thread to queue commands and the render thread to dispatch them, but I don't know how I can keep 1/2 frames distance ...
I've found Filament Engine and it has FrameSkipper class which implements the solution I need. quick example: //what class should implement Tick functionality? std::vector<std::function<bool()>> tickFunctions; void RunAndRemove() { auto it = tickFunctions.begin(); while (it != tickFunctions.end()) { if...
69,426,759
69,426,812
OpenGL how to set attribute in draw arrays
I have a GLfloat array containing my data that looks like this: GLfloat arr[] = { //position //color 300, 380, 0, 0, 1, 0, 300, 300, 0, 1, 1, 0, 380, 300, 0, 0, 1, 1, 380, 380, 0, 1, 0, 1 }; I'm trying to draw 4 points each with their respective color, currently I'm doing this: glPointS...
You are using a shader program. The vertex attribute has the attribute index 0 and the color has the index 1. Use glVertexAttribPointer to define the 2 arrays of generic vertex attribute data: glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 0, arr); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, siz...
69,427,505
69,428,624
Segmentation Fault before even the first line of `main()` is executed and there are no non-local variables
In the C++ code below, a segmentation fault occurs before the first line of main() is executed. This happens even though there are no objects to be constructed before entering main() and it does not happen if I remove a (large) variable definition at the second line of main(). I assume the segmentation fault occurs bec...
This is definitely a stack overflow. sizeof(dynamic_loop_functor_t) is nearly 64 MiB, and the default stack size limit on most Linux distributions is only 8 MiB. So the crash is not surprising. The remaining question is, why does the debugger identify the crash as coming from inside std::operator<<? The actual segfa...
69,427,533
69,427,568
How do i use hidden *this pointer?
I have this code: class Something { private: int m_value = 0; public: Something add(int value) { m_value += value; return *this; } int getValue() { return m_value; } }; int main() { Something a; Something b = a.add(5).add(5); cout << a.getValue() << endl...
add() is returning *this by value, so it is returning a copy of *this, so the chained add() is modifying the copy, not the original. add() needs to return *this by reference instead: Something& add(int value) { m_value += value; return *this; } UPDATE: a initially has m_value set to 0, then a.add(5) sets a.m_v...
69,427,869
69,428,439
Vector sum calculation in C++ - Parallel code slower than serial
I'm trying to write a multi-threaded code that performs the sum of the elements of a vector. The code is very simple: The threads are defined through a vector of threads; The number of threads is defined by the ThreadsSize variable; Using ThreadsSize equal to 1, the sum is performed in about 300ms, while using 8 threa...
This small modification of Function_Sum allows to obtain the speedup you desired: double sum = 0.; for(int unsigned k =kin; k <= kend; k = k + 1) sum += Vector[k]; Mutex.lock(); Sum += sum; Mutex.unlock(); Mutex is now being locked once per thread instead of once per addition. If you want a simple explanation, it'...
69,428,431
69,428,869
LeetCode findAnagrams: addition of unsigned offset error
I am getting the following error when submitting the following code to leetcode, I dont know why, as the code runs fine on my local machine. How can I reproduce this error and figure out exactly what's causing it? Line 1061: Char 9: runtime error: addition of unsigned offset to 0x7ffdd1b0d720 overflowed to 0x7ffdd1b0d7...
Store length of the string p at the beginning , then use that. vector<int> findAnagrams(string s, string p) { int pLen = p.size(); .... } Replace all p.size() in your code with pLen. Then you're good to go. Just like Mr. Sam Varshavchik explained in comment section, 1 + i - p.size() >= 0 this is causing the er...