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
71,187,137
71,188,186
How to pass and return an object to a C++ function called from iOS Swift?
In my iOS project, I want to call a C++ function from my Swift code that takes an object from my Swift code and returns another object. So far, following this tutorial and adding a little bit more stuff, I managed to call a C++ function that takes a simple parameter and returns a string: I create the NativeLibWrapper....
OK so here is what I did to make it work: create Objective-C TestAPOJO and TestBPOJO classes: // TestAPOJO.h: #import <Foundation/Foundation.h> @interface TestAPOJO : NSObject @property NSString *value1; @property bool value2; @end // TestAPOJO.mm: #import "TestAPOJO" @implementation TestAPOJO @end create ...
71,187,470
71,189,020
converting boost::multiprecision::int256_t to string
how would I convert a boost::multiprecision::int256_t type variable into a string for example if i have string string1 = "12345"; boost::multiprecision::int256_t int1 (string1); boost::multiprecision::int256_t int2 = int1 + 5 string string2; // how do i making string equivalent to int2
I think you just use the str() method on the multiprecision number. [Demo] #include <iostream> // cout #include <string> #include <boost/multiprecision/cpp_int.hpp> using namespace boost::multiprecision; int main() { std::string string1 = "12345"; boost::multiprecision::int256_t int1 (string1); boos...
71,187,556
71,187,591
C++ malloc(): corrupted top size on loop
I'm trying to create a function printarr that prints a dynamically sized array. However, whenever I try to run the code I get the error above. I tried copying code I found online as well, but get the same error, so I'm wondering if there's something wrong with my installation, or another part of the code is somehow aff...
The line int *arr=new int(n); will allocate memory for a single int and initialize that int to n. Therefore, the loop for(int i=0;i < n;i++){ arr[i]=i; } will access arr out of bounds, causing undefined behavior. What you probably want is to write int *arr=new int[n]; instead, which will allocate memory for n va...
71,187,933
71,298,442
How to save a vector of a custom type of elements on disk, read it, and parse it into a vector again using C++
The vector type is TrackInfo: class TrackInfo { public: TrackInfo(URL& _url, String& _title, double& _length, String _fileFormat); URL url; String title; double length; String fileFormat; }; ==================================================================================== std::vector<TrackInf...
I used nlohmann JSON. You can find it here -> https://json.nlohmann.me/ My code: std::vector<TrackInfo> StoreData::jsonToTrackInfo(json jsonFile) { std::vector<TrackInfo> tracks; for (json jsonf : jsonFile["Playlist"]) { // Try to parse the data. If there is an error, return the empty vector. ...
71,188,203
71,188,338
Which constructor (or implicit conversion) is called when passing a pointer to the constructor?
class Test { public: Test() { std::cout << "constructing" << std::endl; } Test(Test &t) { std::cout << "calling copy constructor" << std::endl; } Test(Test &&t) { std::cout << "calling move constructor" << std::endl; } Test& operator=(const Test& a){ st...
Test* t2 (t1); is direct-initialization. Direct-initialization considers constructors for class types, but Test* is a pointer type, not a class type. Non-class types do not have constructors. For a pointer type, direct-initialization with a single expression in the parenthesized initializer simply copies the value of ...
71,188,218
71,188,779
I cant merge two files in a third one
My problem is the following when I show the third file, It shows a lot of 0 and not the ints of file 1 and file 2. My file ends up with 4,00 KB (4.096 bytes) for some reason I don't know. Btw, the third file should have first: the first int of file1 and then the first of file2 and so on Edit: I was testing the problem,...
Your code has undefined behavior. According to §7.21.5.3 ¶7 of the ISO C11 standard, when a file is opened in update mode (+), the following restrictions apply: Output shall not be directly followed by input without an intervening call to the fflush function or to a file positioning function (fseek, fsetpos, or rewind...
71,188,236
71,188,438
How to initialize two std::arrays in constructor initializer list when second depends on first
Of the various ways to initialize std::array class members in the constructor initializer list, I found the variadic parameter pack to work best. However, how can I initialize a second std::array member which depends on the first? The example here is a struct polygon which takes a variadic parameter pack of Vector2 ver...
You can put patterns in front of a ..., not just the pack. However, this requires a suitable pack. In this case, a useful pack would be the indices, so you can make a helper for that: template<std::size_t... Is> auto make_lines(std::index_sequence<Is...>) { return std::array<Line<Number>, N>{ Line(vertices[...
71,188,379
71,188,493
Certain element sum from array
new to C++ and in need of help with an array. Looking at the code below, you can see I have an array of 20 undefined elements. My queastion is how do I sum up elements from a[5] to a[14]. Only these elements. (Including them ofc) #include <iostream> using namespace std; int main() { int a[20]; int summa;...
Use your knowledge of a for loop to add those values to your summa variable (which you did not initialize): #include <iostream> using namespace std; int main() { int a[20]; // set this to 0 or your answer will be erroneous int summa = 0; for (int i = 0; i < 20; i++) { a[i] = rand()%6...
71,189,175
71,189,234
Is there a way to define operators in C++? (or another language)
I am aware about operator overloading, but this is not what I am talking about. I do quite a bit of scientific computation in C++. So for example I have to compute gradients, dot products, laplacians, hessians... All of these usually have well defined and standrad math symbols. The gradient uses nabla, the hessian nabl...
Is there a way to define operators in C++? No. You can only overload (some of) the existing operators for custom types in C++. You can define functions that implement the operations that you want, and if you encode your source code in a character set that has those symbols (i.e. you use Unicode), and your compiler su...
71,189,472
71,189,838
how to make bind a map on pybind11
i am working on a backtester for crypto in cpp, but the backend is on python and flask, i try to use pybind11 in order to make the cpp work on the backend, here is my bind code namespace py = pybind11; PYBIND11_MAKE_OPAQUE(std::map<std::string, double>); PYBIND11MODULE(backtester, m) { py::class<BT::Backtester>(m...
py::bind_map tells pybind11 to bind a type, it doesn't affect the arguments that py::init gets. This is probably what you wanted to do: namespace py = pybind11; PYBIND11_MAKE_OPAQUE(std::map<std::string, double>); PYBIND11_MODULE(backtester, m) { py::bind_map<std::map<std::string, double>>(m, "StringDoubleMap"); ...
71,190,412
71,190,642
difference between array of class and array of structure?
I was wondering what the difference between the two. Source: https://www.geeksforgeeks.org/array-of-structures-vs-array-within-a-structure-in-c-and-cpp/ Sample Array of Structure #include <stdio.h> struct class { int roll_no; char grade; float marks; }; void display(struct class class_record[3]) { int...
There is no difference between a class type and a structure type in C++. They are the same thing. The code you are showing is C and not valid C++. In C++ class is a keyword and can not be used to name a type. You create an array of a class type in C++ exactly in the same way as you create an array of any other type: cl...
71,190,459
71,190,472
Why does returning an initializer list in a function returning a priority_queue call the vector constructor?
Consider the following code: std::priority_queue<int> foo() { return {14, 12}; } I would expect foo() to return a priority_queue containing 2 elements: 14 and 12. However, it returns a priority_queue containing 14 copies of 12. I stepped in with gdb and it appears that the vector constructor is being called. Could...
Creating a priority_queue with two integers like that: std::priority_queue<int> pq(a, b); Was till recently treated by most compilers as legal, sending the parameters to the underlying container, thus creating a queue holding a times b. Although the constructor of priority_queue that is used for that is actually expec...
71,190,760
71,190,935
How can I make the faces of my cube smoothly transition between all colors of the rainbow?
I have a program in Visual Studio that is correctly rendering a 3D cube that is slowly spinning. I have a working FillTriangle() function that fills in the faces of the cube with any color whose hex code I enter as a parameter (for example, 0x00ae00ff for purple). I have set the color of each face to start at red (0xFF...
That constant is going to overflow with each addition. Not just as a whole number, but across each component of the color spectrum: R, G, and B. You need to break your pixelColor into separate Red, Green, and Blue colors and do math on each byte independently. And leave Alpha fixed at 255 (fully opaque). And check for...
71,190,853
71,191,233
How to put int arrays into int 2d matrix in C++?
I wrote this(memory error) when I try to put int arrays into int matrix: #include <iostream> using std::cout; using std::endl; int* intToIntArray(int input, int length) { int output[20]; for (int i = 0; i < length; i++) { output[i] = input % 10; input /= 10; cout << output[i]; } ...
#include <iostream> using std::cout; using std::cin; void intToIntArray(int input, int length, int* &output) { output = new int[length]; for(int i = length - 1; i >= 0; --i) { output[i] = input % 10; input /= 10; } } int main() { const int arraySize = 5; int a[] = { 111110, 1111000, ...
71,190,864
71,190,919
Strange Behavior with pointers with arrays in c++
Hello people of Stacked Overflow! Recently I've been learning about pointers and arrays in my college Computer Science class. In order to try to test the depth of my understanding of the two, I tried to come up with some confusing instances in order to see if I could correctly predict the outcome of the result, as well...
I'm very confusing seeing as in nowhere in that short code am I assigning anything further. Not quite, you are, indeed, assigning a new value "further". You are doing it right here: cout<<*(++valptr)<<endl; In C++, the ++ operator increments its operand. The expression ++valptr by itself is logically equivalent to ...
71,190,880
71,190,941
IDE recommends 'pass by value and use std move' when parameter class has no move constructor
struct Person { int mId; std::string mName; Person(int id, std::string name) : mId(id), mName(std::move(name)) { } }; struct Node { Person mData; Node* mLeft; Node* mRight; Node(Person data) : mData(std::move(data)), mLeft(nullptr), mRight(nullptr) {} }; When writing a co...
Your Person class is following the "rule-of-zero", meaning it doesn't declare any copy/move operations or destructor explicitly. That is usually the correct thing to do, because then the compiler will declare all of them implicitly and define them with the semantics you would usually expect from the these operations, i...
71,191,214
71,191,288
Clarification on the relation of arrays and pointers
I wanted some further understanding, and possibly clarification, on a few things that confuse me about arrays and pointers in c++. One of the main things that confuse me is how when you refer to the name of an array, it could be referring to the array, or as a pointer to the first element, as well as a few other things...
Arrays and pointers are two different types in C++ that have enough similarities between them to create confusion if they are not understood properly. The fact that pointers are one of the most difficult concepts for beginners to grasp doesn't help either. So I fell a quick crash course is needed. Crash course Arrays, ...
71,191,244
71,191,266
Why is compiler giving error while using make_unique with array?
Why can't i initialize a unique pointer #include <iostream> #include <memory> class Widget { std::unique_ptr<int[]> arr; public: Widget(int size) { arr = std::make_unique<int[size]>(); } ~Widget() { } }; int main() { } I am not able to understand the meaning of ...
You need arr = std::make_unique<int[]>(size); make_unique has a specific documented usage: template< class T > unique_ptr<T> make_unique( std::size_t size );` ... Constructs an array of the given dynamic size. The array elements are value-initialized. This overload participates in overload resolution only if T is an...
71,191,329
71,191,941
Comparing two strings that return the equivalent substring in c++
I have a function subString that takes in two strings. I loop through my first string to generate substrings of at least size >= 4. I want to find a substring that exists in my second string. For example: string1: "ABCDE" string2: "XYBCDEFGH" substrings of string1 include: "ABCD", "ABCDE", "BCDE" So, I want to compar...
You could Return a vector of substrings. Then loop through the vector and search in s2 string using find method. See below code sample. #include <iostream> #include <string> #include <vector> using namespace std; vector<string> subString(string s1, string s2){ int n = 4; int strLength = s1.length(); st...
71,191,472
71,191,766
Finding next palindrome
I am trying to solve a problem related to palindrome which is: "For each K, output the smallest palindrome larger than K." (Where K is an integer taken as user input) I have used the recursive approach but it just throws an error stating SEGMENTATION FAULT.... My approach... #include <iostream> using namespace std; in...
Instead of writing else { pal(x+1); } write return pal(x+1); Your current pal function does not return any value if the first x+1 is not a palindrome. Based on what @igorTandentik has written in the comments, this should fix the problem. EDIT 1: Your code has a serious flaw. You're making x zero in your while loop an...
71,191,825
71,191,862
Does member function like operator<< , operator* need ADL to work?
I have a code snippet (Hypothetically): #include <iostream> struct Pirate { void song_name() { std::cout << "Bink's Sake\n"; } Pirate& operator*(Pirate const& other) { // do something return *this; } }; int main() { Pirate p1{} p2{}; p1.song_name(); // does this use qualified or unqualifed name lookup? ...
A name is a qualified name if the scope to which it belongs is explicitly denoted using a scope-resolution operator (::) or a member access operator (. or ->). Case 1 Thus, when you wrote: p1.song_name(); //here p1.song_name is a qualified name In the above statement, p1.song_name is a qualified name and so here quali...
71,192,352
71,192,631
How to implement operator[][] for 1D arrays
Is there a way to implement an operator like [][] for a 1D array? I want to change the implementation of a 2D vector to a 1D vector in my code (cause this increases the execution speed by about %50 in my program). 2D vector supports [y][x]. How can I have such functionality for a 1D vector? I can do it like this: const...
C++ does not allow virtual containers. So the operator [] is expected to return a true object of the expected size, if you want all the goodies like true iterators to work smoothly. Here is a post of mine about the iterator question for multi-dimensional containers and a more general question on Code Review If you only...
71,192,384
71,192,734
Replicating environment from renderdoc to debug
I have a strange issue, a vulkan application I am writing seemingly runs fine when run from the terminal. But if run from renderdoc an assertion inside the official .hpp header triggers. Since this only happens if the program is launched with renderdoc I am having a hard time trying to debug it. Is there a way to get t...
If anyone runs into something like this in teh future. The problem was that an old instance of renderdoc was installed in my system, this in turn created conflicts when loading the program onto renderdoc as vulkan wasn't properly configured. Uninstalling the old version fixed it.
71,193,900
71,194,203
What is the meaning of Scalar(0,0,0,)?
Hello i want to ask what is this line of code do? Mat res(img.rows, img.cols, CV_8UC1, Scalar(0,0,0)); i'm guessing it's making matrix of image rows and columns but i still don't understand what's the Scalar(0,0,0) for?
From the documentation of OpenCV, you are using the fourth constructor: Mat (int rows, int cols, int type, const Scalar &s); The third argument is the array type for the elements of the matrix. You are using CV_8UC1: 8-bit single-channel array. The fourth argument is an optional value to initialize each matrix element...
71,193,912
71,194,013
Check if a string contains palindromes separated by a hash symbol using a vector as an implementation of the stack
I have to write a bool mirrored() function that has to return true if the input meets the following criteria. The string is mirrored if it contains palindrome substrings separated by one (and only one) hash symbol, and if all the palindromes are correct. So it should return true for the following: #, ####, abc#cba, #...
A few hints for the first version. The while(hashSymbol && !stack.empty()){ Is superfluous. Check just one character at a time. stack.push_back(s); pushes the '#' on the stack too. I think you will have an easier time to adapt your second version rather than correcting the first. Your not far away from a solution..
71,194,142
71,194,394
A little trouble with g++ compiling makefile
I've got the following makefile: test_containers: containers.o g++ out/containers.o test/test_containers.cpp -o out/test_containers.exe containers.o: queue.o stack.o container.o g++ -c out/queue.o out/stack.o out/container.o -o out/containers.o queue.o: container.o g++ -c src/Queue.cpp out/container.o -o ...
Your recipes are cluttered with files that don't belong there. Given the very limited amount of information you've provided, the most direct solution is to just slam out the recipes directly. test_containers: out/test_containers.exe out/test_containers.exe: out/test_containers.o out/containers.a g++ $^ -o $@ out...
71,194,444
71,194,732
C++ LNK2005 already defined in B_calculating.obj
Errors: LNK2005 "private: static char const * const boost::json::key_value_pair::empty_" (?empty_@key_value_pair@json@boost@@0QBDB) already defined in B_calculating.obj LNK2005 "private: static struct boost::json::object::table boost::json::object::empty_" (?empty_@object@json@boost@@0Utable@123@A) already defined in B...
There is a clue in the boost/json/src.hpp header: This file is meant to be included once, in a translation unit of the program. You should only include boost/json/src.hpp in one cpp file. You should remove it from B_calculating.h and only include it in main.cpp.
71,194,704
71,194,786
I want my clock program to display the output as 00:00 instead it displays it as 0:0 even though I have used stream manipulators
So I made a sloppy clock program as an assignment. It works fine however I want the output to display each cout as "01:02", instead it displays "1:2", even though I think I have written all the right manipulators. This is my whole program. #include <thread> #include <chrono> #include <iostream> #include <iomanip> #incl...
You are using the null character to fill (which is not visible). cout.fill(0); What you probably meant was to use the ASCII character 0, like this: cout.fill('0');
71,194,939
71,200,713
Why constinit of half-initialized struct does not work
struct A1 { int x; int y; }; struct A2 { int x = 1; int y = 2; }; struct A3 { int x = 1; int y; }; constinit A1 a1; // x == 0, y == 0. constinit A2 a2; // x == 1, y == 2. A3 a3; // x == 1, y == 0. constinit A3 a4; // Error: illegal initialization of 'constinit' entity with a non-constant expression int ...
I think this is a case where we might be missing some wording. To start with, there are three stages of initialization that happen ([basic.start.static]): Constant initialization If not that, zero-initialization (for static storage duration variables, like the ones in this question) If necessary, dynamic initializatio...
71,195,215
71,195,296
How can a c++ std::vector<NotAPointer> store objects of different size, and how can ++it know where to jump when it doesn't contain pointers
EDIT: TLDR; I was a victim of object slicing, which I didn't know about. Now the original question follows. I'm trying to understand how std::vector<MyClass> stores objects when an instance of MyDerived is push_backed into it. Also, how do iterators know where the start of the next memory block will be so that the incr...
When storing BaseShapes in a vector by value you'll experience what is called object slicing. Basically all information that only the derived classes contain is forgotten about, and only the base class' information is actually stored. All objects will behave as would BaseClass objects, with the only exception of potent...
71,195,244
71,195,445
Error: cannot define 'enum class std::align_val_t' in different module
I am a C ++ beginner and am looking to create a module. I have followed several guides and would like to test modules with classes. When I try to run the first module via g++-11 -c -std=c++20 -fmodules-ts func.cxx i get the following error: In file included from /usr/local/Cellar/gcc/11.2.0_3/include/c++/11/bits/stl_it...
the include directive in func.cxx needs to be in the global module fragment area. Else you'll get redefinitions. I.e. module; #include <string> export module ..... ...
71,195,257
71,197,613
how to include a separate file containing functions for a class
So i am making a library for a hardware to be used with arduino. Inside that class there are some hardware specific code that needs to included. To improve readability i would like to move the hardware specific functions to another file //.h class myClass(){ public: myClass(); void controlGPIO(); }; //....
Common is to do one .cpp with #if defined(HARDWAREA) #include "deviceA_hal.h" #elif defined(HARDWAREB) #include "deviceB_hal.h" #endif void myClass::controlGPIO(){ #if defined(HARDWAREA) // some code unique to hardwareA #elif defined(HARDWAREB) // some code unique to hardwareB #endif } this is simpler to mainta...
71,195,423
71,195,465
How to use concepts in if statement
I have a concept which checks whether a type is iterable or not template<typename T> concept Iterable = requires(T t) { t.begin(); }; I cannot use it in a template due to problems with overloading, so I'd like to do something similar to the following: template<typename T> void universal_function(T x) { if (x i...
Concept instantiations are boolean values, so they can be used in if statements. You will need to use if constexpr to achieve the desired behavior, as it will allow for branches containing code that would be invalid in a different branch: if constexpr (Iterable<T>) { // ... } else if constexpr (Printable<T>) { ...
71,196,145
71,197,138
Overload resolution between constructor and inherited constructor in C++ - which compiler is correct?
In the following program struct B inherits B(int) deleted constructor from its base A, and also defines additional constructor B(int&&). Then an object of B is created with B b(1): struct A { A() {} A(int) = delete; }; struct B : A { using A::A; B(int&&) {} }; int main() { B b(1); } If both const...
GCC is correct here: there is a tiebreaker that prefers direct over inherited constructors ([over.match.best.general]/2.7), but it applies only if they have the same parameter types (ignoring those whose default arguments are being used).
71,196,409
71,196,549
C++ how to split string with alphabets and numbers
I have a need to split the following string into their corresponding alpahbets and numbers CH1000003 ABC000123 WXYZ10001 Results I want are st1: CH st2: 1000003 st1: ABC st2: 000123 st1: WXYZ st2: 10001 Now I do have a working code but the amount of code I have written seems a bit too much. There has to be an easy ...
Thanks to igor. size_t first_digit = idToCheckStr.find_first_of("0123456789"); cout << "first_digit: " << first_digit <<endl; std::string str1 = idToCheckStr.substr (0,first_digit); cout << "str1: " << str1 <<endl; std::string str2 = idToCheckStr.substr (first_digit,idToCheckStr.length());...
71,196,614
71,197,286
Vector push_back() fails when compiling with CMake and MinGW Makefiles
I've been searching all over the internet for a solution to this problem, however there is no good information about the origin of this problem. In essence, the program fails to run whenever I execute any vector-related function such as resize() or initializing the vector with a given size. This is the current project ...
Edit: It seems that the problem had to do with static linking of necessary libraries. Thus the solution I found was to include one of the static flags for g++ such as -static, -static-libstdc++, etc. To tell CMake to do this automatically upon compilation I just added this as a flag: set(CMAKE_EXE_LINKER_FLAGS "-static...
71,197,161
71,220,713
How to use ROS services and serial comunication with posix and semahrores in C++?
Im new to Concurrency and parallelism programming in C/C++ so I need some help woth my project. I want to run multiple process using POSIX and Semaphores in C++. So the structure of the program should be the following one. First I Open Serial port (Serial communication of the Raspberry PI 4). While the Serial is Open T...
Fortunately, ROS lets you decide what threading model you want to use (http://wiki.ros.org/roscpp/Overview/Callbacks%20and%20Spinning). You could use the ros::AsyncSpinner for that: Your main thread starts the AsyncSpinner that runs in the background, listens to ROS messages, and calls your ROS callback functions in it...
71,197,216
71,211,971
Why does compiling a header file with constexpr array use so much memory?
I have a header file with an array of unsigned chars that holds some raw binary data: #include <string> #include <array> extern __declspec(selectany) inline constexpr std::string_view bin_name = std::string_view("test.bin"); extern __declspec(selectany) inline constexpr int bin_size = 10812406; extern __declspec(select...
Compilers don't tend to do well with large initializers since the go-to method of compiling an initializer is to make an AST node for each element. There's a proposal to deal with this in the language directly that includes motivation and alternatives: constexpr std::span<const std::byte> bin_data = std::embed("test.bi...
71,197,736
71,197,799
C++ Linked List from header file is resetting memory storage
So I've been working on a linked list in C++ through a header file. When I insert values into it, it works fine, but as soon as I return to the main class and try to print the value stored inside a node, it returns a negative number. Here is an excerpt of my code so far, I tried to keep it as simplistic as possible. Th...
void AddHead(const T& addData) { Node n; n.data = addData; n.next = head; head = &n; Print(); } Once AddHead ends n is released, its a temorary variable on the stack. You have to create the nodes on the heap void AddHead(const T& addData) { Node *n = new Node(); n->data = addData; n->ne...
71,197,769
71,207,983
how to read and update the SACL properties of a folder in a remote machine in active directory
I am trying to read and update the SACL properties of a folder in a domain machine from the domain controller. I came across this link but I don't know how to use the IADs::Get to get the object of the folder from the active directory. I am struggling to find the ldap query to get the folder, I searched all over the in...
IADs::Get is only for objects in Active Directory itself. You can't use it for files on a file system. To modify permissions a file on a remote computer, you treat it pretty much the same as a file on the local system. You can use GetNamedSecurityInfo, where pObjectName would be the path to the file in the format of \\...
71,197,988
71,198,093
Built-in array with variable size?
Chapter 2.3.2 of The C++ Programming Language lists this constructor: class Vector { public: Vector(int s) :elem{new double[s]}, sz{s} { } private: double* elem; int sz; }; As far as I know, the array size must be a constant expression, and s isn't. Is this legal? If so, why?
Yes, it's legal because the array is allocated at runtime with the 'new' operator. If you want to allocate an array at compile-time, you must provide a const int, or constant expression. int count = 0; cin >> count; int* a = new int[count]; // This is dynamic allocation happen at runtime. int b[6]; //...
71,198,597
71,199,520
is a concurent write and read to a non-atomic variable of fundamental type without using it undefined behavior?
in a lock-free queue.pop(), I read a trivialy_copyable variable (of integral type) after synchronization with an atomic aquire inside a loop. Minimized pseudo code: //somewhere else writePosition.store(...,release) bool pop(size_t & returnValue){ writePosition = writePosition.load(aquire) oldReadPosition = readPositio...
Yes, it's UB in ISO C++; value = data[oldReadPosition] in the C++ abstract machine involves reading the value of that object. (Usually that means lvalue to rvalue conversion, IIRC.) But it's mostly harmless, probably only going to be a problem on machines with hardware race detection (not normal mainstream CPUs, but p...
71,199,179
71,209,937
CMake project builds but shows include error in LSP
I'm working on a C++ project using ccls (the LSP language server) and lsp-mode in Emacs. I also have a CMake project definition for my project. My project builds correctly with make using the Makefile generated by CMake, but ccls says that my #include is not found. Here's the project structure: + CMakeLists.txt + main....
ccls tries to find SomeClass.hpp in the root of your project. It should be fine when you change the first line of your main.cpp to this (At least for me it resolved the error): #include "src/SomeClass.hpp"
71,199,229
71,199,296
OpenGL. Multiplying a vertex by a projection matrix
I'm trying to draw a model and this is what I ran into, the code below works like 2d, although there should be a perspective Code # 1 mat4 Proj = glFrustum(left, right, bottom, top, zNear, zFar); mat4 View = gluLookAt(position, direction, up); mat4 World = mat4(1); glBegin(GL_TRIANGLES); for (auto& t : mesh) { norm...
The transformation with the projection matrix generates Homogeneous coordinates. A Homogeneous coordinate has 4 components, but you just pass 3 components to the vertex coordinate. Use all 4 components to specify the vertex coordinate. e.g: glVertex3f(dot1.x, dot1.y, dot1.z); glVertex4f(dot1.x, dot1.y, dot1.z, dot1.w);...
71,199,354
71,200,047
Vulkan dynamic rendering, nothing seems to be getting rasterized
I am trying to render using the dynamic rendering extension, to this effect I am trying to render just a triangle with these 2 shaders: #version 450 layout(location = 0) in vec2 inPosition; layout(location = 1) in vec3 inColor; layout(location = 0) out vec3 fragColor; void main() { gl_Position = vec4(inPosition,...
In case someone runs into this problem in the future. I was trying to render just a single frame (rather than on a loop) so I was not synchronizing objects because I thought it would not be necessary. Turns out it very much is, so if you are rendering to the swacphain images even if just once, things won't work unless ...
71,199,574
71,200,028
C++20 Concepts: Explicit instantiation of partially ordered constraints for member functions
This works and outputs "1", because the function's constraints are partially ordered and the most constrained overload wins: template<class T> struct B { int f() requires std::same_as<T, int> { return 0; } int f() requires (std::same_as<T, int> && !std::same_as<T, char>) { return 1; } };...
C++20 recognizes that there can be different spellings of the same effective requirements. So the standard defines two concepts: "equivalent" and "functionally equivalent". True "equivalence" is based on satisfying the ODR (one-definition rule): Two expressions involving template parameters are considered equivalent i...
71,199,777
71,199,988
Any way to know how many bytes will be sent on TCP before sending?
I'm aware that the ::send within a Linux TCP server can limit the sending of the payload such that ::send needs to be called multiple times until the entire payload is sent. i.e. Payload is 1024 bytes sent_bytes = ::send(fd, ...) where sent_bytes is only 256 bytes so this needs to be called again. Is there any way to k...
Although the call to ::send() is done sequentially, is the any chance that the byte stream is still mixed? Of course. Not only there's a chance of that, it is pretty much going to be a certainty, at one point or another. It's going to happen at one point. Guaranteed. sent to the same socket by different threads It ...
71,199,868
71,204,101
C++ Use a class non-static method as a function pointer callback in freeRTOS xTimerCreate
I am trying to use marvinroger/async-mqtt-client that in the provided examples is used together with freertos timers that use a callback that gets invoked whenever the timer expire. The full example is here. I wanted to create a singleton class to enclose all the connection managing part and just expose the constructor...
FreeRTOS code is plain old C. It knows nothing about C++, instance methods, function objects, etc. It takes a pointer to a function, period. As Armandas pointed out, WiFi.onEvent on the other hand is C++, lovingly written by someone to accept output from std::bind(). There is a workaround. When you read the xTimerCre...
71,200,268
71,200,313
What causes this code to trigger implicit int narrowing?
The following code makes clang to fail when -Wc++11-narrowing is specified #include <stdint.h> extern uint8_t numbers[]; extern int n; uint8_t test(int num) { uint8_t a{n > 0 ? *numbers : 2}; return a; } (Same code in godbolt: https://godbolt.org/z/nTKqT7WGd) 8:15: error: non-constant-expression cannot be n...
The second operand to the conditional expression has type uint8_t. The third operand, the literal 2, has type int. When the second and third operands to a conditional expression are of different arithmetic type, the usual arithmetic conversions are performed in order to bring them to their common type. [expr.cond]/7.2 ...
71,200,440
71,200,531
Forward declaration of class and still Error: Variable has incomplete type
I have defined two classes : (1) class Point_CCS_xy , and (2) random_Point_CCS_xy_generator. I would like to define a function in Point_CCS_xy class which makes use of random_Point_CCS_xy_generator class to generate random points on a cartesian coordinate system within a range Min and Max, both of which have been defin...
The type must be complete by the time you actually use it (e.g. constructing a value). Forward declaration will only help you specify pointer or reference types, not value types. Your main issue here is that you're defining your functions inline in the class definition. Instead of that, move them out: class Point_CCS_...
71,200,746
71,200,803
Error with befriending a function in a namespace in C++
I've tried to befriend a function in a namespace but I don't know why there is an error: Error C2653 'a': is not a class or namespace name I've tried multiple times and I don't think it's a mistake on my part but take a look: class plpl { private: int m; public: plpl() : m(3) {} friend void a::ab...
As suggested in comments, you need to forward declare the namespace a and the function abc, as shown below. #include <iostream> namespace a { void abc(); } class plpl { private: int m; public: plpl() : m(3) {} friend void a::abc(); }; namespace a { void abc() { plpl p; std::cout ...
71,200,786
71,200,919
recursive function for checking if the array is sorted not working
i wrote this isSorted function that will check if the array is sorted or not if the array is sorted, it will return 0, else it will return 1, but for some reason, the function keeps on returning 0 even if the array is not sorted. This is the full program with the function struct array { int A[10]; int size; ...
but instead of returning -1 , it is returning 0 When you write return -1; that value is only passed back to the caller. Now, at that point, you might be several calls deep into the recursion. The line from the call immediately before is this: ifSorted(a, n - 1, i); So, what happens is after that call returns, you ...
71,200,820
71,625,662
CMake trying to link with 'vulkan.lib'
I am following a Vulkan tutorial and I choose CMake as my build system. However, the build fails every time because it is trying to link with a file called 'vulkan.lib' from what I know, there's no such file as vulkan.lib because the actual library file for Vulkan is 'vulkan-1.lib' Here is my CMake script: project(Vulk...
Thanks to @Stephen Newell's comment I solved it by getting rid of the vulkan in the second target_link_libraries call and it worked.
71,201,005
71,203,546
Why the sequence from the bitwise operator(~) would be this? Is that broken?
#include <stdio.h> #include <stdlib.h> int main() { unsigned char a=100,b=50; printf("%d & %d = %d\n",a,b,a&b); printf("%d | %d = %d\n",a,b,a|b); printf("%d ^ %d = %d\n",a,b,a^b); printf(" ~%d = %d\n",a, ~a); /*the out come of this line would be this: ~100 = -101 */ printf(" %d >> 2= %d\n",a, a>>2); printf(" %...
According to the standard, the operand of ~ will undergo integral promotion. So here we will first promote a to int. [expr.unary.op]: The operand of ~ shall have integral or unscoped enumeration type; the result is the ones' complement of its operand. Integral promotions are performed. If int is 4 bytes (for example)...
71,201,135
71,201,223
Getting an error while using begin and end iterators
vector <vector<int> > v8; int N; cin >> N; for (int i = 0; i < N; i++) { int n; cin >> n; vector <int> temp; for (int i = 0; i < n; i++) { int x; cin >> x; temp.push_back(x); } v8.push_back(temp); } vector <int> ::iterator it; for (it = v8.begin(); it < v8.end()...
The problem is that it is an iterator to 1D vector<int> while b8.begin() gives us an iterator to a 2D vector<vector<int>>. So these iterators are not compatible with each other. That is, you cannot use the iterator it to traverse a 2D vector. You can solve this by changing vector <int> ::iterator it; as shown below: ...
71,201,745
71,201,892
How can I sort two arrays in descending order?
I am trying to write a program that asks the user to enter the number of pancakes eaten for breakfast by 10 different people (Person 1, Person 2, ..., Person 10). I need to modify the program so that it outputs a list in order of number of pancakes eaten of all 10 people. Example: Person 4: ate 10 pancakes Person 3: at...
You can use a std::vector of std::pair to store the Person index and its corresponding value. Then, you can use a comparator function to sort by values. #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { vector<pair<int, int>> person(10); // store the number entered b...
71,202,529
71,202,678
why is there written Process terminated with status -1073741510 on my logs
i was just trying code::blocks a few min ago and I just did a simple c out to see if it works #include <iostream> using namespace std; int main() { cout << "first program" << endl; return 0; } what`s wrong in this??
It's a good habit to convert such negative output values from decimal to hexadecimal and to search online for information: Decimal : -1073741510 Hexadecimal : FFFF FFFF C000 013A So, you can search for "C000013A". This link mentions something might be wrong with the way you start/stop your program. I would advise ...
71,203,108
73,068,951
Enable the writing of ANSI escape codes on a file?
I am struggling with a problem. I searched all around the web and StackOverflow website and found similar questions, but none of them provided me the answer I am searching. I am on a Linux system (Ubuntu) and basically want to know how to write an ANSI escape code in an output file. For example, if I want to write a re...
After all your answers and weeks of practice, the solution for this answer is pretty obvious and is the following: file redirection of ANSI escape sequences manipulation depends on the kind of file you are writing in and you have to manually set the way in which you want to translate the ANSI into the output file, depe...
71,203,472
71,213,036
concatenate the images to single image using opencv C++
I am creating a single image from the video. But I read the video and create frames, then after that rotate the frames and crop the frames and these cropped frames are saved. These cropped frames should be combined to create a single image. So I have appended them in the vector of Mat and then want to concatenate them ...
The only issue I could notice is h = 1 - that makes the height of cropped_image to be only 1 pixel. Since you are not reporting any error message, we can't really tell why it's not working. I recommend you to use the debugger, and iterate the code step by step (use an IDE for that). For building a working example, you ...
71,203,791
71,203,935
Cpp Instance in Instance in... existance
I have some classes in hierarchy. So let's call first class Hardware, it recieves and sends data and each Instance of it wll have some unique parameters. Let it be: class Hardware{ private: SPI_TypeDef** Instance; GPIO_Port* Port; GPIO_Pin Pin; int Settings; public Hardware(); Hardware(GPIO...
And I wonder if instances of Device and their parameters will not be deleted after DeviceArray constructor is closed. And the same is for Hardware (Sender) instances. Yes, instances of the two types will be destroyed, but that doesn't matter. For example the line this->Devices[i] = Device(Ports[i], Pins[i],SPIx); cr...
71,204,006
71,217,473
dll loacation Error by running a testcode
I am learning how to use dlls and how to export them. I have created a small program that calls the different components(classes, methods, functions, ect.. ) of my dll file to use them. When I build the project I get no problem, but when I compile the test code I get this error. Error translation: {The procedure entry...
@YujianYao-MSFT & Kiner_shah I really appreciate your help. I have solved the problem. My problem was that I created the dll file on Friday and then got the idea to change the location of creating the dll file and forgot about it. Then on Monday I copied the old file which does not contain my start() method. So the pro...
71,204,200
71,205,459
std::cout print all digits of float value
I have this function: template<typename T> // T can be float, double or long double void printAllDigits(T value) { std::cout << std::fixed << std::setprecision(999) << value; } It's a dumb implementation to print all digits of a floating point value. This has some problems: I can't guarantee that it works for all...
Assuming that the implementation uses radix 2 for the floating point, if (std::numeric_limits<T>::radix == 2) then writing ALL the decimal digits for ALL possible values would require: std::cout << std::setprecision(std::numeric_limits<T>::digits - std::numeric_limits<T>::min_exponent); I suspect that the formulation...
71,204,325
71,205,326
How to assign variadic/variable arguments in C++
I'm trying to create a function to assign default or input values to several (scalar) parameters using variadic/variable input arguments as: void set_params(const vector<double> &input, int n, ...) { va_list args; va_start (args, n); for (int i = 0; i < n; i++) { if (i < input.size()) { va_arg(args, i...
Instead of using C's va_ stuff, C++ has it's own variadic template arguments, which you should preferably use I'm no expert on this, but it could look a little bit like #include <vector> #include <iostream> template <typename... Arg> void set_params(const std::vector<double> &input, Arg&... arg) { unsigned int i{0...
71,204,468
71,204,817
Problem with BME280 and char arrays on Arduino
I am trying to fill a char array with 1800 characters from digital pin 7 (data from a rain gauge) before reading the air pressure from a BME280 using Ardino UNO. The results are printed with Serial.println over USB. #include <Adafruit_BME280.h> #define DATA 7 Adafruit_BME280 bme; void setup() { Serial.begin(9600...
Looks like you have a stack overflow problem. As you can see in ATMega328 datasheet here or here, you have 2KB RAM only. ATMega328/ATMega328P is usually used as a base MCU for the Arduino UNO board. To check that, you can make array char r[rmax]; as static & fix the buffer overflow problem, as Ian told. Here you can fi...
71,205,603
71,205,727
int abs(int) vs double abs(double)
I'd like to understand the behavior of the following code, from the C++ Standard point of view (GCC 9.3, C++20): #include <cstdlib> template<class> struct type_tester; int main() { type_tester<decltype(abs(0.1))>{}; // int abs(int) overload is selected for some reason! type_tester<decltype(std::abs(0.1))>...
So, int abs(int) is imported to the global namespace, Why? Because the C++ standard allows it to be imported into the global namespace. While double abs(double) is not! Why? Because the C++ standard doesn't require it to be imported into the global namespace. Relevant standard quotes: [headers] Except as noted in...
71,205,695
71,207,949
is lambda capture allowed in c++20 function trailing return type and noexcept operator?
Simple code as below or godbolt has different results from gcc, clang and Visual Studio. auto foo1(int n) -> decltype(([n]() { return n+1; }())) // gcc error: use of parameter outside function body before '+' token { return [n]() { return n+1; }(); } auto foo2(int n) -> decltype(([&n]() { return n+1; }())) // gcc ...
From [expr.prim.lambda.capture]/3: A lambda-expression shall not have a capture-default or simple-capture in its lambda-introducer unless its innermost enclosing scope is a block scope ([basic.scope.block]) or it appears within a default member initializer and its innermost enclosing scope is the corresponding class s...
71,206,859
71,207,894
Handling enum value 0 in protobuf c++
I'm working on a C++17 project that uses protobuf for data serialization, but I come across a problem. I tried to serialize an object defined in protobuf into std::string and the object has only one enum field, when accidentally the value of the field is set to 0, the function SerializeAsString() or SerializToString(st...
This is actually not a problem at all since the parsing will work as expected because this is part of how protobuf handles default values: Also note that if a scalar message field is set to its default, the value will not be serialized on the wire. So because protobuf does not differentiate between a field being set ...
71,206,958
71,214,200
Why wouldn't boost::icl::interval_map add up the value?
Consider the following program: #include <iostream> #include <boost/icl/interval_map.hpp> struct Value { explicit Value(int v) : v(v), is_empty(false) {} Value() : v(0), is_empty(true) {} Value& operator+=(const Value& other) { v += other.v; return *this; } bool operator==(con...
The problem is that bool operator==(const Value& other) const { return is_empty == other.is_empty; } bool operator!=(const Value& other) const { return is_empty != other.is_empty; } make it so that ANY value is "identical". That makes the behaviour unspecified, and likely ends up merging any touching intervals and kee...
71,207,162
71,236,083
Intercepting signals/mach exceptions in a C++ plugin on macOS
I'm working on a suite of plugins for a certain host application, targeting both Windows and Mac (OSX+). The plugins are written in C++. I would like to add crash & exception report handling to them in case the plugin goes rogue. This in order to not bring the whole host app down in case the plugin misbehaves, but g...
The only options on macOS are signal handlers and Mach exception handlers. Both of these mechanisms are process-wide, so would report problems wherever they occurred. If a new signal handler is installed, the old one will not be run. The sigaction() API does return the previously installed one, so it's possible to have...
71,207,351
71,207,707
Is it required to define all forward declarations?
In general, I'm wondering if a program like this, containing a forward-declaration of a class that is never defined, is technically well-formed? class X; int main() {} More specifically, I'm wondering if having a pattern like this // lib.h #pragma once struct X { private: friend class F; }; is safe to write if lib...
According to the standard [basic.odr.def]: Every program shall contain exactly one definition of every non-inline function or variable that is odr-used in that program outside of a discarded statement (8.5.1); The key part is odr-used, which is determined by all the other places in code that may make use of the funct...
71,207,477
71,207,503
What does this header mean in c++?
#if defined(UNICODE) && !defined(_UNICODE) #define _UNICODE #elif defined(_UNICODE) && !defined(UNICODE) #define UNICODE #endif this is the header for the default win32 c++ app on codeblocks
It ensures that both UNICODE and _UNICODE are defined if one of them is.
71,207,967
71,208,303
Arduino sketch with header and code file added with template methods. Caught between 'undefined reference to' and 'redefinition of'
I have a header file declaring a method, and a code file with the implementation. On compile, the compiler errors out with 'undefined reference to...'. If I copy the implementation of the method to the header, it then tells me the method is being redefined in the code file. Surely if it can find the method in the cpp f...
You have a few C++ syntax errors in your code. Templates have to be declared and defined inside header files (there is rare syntax that provides an exception to this, but I won't discuss that here). You are missing parentheses before your 'loop' function definition. You are declaring your Double parameter with the nam...
71,208,273
71,208,464
Dereference pointer from unnamed namespace not working
For a Wii homebrew game engine I'm working on, I have this (shortened) script that handles printing text: #include <grrlib.h> #include "graphics.hpp" #include "Vera_ttf.h" namespace { GRRLIB_ttfFont *font = GRRLIB_LoadTTF(Vera_ttf, Vera_ttf_size); } namespace graphics { namespace module { void print(const char...
Since you have to initialize the library with GRRLIB_Init(), you can provide a similar init function to ensure that your variables are initialized after the library. #include <grrlib.h> #include "graphics.hpp" #include "Vera_ttf.h" namespace { GRRLIB_ttfFont *font = NULL; } namespace graphics { void InitGra...
71,208,777
71,209,144
Why am I getting an undefined reference error while using separate .cpp and .h files for a class?
I am using a simple function to add to integers, the class is declared in the Adder.h file as below class Adder { public: int add (int x, int y); }; Then I have the Adder.cpp file which has the function definition int add (int x, int y) { return x + y; } Then the main.cpp file which calls the function # i...
In your second and final step, you didn't instruct the compiler (linker more exactly) to take into account Adder.o, so your final executable still doesn't know the implementation of Adder::add Try, after getting Adder.o, to run g++ main.cpp Adder.o Also, this may be relevant : Difference between compiling with object a...
71,208,820
71,212,872
C++ polymorphism: how to create derived class objects
I have an abstract base class called BaseStrategy. It contains one pure virtual function calculateEfficiency(). There are two classes ConvolutionStrategy and MaxPoolStrategy which derive from this base class and implement their own specific version of calculateEfficiency(). Here is some code: class BaseStrategy { publi...
You can indeed use runtime polymorphism here: Declare ~BaseStrategy virtual (you are already doing it ;-) If you are never going to instantiate a BaseStrategy, declare one of its methods as virtual pure, e.g. calculateEfficiency (you are already doing it as well!). I would make that method const, since it doesn't look...
71,209,541
71,209,823
QtConcurrent error: attempting to reference a deleted function
I'd like to run simple method in a different thread than the GUI thread inside my Qt application. To do this I'm using QFuture and Qt Concurrent. However, I ran into a compile error: C:\Qt\5.15.2\msvc2019_64\include\QtConcurrent/qtconcurrentstoredfunctioncall.h(58): error C2280: 'QtConcurrent::RunFunctionTask<T>::RunFu...
As noted in the comments, and as indicated in the error message itself, the problem is that your Error class has no default constructor. While there is nothing explicit in the documentation for QtConcurrentRun that indicates this requirement, there is the following in the documentation for QFuture (bold emphasis mine)1...
71,210,227
71,210,282
Full emulation of `intptr_t` with `ptrdiff_t` and `nullptr`?
Given that intptr_t is optional and ptrdiff_t is mandatory, would p - nullptr be a good substitute for (intptr_t)p, to be converted back from a result denoted by n with nullptr + n instead of (decltype(p))n? It's IIUC semantically equivalent on implementations with intptr_t defined, but also works as intended otherwise...
No. ptrdiff_t only needs to be large enough to encompass a single object, not the entire memory space. And (char*)p - (char*)nullptr causes undefined behavior if p is not itself a null pointer. p - nullptr without the casts is ill-formed.
71,210,491
71,210,647
C++ in containered Linux environment: why does attempting to allocate large vector causes SIGABRT or neverending loop instead of bad_alloc?
I am writing in C++ on a Windows machine in three environments: Docker Linux container with Ubuntu - g++ compiler (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0 WSL Ubuntu enviornment on Windows - g++ compiler (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0 Windows - gcc compiler (i686-posix-dwarf-rev0, Built by MinGW-W64 project) 8.1.0 ...
Containers don't have complex memory management logic. What you're seeing is a result of a surprising Linux policy known as memory overcommit. In Linux large allocations do not fail; malloc() always succeeds. The memory isn't actually allocated until you actually attempt to use it. If the OS can't satisfy the need it i...
71,210,560
71,214,240
Flattened Int array C++ (the ends of each integer is translated wrongly)
There is an array of integers, and I want to turn them into an array of separated digits and print them back out as the same sets of integers. ps: reason being, I want to do lots of individual digit calculations, and I want to use this method to separate the digits, and store their "separating indexes" to turn them bac...
Can you use the STL data structures and algorithms? Here's some code: Starting from a vector of ints. Creating a vector of strings from it. Flattening the vector of strings into a vector of int digits. Transforming the vector of strings back into a vector of ints. [Demo] #include <algorithm> // for_each, transform #...
71,210,999
71,211,943
can't get the right answer when multiplying two large numbers using Karatsuba multiplication(recursive Gauss "trick")
I have been trying to implement integer-multiplication problems using strings. The product of smaller numbers is always right but for larger numbers the results are wrong. Can anyone tell me which part of the code is causing the problem? a: 3141592653589793238462643383279502884197169399375105820974944592 b: 27182818284...
You have a simple error in getEqualLength. It should return a.length() or b.length(). Here's the corrected code: //#include <bits/stdc++.h> #include <string> #include <iostream> using namespace std; int getEquallength(string& a, string& b) { int n1 = a.length(); int n2 = b.length(); if (n1 > n2) { ...
71,211,009
71,211,385
Error in setting in event filter : Can not cast to its private base class QObject
I am trying to set event filter for rubber band rectangle zoom in. But getting the following error widget.cpp:29:42: error: cannot cast 'SchematicDesign' to its private base class 'QObject' schematicdesign.h:13:68: note: constrained by implicitly private inheritance here widget.h QT_BEGIN_NAMESPACE namespace Ui { cla...
QGraphicsRectItem does not inherit from QObject, so installEventFilter will not work. You'll want to override sceneEvent (or sceneEventFilter, if you actually want a filter, but it seems like you may just want SchematicDesign to handle the events itself) and use installSceneEventFilter. From the documentation: You can...
71,211,395
71,232,114
visual studio code not running code cause of ofstream
I have set up my Visual Studio Code and it works fine, but when I want to use fstream functions, it doesn't run. Here's an example: #include <iostream> #include <math.h> #include <conio.h> #include <fstream> #include <string> using namespace std; void createfile(); int main(){ int choice; cout << "Enter 1 to ...
I installed mingw again and it worked.
71,211,646
71,211,826
c++ std vector initialize with existing objects
Below is some code that contains some already created Location objects and updates them. Then it needs to construct a std::vector of those objects to pass to other functions. The way I construct the vector looks cleaner as it is a initializer list and is one line, instead of using 3 push_back calls after initializing a...
Is there a vector constructor or another technique to initialize the vector with only 1 copy? If you move the local objects into an array, you can construct the vector from that array, eg: // local objects Location locs[3]{ {1, 2}, {3, 4}, {5, 6} }; // code that updates locs ... // construct vector std::vecto...
71,212,596
71,214,266
OpenMP parallel calculating for loop indices
My parallel programming class has the program below demonstrating how to use the parallel construct in OpenMP to calculate array bounds for each thread to be use in a for loop. #pragma omp parallel { int id = omp_get_thread_num(); int p = omp_get_num_threads(); int start = (N * id) / p; int end = (N * (id + 1))...
You are right. Indeed, (N * ((p - 1) + 1)) / p is equivalent to (N * p) / p assuming p is strictly positive (which is the case since the number of OpenMP thread is guaranteed to be at least 1). (N * p) / p is equivalent to N assuming there is no overflow. Such condition is often useful when the integer division cause s...
71,212,959
71,213,957
How to deal with the sign bit of integer representations with odd bit counts?
Let's assume we have a representation of -63 as signed seven-bit integer within a uint16_t. How can we convert that number to float and back again, when we don't know the representation type (like two's complement). An application for such an encoding could be that several numbers are stored in one int16_t. The bit-cou...
Your question is ambiguous as to whether you intend to truly store odd-bit integers, or odd-bit floats represented by custom-encoded odd-bit integers. I'm assuming by "not knowing" the bit-width of the integer, that you mean that the bit-width isn't known at compile time, but is discovered at runtime as your custom val...
71,213,295
71,213,585
HTTP requests via proxy with boost beast
Is it possible to set a proxy when making HTTP requests using Boost Beast? Using CURL is straighforward. Anyone has done this? Thank you,
Depends on the kind of proxy. There's a socks4 sample in the Asio library distribution (asio/example/cpp{03,11}/socks4). I've written a socks4 client (sync/async) on here: socks4 with asynchronous boost::asio. More recently I extended that for socks5: Is there a native support for proxy connection via socks5 for boost:...
71,213,495
71,213,782
how do you define an exact case constant with a switch statement in c++
I'm learning C++ and I don't fully understand how case works in switch statements. I have the following code: bool accept3() { int tries = 1; while (tries<4) { std::cout<<"Do you want to proceed (y or n)?\n"; char answer = 0; std::cin>>answer; switch(answer) { case 'y'...
When you input any string of characters that begins with n, it still takes that as the 'n' case. Why does it do this? Because you are asking cin to read a single char, so that is what it does. operator>>(char&) ignores leading whitespace, if any, and then reads 1 char. Any subsequent characters, if any, are left in ...
71,213,831
71,213,848
C++ char* as a function parameter
How can I pass a char pointer (char*) to the function func()? #include <iostream> using namespace std; void func(char *var) { cout << var; } int main() { char* test = "Hello World"; func(test); } The compiler says: Initialization: const char[12] cannot be converted to char *
A string literal is a const char[N] array in read-only memory (where N is the number of characters in the literal, plus 1 for the null terminator, so in your case 11+1=12). You can't point a char* pointer (ie, a pointer to non-const data) at a string literal, as that would allow for the possibility of altering read-on...
71,215,301
71,215,373
0xC0000005: Access violation reading location 0x005EF9E4
I am having issues with Handles. I have Bytebeat (music in bytes) playing inside of a DWORD WINAPI function. When I try to terminate and close the thread, it straight up gives me the error in the title. This is my code: #include <windows.h> #pragma comment(lib, "Winmm.lib") DWORD WINAPI bytebeat1(LPVOID) { while (...
When you call TerminateThread, you are basically force-crashing your threads. They still have their own stack allocated and handles to Windows resources. They aren't cleaned up properly, causing your crash. Here's a simple example of how to close your threads without any error. In a real-world scenario this is an unpro...
71,215,477
71,215,533
C++ rvalue assignment what caused this program to crash but lvalue assignment not
I am studying C++ rvalue reference by example. It was like this: Intvec::~Intvec() { log("destructor"); if (m_data) { delete[] m_data; m_data = 0; } } Intvec::Intvec(const Intvec& other) :m_size(other.m_size), m_data(new int[m_size]) { log("copy constructor"); for(size_t i = 0; ...
You are deleting the same m_data pointer twice. The problem starts here: Intvec& Intvec::operator=(const Intvec& other) { log("copy assignment operator"); size_t othersize = other.m_size; int* otherdata = other.m_data; std::swap(m_size, othersize); std::swap(m_data, otherdata); return *this; } ...
71,215,683
71,216,224
Understanding a custom sort comparator - How to know what a true return means
I came across this sort comparator for a vector std::vector<foo> bool comp(foo& x, foo& y) { return x.a < y.a; } Can someone explain what this does ? Does this mean that if a function returns false. foo x will be on the top and y at the bottom. Basically I am trying to understand is how do i know which element ge...
Consider a vector composing of student records like name, age, score. Now you want to sort the vector according to name of students so you pass a custom compare function to the pre-defined sort function which will sort according to the name of student which will look like. bool comp(foo& x, foo& y) { return x.nam...
71,215,776
71,243,149
list does not provide a subscript operator
In C++ I got this error: main.cpp:34:15: error: type 'list<std::string>' (aka 'list<basic_string<char>>') does not provide a subscript operator cout << code[0]; ~~~~^~ 1 error generated. make: *** [<builtin>: main.o] Error 1 Why? I thought square brackets were meant to get the data of an item of an list by...
list does not provide a subscript operator That's correct, std::list does not provide operator[]. (std::vector and std::array both do so.) It would have been possible for std::list to provide an indexing operator, so that lst[10] gives you the 10th (counting from 0) element of the list. But the operation would be O(N...
71,215,918
71,216,843
Wrapper over a templated class with more than one template parameter pack
I'm writting a thin wrapper over a class from a third-party library. My code looks like this: template<typename TArg1, typename... TPack1, typename... TPack2> class MyWrapper<TArg1, TPack1..., TPack2...> : protected ThirdParty<TArg1, TPack1..., TPack2...> { // class is empty }; Where the template parameters of my ...
You don't declare a class template, but something like partial specilization. The correct way should be template <typename T> class MyWrapper : protected ThirdParty<T>; I don't use your template parameters since it contains 2 template parameter pack. The compiler can't know how to split the template arguments. So I go...
71,216,428
71,216,470
Why one statement calls copy constructor while the other one call calls copy-assignment operator?
#include<bits/stdc++.h> using namespace std; class numbered{ public: int value; numbered(){} numbered& operator= (const numbered& n){ this->value=n.value+1; return *this; } numbered (const numbered& n){ this->value=n.value+2; } };...
Statement 1 When you wrote: numbered n2 = n1; //this is initialization and so this uses copy constructor The above statement is initialization of variable n2 using variable n1. And from copy constructor's documentation: The copy constructor is called whenever an object is initialized (by direct-initialization or copy...
71,217,084
71,217,319
Call constructor without object name
In this code (assuming T can be any value type): T foo; T(std::move(foo)); // <--- Is T(std::move(foo)) the construction of an unnamed T from a T&&, or a C-style cast? I think both have the same effect, but I want to know what the expression means in the eyes of the compiler. In particular, it seems the expression So...
what the expression means in the eyes of the compiler Both mean the same thing. The standard calls (T)x an "Explicit type conversion (cast notation)", and T(x) an "Explicit type conversion (functional notation)". "C-style cast" is not an official term, and it's moot whether T(x) (with a single argument) counts as a C...
71,217,152
71,217,254
gcc can't take constexpr address of attribute through member pointer?
I'm trying to take the address of an object's attribute through a member pointer at compile-time. The following code compiles fine on MSVC but not on GCC: #include <optional> struct S { int i = 42; }; int main() { constexpr S obj; constexpr auto member = &S::i; constexpr auto ptr = std::optional(membe...
The result of a glvalue constant expression can only refer to an object with static storage duration. obj doesn't have static storage duration, because it is declared at block scope. You can give obj static storage duration by adding the static keyword at block scope: static constexpr S obj; or by declaring it at name...
71,217,413
71,217,480
Why assignment operator working even when it was forbidden?
I'm struggling with OOP again. I tried to implement signgly linked list, here's the code: template <typename T> class node { T value; node* next; public: node(const T& n) { this->value = n; this->next = nullptr; } ~node() { //is it ok to leave destructor empty in my ...
Templates aren't evaluated unless/until you instantiate them. If you don't use the copy or move constructor, then their bugs don't produce errors.
71,217,529
71,218,085
How to expand the initializer list parameters pack?
Codes like: template <typename... type> void print(type... pack) { ((std::cout << pack << " "), ...); } But I have parameters like: { {1, 2, 3}, {4, 5, 6} } So how can I pass this to the function ? Or, how to expand the parameters pack like this ?
But I have parameters like: { {1, 2, 3}, {4, 5, 6} } You can pack them into std::tuples #include<iostream> #include<tuple> template <typename... Tuples> void print_tuples(Tuples... tuples) { (std::apply([](auto... args) { ((std::cout << args << " "), ...); }, tuples), ...); } Then print_tuples(std::tuple{1,...
71,217,631
71,217,821
How can I read REG_NONE value in C++?
I want to read REG_NONE value from regedit with C++. Here are my codes: #include <iostream> #include <windows.h> using namespace std; //--- Değişkenler ---// //DWORD DWORD dw_Rn_Boyut = MAX_PATH; DWORD dw_Rn_Deger; DWORD dw_Rn_DegerTipi = REG_NONE; //HKEY HKEY hkey_Rn; //LONG LONG long_Rn_Sonuc; int main() { lo...
There is no such thing as a REG_NONE value. On success, your dw_Rn_DegerTipi variable will be updated with the actual value type (in this case, REG_BINARY), and your dw_Rn_Boyut variable will be updated with the number of actual bytes read. Your problem is that you are using the wrong data type for your dw_Rn_Dege vari...
71,218,222
71,218,494
Partial template specialization with auto template argument
I have two enums #include <iostream> enum class E1 : unsigned int { E11 = 1 }; enum class E2 : unsigned int { E21 = 1 }; which have identical underlying values (1) in this case. Next, I have a class C which has two template parameters, an integer j and a value i with type auto. template<int j, auto i> struct...
The auto template argument can be replaced by template<int j,typename T,T i> struct C { C() { std::cout << "none\n"; } }; If you are fine with more typing you can explicitly specify the type of the enum: #include <iostream> enum class E1 : unsigned int { E11 = 1 }; enum class E2 : unsigned int { E21 = 1 }; ...