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
70,755,986
70,756,027
Why is character array processed as true by if statement?
I tried the code given below and found that it actually prints "yes", which means that the character array is taken as true in if statement. But i wonder what is the reason. I mean its an array so did it returned the whole "string". Or it returned its first element that is "s", or it returned its memory location which ...
if (a) In this context, a reference to an array decays to a pointer to the first value of the array. The same thing would happen if a were to get passed as a function parameter. So, here, a is just a pointer. And since it's not a null pointer this always evaluates to true. char a[6] = "string"; This is not really rel...
70,756,433
70,756,662
Can I assign and return without a utility routine?
Is there a way to "assign and return" without creating a utility routine? Here's my code: static int& do_work_(const int* p, int& result) { result = (*p) * 10; return result; } template<typename T> T& assign(const T* p, T& result) { result = *p; return result; } int& do_work(const int* p, bool cond, int&...
If you want to return the result of an assignment operation you can (in most cases) do so without a 'utility' function like your assign, because the assignment expression itself has a value; from cppreference (bolding mine): The direct assignment operator expects a modifiable lvalue as its left operand and an rvalue e...
70,756,996
70,757,224
Default parameter in a function wouldnt compile/link without static inline
i was writing a BST class in C++ and wanted to add a default parameter to a function but, when i tried to the visual studio compiler gave compile and linking errors, so after a bit of googling, i made the root variable static inline and it worked, i want to know what does static inline change in this specific situation...
This is because The keyword this shall not be used in a default argument of a member function and non static member of a class is bound to this (i.e. root is equivalent to this->root). More about default parameters restrictions here. In your case you could have the following workaround: node<T>* findmin(node<T>* temp...
70,757,091
70,757,150
Why does my code do not run the switch statement? (Linked List)
I am a beginner and still learning how to use a switch statement. My professor asked us to make a linked list using a switch statement. I don't really know why the switch statement is not working as intended to be. Hoping someone can help me. OUTPUT The output of the program should look like this Menu [1] Inserting val...
menu does not return any value. You probably want to do this: int menu() { char ah; int ch; cout << "\n----------------------------------"; cout << "\nMenu"; cout << "\n----------------------------------"; cout << "\n[1] Inserting value in the link"; cout << "\n[2] Deleting value in the link...
70,757,795
70,757,959
Why does rvalue object does not get moved to function with rvalue parameter?
I was wondering why std::move to a function with an rvalue parameter was not actually moving anything, but passing by reference instead? Especially when I know it works for constructors. I was running the following code: #include <memory> #include <iostream> void consume_ptr(std::shared_ptr<int> && ptr) { std::cou...
std::move by itself does not actually move anything. That is to say, std::move alone does not invoke any move constructors or move-assignment operators. What it actually does is effectively cast its argument into an rvalue as if by static_cast<typename std::remove_reference<T>::type&&>(t), according to cppreference. In...
70,757,922
70,758,141
C++ copy assignment operator behaviour
I used the code below to test the behaviour of copy assignment operator: #include <iostream> using namespace std; int group_number = 10; // Global class Player { public: explicit Player(const int &g): group(g) { } Player& operator=(const Player& rhs) { cout << "Copy assignment operator called " << en...
You have not copied the data member stamina inside the copy assignment operator. So just add stamina = rhs.stamina; inside the copy assignment operator and you'll get your expected output. So the modified definition of operator= looks like: Player& operator=(const Player& rhs) { cout << "Copy assignment operato...
70,758,414
70,758,709
How to find certain substring in string and then go back to certain character?
I save messages in string and I need to make filter function that finds user specified word in those messages. I've split each message by '\n' so the example of one chat would be: user1:Hey, man\nuser2:Hey\nuser1:What's up?\nuser2:Nothing, wbu?\n etc. Now user could ask to search for word up and I've implemented a sear...
Since you said you split the strings, I image you have a vector of strings where you want to find up for example. You would do something like this for (const auto& my_string: vector_of_strings){ if (my_string.find("up") != string::npos) { // message containing up is my_string } } In case you haven't s...
70,759,474
70,759,579
What would happen if I used a cout statement as the condition for an if statement?
So, my programming instructor asked me to try putting a cout-statement as the condition for an if-statement and see what happens. I tried it (just made a random code) and didn't notice anythimg special. Here's the code. #include<iostream> using namespace std; int main() { int x=1; int y=2022; if(cout<<"Covi...
Prior to C++11, when you write if(cout << "Covid"), there is an implicit conversion to void*. This value is unspecified by the C++ standard, other than if the stream is in an error state, then nullptr is returned. From C++11, the implicit conversion is to bool. false denotes the stream is in an error state, true otherw...
70,759,629
70,759,671
Is there a type in the standard for storing the begin- and end-iterators of a container?
My question is really simple: Is there a type in the standard whose purpose is to store the begin-terator and the end-iterator for a container? I want to return both iterators from a single function. I'm aware I could use std::pair for this but it feels like there would be some type in the standard for this exact purpo...
Is there a type in the standard for storing the begin- and end-iterators of a container? Your description matches closely with the concept of a range. std::ranges::subrange can be created from a pair of iterators. That will be templated based on the iterator type. If you need to hide the iterator type for runtime pol...
70,760,036
70,761,803
How to develop a constexpr implementation of boost::pfr::for_each?
I am using boost::pfr and it's quite impressive the way it uses reflection without any neccesity of macro registering of variables. But the issue I wonder is why boost::pfr::for_each was not declared as constexpr, avoiding in current situation the use of PFR for_each within any constexpr function declared by users. Is ...
This looks like an oversight in the implementation, given that it could easily be constexpr, at least for the C++17 implementation - godbolt example In the meantime you can build your own constexpr one using boost::pfr::structure_tie (which is constexpr) & std::apply: godbolt example template<class T, class F> constexp...
70,760,158
70,760,388
What is the definition of "single statement" in C++?
Identify a statement that is false for the given snippet: int n = 1 + 2; A. 1 and 2 are operands. B. + is operator. C. ; marks the end of a statement in C++. D. It is a single statement.
The answer is C. The grammar production for a for statement is for ( init-statement conditionopt ; expressionopt ) statement So, in for (int i = 0; i < 10; ++i) the first ; ends the "init-statement". The second ; is part of the for loop grammar, and does not end a statement.
70,760,458
70,760,634
Why do I keep getting this error: exception Unhandled : Unhandled exception thrown: read access violation. this was 0x4
I am currently working on the BlackJack project, but there is an error showing "exception Unhandled: Unhandled exception thrown: read access violation. this was 0x4.". I am not quite sure which part I did wrong, and the program sometimes runs normally sometimes shows that exception. In draw_card function, it returns a...
You generate suite = rand() % 4 + 1; This is a random number between 1 and 4 inclusive. You then call getSuit(suite); But getSuit only has switch branches for values between 0 and 3 inclusive: switch (suit) { case 0: return "spades"; break; case 1: return "clubs"; break; case 2: return "diamonds";...
70,761,598
70,761,684
Target-typing in modern C++
When I say target-typing I mean using the type of the receiver variable or parameter as information to infer parts of the code I'm assigning to it. Like for example, in C# you'd write something like this to pass a nullable value or a null (empty) if necessary: void f(int? i) {} void caller(bool b) => f(b ? 5 : nul...
In C++, expressions have types. {} is not, however, an expression. There are a handful of restricted contexts where {} could be used when you'd expect an expression should go there. This doesn't make {} into an expression. ?: is an operation, and its arguments must have types. The type of ?: is derived from the type...
70,761,711
70,761,785
std::variant template deduction when isolating containing type
I have been making a serializer today and am having trouble getting it to work with variants. I have used this process before for various other things where I keep trimming off the type till I get to the one type I need. However, it seems VC++ can't deduce it this time. Here is a complete example of the error. #includ...
The branch with sizeof...(Rest) >= 1 must also be valid when the condition is false, but it isn't. You can get it discarded when the condition is false via if constexpr. Moreoever you were trying to return something but the return type is void. namespace detail { template<typename VariantT, typename T1, typename...
70,762,310
70,806,752
I'm getting undefined reference to `i2c_smbus_read_word_data and 'extern "C"' doesn't fix it
I'm getting the error undefined reference to i2c_smbus_read_word_data(int, unsigned char)` I've tried wrapping a few of my libraries in extern "C" but I get the same error. I tried this after seeing this answer to a similar problem. Regardless of whether I wrap some or all of these include #include <linux/i2c-dev.h>, #...
I did a sudo apt-get update and the problem went away. I also ran a few commands to update the compiler, though it still says my g++ version is 7.5, so that might have also contributed.
70,763,494
70,763,573
What are the downsides to accessing a std::map<std::string, int> using string literals?
I have written a ResourceManager class in C++ that contains a std::map<std::string, Resource>. My current code then accesses these methods using string literals, e.g: // ResourceManager.h class ResourceManager { private: std::map<std::string, Resource> public: void loadResource(std::string_view...
As with any other situation where magic constants are used, it can lead to brittle code, i.e., code that is likely to become broken. In particular, consider what happens if a "background image" resource is loaded once and retrieved from multiple different locations, possibly spanning many source files. If the resource ...
70,763,549
70,772,972
ROS cpp callback without message type
I want to create a ROS node that is able to listen to a topic without knowing its message type. In python, this is possible as can be seen here: https://schulz-m.github.io/2016/07/18/rospy-subscribe-to-any-msg-type/ I tried that and it works like a charm. However, I want to avoid copying the whole message; thus, i need...
By nature, this sort of problem is very pythonic and much harder to work around in c++. That being said, there is one (sort of) solution out there already. Take a look at the ros_msg_parser. The syntax isn't pretty, and I'm not even sure if it's a good idea, but it will let you generate generic subscribers. Example fro...
70,764,818
70,765,683
member "Node::next" (of a friend class) is inaccessible
I am building my own LinkedList, because I need a special Node that holds more data. I specify that my Node class is a friend of the LinkedList class, but it doesn't seem to allow me to access the private variables in the Node class from the LinkedList class. Node.h class Node { private: Node* next; ......
A friend declaration grants access of the specified class to the private members of the declaring class (ie, "that class X over there is a friend of mine, he has permission to use my private stuff"). So, by declaring Node as a friend inside of LinkedList, you are granting Node access to LinkedList's private members, no...
70,764,819
70,764,987
How can i find the integers that can be written as a sum of a power of 2, a power of 3 and a power of 5? C++
So the program must compute all the numbers that can be written as a sum of a power of 2, a power of 3 and a power of 5 below 5.000.000. For example 42 = 16 + 1 + 25 = 2^4 + 3^0 + 5^2. Any idea how can I do this?
you can get all powers of 2 and all powers of 3 and all powers of 5 under 5.000.000. first Then you can try all combinations vector<int> solve(){ const int M = 5000000; vector<int> p_2={1},p_3={1},p_5={1}; while(p_2.back()*2<M)p_2.push_back(p_2.back()*2); while(p_3.back()*3<M)p_3.push_back(p_3.back()*3); while(p_...
70,765,063
70,770,238
V8 Embedding. Cannot print out the `v8::Local` object
In Short I was trying to print out the v8::Local object content, with either of v8/tools/gdbinit and v8/tools/lldb_commands.py helper scripts, I got Empty Line OR Syntax Error messages. Is there anything I've missed? So my question is how can we print the v8::Local object content? Most of configurations are from offic...
For debugging, try using a debug build: use gn args <your_output_dir> to set is_debug = true, then recompile. If you insist on debugging release-mode binaries, you can enable jlh and friends with the v8_enable_object_print = true GN arg, but your experience will likely be weird in other ways (e.g. stepping and breakpoi...
70,765,272
70,766,140
Does std::format() accept different string types for format and arguments?
With printf I can do something like this wprintf(L"%hs", "abc"); where the format is wchar_t * but argument is char *. Is this doable with std::format(), or do I have to convert one to the other prior? When I do std::format(L"{:hs}", "abc"); I get compile error about type mismatch.
It cannot. As per the documentation, the format string matches Python’s format specification, which does not have any magic for directly dealing with different string types or encodings. (Python does everything behind the scenes with CESU-8, IIRC.) This is one of those things where I wish the C++ Standard would just Do...
70,765,285
70,765,307
How to use <stacktrace> in GCC trunk?
From https://github.com/gcc-mirror/gcc/commit/3acb929cc0beb79e6f4005eb22ee88b45e1cbc1d commit, C++ standard header <stacktrace> exists things such as std::stacktrace_entry but is not declared since _GLIBCXX_HAVE_STACKTRACE is not defined neither. I have tried this on https://godbolt.org/z/b9TvEMYnh but linker error is ...
Part of building GCC from source is to run the configure shell script and pass it a bunch of arguments to tell it how to behave. That commit message is telling you that in order to enable this feature, you must add the following configure argument: --enable-libstdcxx-backtrace=yes
70,765,507
70,765,625
Initialize a std::vector of structures to zero
I am guaranteed to initialize a vector of struct with each element initialized to zero with that code ? #include <vector> struct A { int a, b; float f; }; int main() { // 100 A's initialized to zero (a=0, b=0, f=0.0) // std::vector<A> my_vector(100, {}); does not compile std::vector<A> my_vector(1...
Yes it is guaranteed since A{} is value initialization and from cppreference: Zero initialization is performed in the following situations: As part of value-initialization sequence for non-class types and for members of value-initialized class types that have no constructors, including value initialization of element...
70,765,553
70,766,925
CUDA : Shared memory alignement in documentation
We can see on the official Nvidia website that to use multiple arrays of shared memory of unknow size, we can use that code in the kernel: __global__ void myKernel() { extern __shared__ int s[]; int *integerData = s; // nI ints float *floatData = (float*)&integerData[nI]; // nF floats cha...
Yes, you have to worry about alignment. The easiest way to get around this is to sort arrays by alignment from largest to smallest, meaning double + long long -> float + int -> … Since all integral types have sizes and alignments that are powers of 2, you won't waste any space when you pack your arrays like that. Extra...
70,765,743
70,781,619
Return multiple mock objects from a mocked factory function which returns std::unique_ptr
How to return multiple mock objects from a mocked factory function which returns std::unique_ptr? Return(ByMove(...)) cannot be used to return multiple times. Trying to work from this answer: https://stackoverflow.com/a/70751684/3545094 I came up with this: class MyType { public: virtual ~MyType() {} }; class MyTyp...
Stepping gtest/gmock to 1.10 solves this issue.
70,766,319
70,766,404
Get the total number of prime numbers from 1 to 1million
Env: Microsoft Visual Studio. Project type: Run code in a Windows terminal. Print "Hello World" by default. Running ok while get the total number of prime number from 2 to 100000. While not able to get the total number of prime number from 2 to 1000000. It will just return Hello World! Hello World from function(). The...
Your program is probably hanging due too long timeout. As suggested in comments by @NathanPierson it is enough to check primality until i * i <= number which will speedup code greatly. As commented by @Quimby if you use GCC or CLang compiler then it is worth adding -O3 command line compile option, which does all possib...
70,766,398
70,766,758
C++ judgment conditional formatting question
#include <iostream> using namespace std; int foo(int x,int n); int main() { string s = "hello"; int k = 0; if((k - s.size()) < 0) { cout << "yes1"; } int temp = k - s.size(); if((temp) < 0) { cout << "yes2"; } } Anyone can tell me why the output is yes2? Where is the yes1???...
If you look at if((k-s.size())<0), there was no type casting datatype. When you write int temp = k-s.size();, integer datatype convert result as integer value(-5). Then your result "yes2". Change k-s.size() to int(k-s.size()), you will get "yes1" and also "yes2".
70,766,614
70,766,732
C++ - Why does aggregate initialization not work with template struct
This code works, without having to specify a constructor: struct Foo { int a; int b; }; //... int a1, b1; Foo foo = {a1, b1}; If I make Foo a template, it doesn't work. template<typename T1, typename T2> struct Foo { T1 a; T2 b; }; //... int a1, b1; Foo foo = {a1, b1}; It says de...
Since C++20 aggregates have implicitly-generated deduction guide so class template argument deduction works for aggregates too. int a1, b1; Foo foo = {a1, b1}; // works since C++20; T1 and T2 are deduced as int Before C++20, you need to add user-defined deduction guide, e.g. template<typename T1, typename T2> struct F...
70,766,639
70,766,703
opengl window initialization issue
I'm trying to encapsulate GLFW in a class to make my code cleaner. So in my class, I've made the basic window creation but when I execute the program, it always enter in the if statement where I check if the initialization went right or not and I don't know why. This is what I have #include "include/Window.h" #include ...
Make sure to glfwInit(). Also good luck in your jorney learning GL and C++!
70,766,824
70,767,015
How I can run two threads parallelly one by one?
In C++ how i can write two parallel threads which will work one by one.For example in below code it need to print 0 t 100 sequentially.In below code the numbers are printing ,but all are not sequential.I need to print like 1,2,3,4,5,6.....99.If any body know , try to add with sample code also. #pragma once #includ...
You can use ready variable as a condition for condition variable. #include <mutex> #include <iostream> #include <vector> #include <thread> #include <condition_variable> using namespace std; class CuncurrentThread { public: mutex mtx; condition_variable cv; static bool ready; //static bool processed; ...
70,767,210
70,767,557
How to solve undefined reference in main function?
Below is my header file , which declares the function set_params #ifndef PID_H #define PID_H class PID { float _kp,_ki,_kd,_error,_previous_error,_dt; public: void set_params(float kp, float ki, float kd,float error,float previous_error,float dt); }; #endif The following is my pid.cpp, it contains fun...
After you comment, even if including the cpp files is a workaround, please do not do that! You have two acceptable ways. define the method in the class itself in the include file Some IDE by default create an include file containing only the method declarations and put the definitions in an implementation cpp file. Bu...
70,768,157
70,768,389
Variable is not a type
#include<iostream> #include<string> #include<vector> using namespace std; class Course { public: string name; string instructorInCharge; int numberOfStudents; int totalMarks; Course(string u, string v, int p, int q){ this->name=u; this->instructorInCha...
If you want in-class initialization, you may do this: vector<int> studentMarks = vector<int>(numberOfStudents); Now the default constructor will initialize studentMarks with vector<int>(numberOfStudents) when an instance of Course is created. However, this will cause undefined behavior since numberOfStudents is not in...
70,768,599
70,768,679
Pointer to an unspecified variable
The following code gets compiled int v[] = { 0,1,2,3,4,5,6,7,8,9 }; std::cout << v[10] << std::endl; int x; int* ptr = &x; std::cout << *ptr << std::endl; I would like to understand why it was possible to display v[10] and *ptr and also why v[10] and *ptr have the same value. Could you please provide an explanation?
It is undefined behavior but for some of compilers it is how the variables are places in memory. In C/C++ you have direct access to memory (as a huge space with some addressation). x is just placed just after v[]. v[10] means 10th object from start (v is pointing to beginning). If it exceeds the size of container, it w...
70,769,044
70,771,086
How to build cv::Mat from coloured rectangles
My goal is to create yield maps using OpenCV. These yield maps need to be built with coloured rectangles to indicate yield. An example of a Mat built by rectangles here. So is it possible to create a cv::Mat with coloured rectangles? The amount of rectangles isn't constant, thus changes with every use. To make the ques...
OpenCV has cv::hconcat and cv::vconcat. Use them like numpy's hstack/vstack. make sure your parts have the same type (and number of channels). The documentation has a code example. cv::Mat matArray[] = { cv::Mat(4, 1, CV_8UC1, cv::Scalar(1)), cv::Mat(4, 1, CV_8UC1, cv::Scalar(2)), ...
70,769,192
70,776,764
Error using Thrust Zip iterator with device functor
I'm working in a Linux environnement with Cuda and Thrust I got a standard code and i need to transform it Because of this i try to use use zip_iterator for the first time and i have some issues with it. error: function "gridTransform::operator()" cannot be called with the given argument list Does someone know how to r...
gridTransform::operator() needs to take a const Float3 &. I guess Thrust doesn't implement a cast from their internal thrust::detail::tuple_of_iterator_references<float &, float &, float &> to the non-const tuple. The reason for this design decision is probably that for a non-const reference the behavior would be somew...
70,769,321
70,769,505
Can a variable and a method have the same name in C++?
class Controller { bool isBackendActive(); void anotherMethodDoingSomething(); } Can I declare a boolean variable with the same name as a method so that I can use it like this: void Controller::anotherMethodDoingSomething() { bool isBackendActive = isBackendActive(); if (aBoolean && isBackendActive) { ...
Without discussing merits (or lack thereof), yes, you can disambiguate a member from a local variable rather easily. bool const isBackendActive = this->isBackendActive(); or bool const isBackendActive = Controller::isBackendActive(); Will work (and might as well be const correct).
70,769,513
70,769,576
Rotate through a zero based range for positive and negative numbers
Say I have a zero-based range like [0, 1, 2, 3, 4] these are essentially the indexes of an array with size = 5. Is it possible to use a signed integer variable to continuously loop up or down in that range? By up or down, I mean that the variable is permitted to perform arbitrarily many increment or decrement operatio...
C made a really poor decision for % to round towards zero, rather than be a straightforward floor, so the math's clunkier than it has to be. Basically, though, you want (index % size + size) % size. That code starts by chopping off the negative or positive multiples to bring the index into the range (-size, size), adds...
70,769,545
70,770,090
Why in range for loop do begin/end need to be copyable?
When looking at what range-based for loops actually do here: https://en.cppreference.com/w/cpp/language/range-for#Explanation, I see that the begin_expr and end_expr are taken by value, i.e. using copy constructor: auto __begin = begin_expr ; auto __end = end_expr ; Is there a reason the begin/end are taken like that,...
Is there a reason the begin/end are taken like that, or is it an oversight? Wouldn't it be better to either move them: In general no, because such specification could potentially prohibit copy elision. Why in range for loop do begin/end need to be copyable? The initialisation that you quote doesn't generally necess...
70,770,596
70,770,758
C++ Arduino ESP8266 fucntion gives an exception, but running the same directly in loop works fine
I wrote function which should make a url request. function: int updateX(float x) { if(WiFi.status() == WL_CONNECTED) { WiFiClient client; HTTPClient http; String sendStr = "192.168.1.1/updateXdeg?xDegVal="+String(x); http.begin(client, sendStr); int httpCode = http.GET(); http.end(); } ...
My function was declared to return an integer, but I didn't return anything.
70,770,614
70,770,642
C++ camera component can't look up or down
I replaced the standard blue print camera with a c++ version so it works with my other functions that have been converted to c++ m_camera = CreateDefaultSubobject<UCameraComponent>(TEXT("camera")); but for some reason even though the m_camera node is connected to everything the blueprint node was I can’t look up or dow...
Check your values for UseControllerRotation To see details for the camera it has to have a metatag EditAnywhere in the .h UPROPERTY(EditAnywhere) UCameraComponent* m_Camera
70,770,677
70,770,729
why C++ recognizes an uninitialized raw-pointer as true?
Why the following code produces a seg-fault //somewhere in main ... int *pointer; if(pointer) cout << *pointer; ... But slightly changed following code doesn't //somewhere in main ... int *pointer = nullptr; if(pointer) cout << *pointer; ... the question is what in C++ ...
Why C++ Recognizes an uninitialized Raw Pointer (or say a daemon) as true? The behaviour may appear to be so, because the behaviour of the program is undefined. Why the following code produces a SEGMENTATION FAULT!!! Because the behaviour of the program is undefined, and that is one of the possible behaviours. Bu...
70,770,818
70,772,283
Need help to store the record of the current student in the students array
I have to develop a C++ program that reads the student’s name and scores from a file and store them in an array of Student struct objects, then calculate and display each student’s final grade based on the following criteria: midterm exam is counted for 25% of the final grade, final exam is counted for 25% of the final...
You should use the C++ goodies, and learn to be more conservative with the idioms. main should be int main() or int main(int argc, char *argv[]). On some environments you can also use int main(int argc, char *argv[], char **environ) but never use the ugly void main(). Despite being equivalent in C++ int main(void) will...
70,771,600
70,779,270
How do I compare single multibyte character constants cross-platform?
As I am writing a cross-platform application, I want my code to work on both platforms. In Windows, I use this code to compare 2 single characters. for( int i = 0; i < str.size(); i++ ) if( str.substr( i, 1 ) == std::string( "¶" ) ) printf( "Found!\n" ); Now, in Linux, the character is not found. It is f...
Solved using str.compare() and size() of character string: std::string str = "Some string ¶ some text ¶ to see"; std::string char_to_compare = "¶"; for( int i = 0; i < str.size(); i++ ) if( str.compare( i, char_to_compare.size(), char_to_compare ) == 0 ) printf( "Found!\n" );
70,772,159
70,775,635
Executing C functions from C++ file results in linker error: "conflicting declaration with 'C' linkage" and "previous declaration 'C++' linkage
I am attempting to execute a C function from within a C++ file in the Arduino framework. The function I am trying to run, GuiLib_ShowScreen, appears in GuiLib.h and GuiLib.c as follows (the files are massive so for convenience and relevance sake I included only definitions): extern void GuiLib_ShowScreen( const G...
After trying suggestions from the comments, this cleared out the error. I included the library outside the scope after extern "C" and changed the parameters of GuiLib_ShowScreen() to their native types, defined in the library as #define GuiConst_INT16U unsigned short. There was a compatibility issue placing the includ...
70,772,186
70,772,722
Is there an easy way to copy an instance of a class in C++?
I'm trying to make a step based puzzle game (kind of like Baba Is You) and I need to store the state of the level at each step. So I'm using classes for the level, entities and some other things, and I was wondering if I can use default constructors like "Level(Level &&)" or "Level(const Level &)" I saw proposed by aut...
use default constructors like Level(Level &&) or Level(const Level &) Level(Level &&) is the move constructor. You don't want that, because you don't want to damage the original object Level(Level const &) is the copy constructor, which is for making a duplicate of an existing object without altering the original. ...
70,772,241
70,772,600
Xml without indent char but with new line
Is there a way to write xml using boost::property_tree, without indent characters but with new line? Consider this code using namespace boost::property_tree; int main() { ptree tree; ptree* root = &tree.add("root", ""); root->add("something", "yes"); root->add("something2", "no"); write_xml("test.xm...
It seems like you cannot do this. Take a look at: https://github.com/boostorg/property_tree/blob/d30ff9404bd6af5cc8922a177865e566f4846b19/include/boost/property_tree/detail/xml_parser_write.hpp#L76 bool want_pretty = settings.indent_count > 0; and then, at 101 line: if (want_pretty) stream << Ch('\n'); So, if yo...
70,772,672
70,772,833
Order of memory locations
What is the order of memory locations allocated by new operator? For the context, if we are implementing a linked list, then does the new nodes created successively have increasing memory locations?
What is the order of memory locations allocated by new operator? The order is unspecified by the language. The order is what-ever the language implementation chooses it to be. if we are implementing a linked list, then does the new nodes created successively have increasing memory locations? If you use the default ...
70,772,818
70,773,460
how to prevent priority queue from having duplicate values at c++
now I'm trying to use priority queue in c++ like this struct compare { bool operator()(const int &a, const int &b) { return weight[a] < weight[b]; } }; priority_queue<int, vector<int>, compare> q; but I want it to ignore any duplicate values Is it possible using any technique to do this? or should ...
The answer is creating a custom container for the std::priority_queue: template <typename T> class Vector : public std::vector<T> { public: using std::vector<T>::vector; void push_back(const T &value) { if (std::find(this->begin(), this->end(), value) == this->end()) std::vector<T>::push_back(value...
70,773,087
70,773,293
C++ operator overloading [] and return types
I'm just revisiting C++, and I have a question about overloading of the [] operator, and more specifically why my program doesn't work. Given the following code in vec.cpp: double Vec::operator[](unsigned int i) const { return this->values[i]; } double & Vec::operator[](unsigned int i) { return this->values[i]...
In this declaration Vec *a = new Vec(2, avals); there is declared a pointer of the type Vec *. So an expression with the dereferenced pointer has the type Vec. So in this statement cout << a[0] << endl; the expression a[0] has the type Vec. It seems you mean ( *a )[0] or a[0][0]
70,773,117
70,773,336
A letter in a byte? C#
I have an imported C++ method that receives a byte parameter, but according to the documentation, I can send a letter to that parameter, this is the C++ and C# method: int WINAPI Sys_InitType(HID_DEVICE device, BYTE type) public static extern int Sys_InitType(IntPtr device, byte type); This causes me a syntax error i...
Convert.ToByte(string); doesn't do what you think it does, according to the documentation Converts the specified string representation of a number to an equivalent 8-bit unsigned integer. This would work byte random = Conver.ToByte("52"); which will return the byte 52. See here: https://learn.microsoft.com/en-us/dotn...
70,773,154
70,773,428
Why can I use scalar type as the return type of operator->?
From cppreference: The overload of operator -> must either return a raw pointer, or return an object (by reference or by value) for which operator -> is in turn overloaded. However, I tested the following example, and it is accepted by GCC, Clang and MSVC: struct A { int operator->(); }; According to cppreference,...
While the standard doesn't directly place restrictions on the return type of operator->, it does describe what happens when the overloaded -> operator is used: 12.6.5 Class member access [over.ref] A class member access operator function is a function named operator-> that is a non-static member function taking no par...
70,773,702
70,773,810
How to limit the template parameter to only floating point type
Is there a way to limit a template parameter T to a specific type or category? The below code works but I want to make it simpler: #include <iostream> #include <type_traits> template <typename T> constexpr auto func( const T num ) -> T { static_assert( std::is_floating_point_v<T>, "Floating point required." ); ...
The below code works but I want to make it simpler: You may combine abbreviated function templates and the std::floating_point concept for a condensed constrained function template definition: constexpr auto func(std::floating_point auto num) { return num * 123; } Note that this does not include an explicitly spec...
70,774,255
70,774,469
How can I use Unique_ptrs with an class object having std::function as argument in the constructor
Problem Description We have 2 classes A and B. B has the following constructor: B(std::function<std::unique_ptr<A>()> a) I am trying to create a unique_ptr as in std::unique_ptr<B> aPtr = std::unique_ptr<B>(new B(std::function<std::unique_ptr<A>())); I can't figure out how to do it. It's not compiling and I can't real...
auto bPtr = std::unique_ptr<B>(new B( std::function< std::unique_ptr<A>() > () )); // need to close the template ^ // need to construct an instance of ^^ You get the same a bit simpler by using std::make_unique: auto bPtr = std::make_u...
70,774,419
70,774,606
OpenGL depth testing and blending not working simultaniously
I'm currently writing a gravity-simulation and I have a small problem displaying the particles with OpenGL. To get "round" particles, I create a small float-array like this: for (int n = 0; n < 16; n++) for (int m = 0; m < 16; m++) { AlphaData[n * 16 + m] = ((n - 8) * (n - 8) + (...
You're in a special case where your fragments are either fully opaque or fully transparent, so it's possible to get depth-testing and blending to work at the same time. The actual problem is, that for depth testing even a fully transparent fragment will store it's depth value. You can prevent the writing by explicitly ...
70,774,468
70,775,393
Using a union to prevent destruction?
Related: How does =delete on destructor prevent stack allocation? First, I realize this sort of thing is playing with fire, tempting UB. I'm asking to get a better understanding of corner-cases of unions. As I understand it, if I have a class with a c'tor and d'tor and put it in a union, the compiler will force me to t...
[class.dtor]/15 says that a program is ill-formed if a potentially invoked destructor is defined as deleted. [class.base.init]/12 says that a destructor of a potentially constructed subobject of a class is potentially invoked in a non-delegating constructor. [special]/7 says that all non-static data members are potenti...
70,774,914
70,791,799
ld: can't open output file for writing: execs/aligns, errno=2 for architecture arm64
I created a small program to learn some concepts of STL, but when I compile, I get following error: ld: can't open output file for writing: execs/aligns, errno=2 for architecture arm64 clang: error: linker command failed with exit code 1 (use -v to see invocation) Compiled with: g++ --std=c++17 aligns.cpp -o execs/ali...
I have finally found the solution! Folder 'execs' simply didn't exist)))
70,775,025
70,775,136
c++ Two Classes Refering To Each Other
i'm working with c++. I need to create two classes that refering to each other. Something like this: class A { private: B b; //etc... }; class B { private: A a; //etc... }; How can i do that? Sorry for my bad English and thanks you for helping me :)
You can't do that even in principle, because a single A object would contain a B which contains another A, which contains another B and another A ... If you just want a reference, you can simply do class B; // forward declaration class A { B& b_; // reference public: explicit A(B& b) : b_(b) {} }; class B { A ...
70,775,205
70,776,161
Implementing template specialized functions
I'm trying to allow a class to implement an interface, where the interface is templated to either allow an update internally or not. The code looks like this and works if the implementation is within the class declaration. If it is moved out (as shown here), I get a compiler error on Visual Studio 2019, and I can't und...
1. Microsoft-specific syntax The syntax you're using to override GetValue() is not standard c++. class X : public IXQ<EntryType::Read> { public: float IXQ<EntryType::Read>::GetValue() { /* ... */ } } This is a Microsoft-Specific Extension for C++ called Explicit Overrides (C++) and is intended to be used with __in...
70,775,446
70,778,214
Can OpenMP's SIMD directive vectorize indexing operations?
Say I have an MxN matrix (SIG) and a list of Nx1 fractional indices (idxt). Each fractional index in idxt uniquely corresponds to the same position column in SIG. I would like to index to the appropriate value in SIG using the indices stored in idxt, take that value and save it in another Nx1 vector. Since the indices ...
Probably no, but I would expect manually vectorized version to be faster. Below is an example of that inner loop, untested. It doesn’t use AVX only SSE up to 4.1, and should be compatible with these Eigen matrices you have there. The pIndex input pointer should point to the j-th element of your idxt vector, and pSignsC...
70,776,453
70,776,798
What is the difference between __declspec( dllimport ) extern "C" AND extern "C" __declspec( dllimport )
Would there be any difference between both notations when compiling in a .c file or within a .cpp file ?
extern "C" and __declspec(dllimport) are totally orthogonal. extern "C" means that C linkage should be used for that symbol. I.e. no C++ name mangling will be applied. It also limits functions' interfaces to C-compatible things: built-in types, trivial structs, and pointers. Essentially, it tells the compiler and l...
70,776,943
70,777,056
gcc.exe vs cpp.exe vs g++.exe
I am using Visual Studio Code for the coding and for C/C++ I uses MinGW. When I click on configure default build task then I can see various options like C/C++:cpp.exe build active file(compiler: C:/MinGW/bin/cpp.exe),C/C++:g++.exe build active file (compiler: C:/MinGW/bin/g++.exe),C/C++:gcc.exe build active file(compi...
cpp - The C and C++ preprocessor that replaces macros etc. Since you don't have a "Task generated by debugger" for this, it'll most likely be used in the same way for both debug and release builds. gcc - The C compiler that is used to compile C programs. g++ - The C++ compiler that is used to compile C++ programs
70,777,047
70,777,397
Difference in a C++ pointer behavior when incremented in the for loop definition vs inside for loop
I'm onto a leetcode problem (Floyd’s Cycle Detection Algorithm for Linked List) wherein I noticed a strange behavior on the pointer states. When I change the pointer state inside the for loop, the program executes correctly (pointer states move to the right states): ListNode *detectCycle(ListNode *head) { ...
A for (init-statement; condition; iteration-expression) { dostuff(); } maps to { init-statement while ( condition ) { dostuff(); iteration-expression ; } } so we get { slow = head, fast = head; while (fast && fast->next) { slow = slow->next, fast = fast->next->...
70,777,258
70,805,849
Constructing native object from NodeJS Addon
Expectation I want to to implement using a native NodeJS module that works like the javascript module below class C1{ make(){return new C2()} } class C2{} module.exports({C1, C2}) Approach My attempt was, (among some other failed attempts) // so.cpp #include <napi.h> class C1: public Napi::ObjectWrap<C1> { public: ...
You are not allowed to use constructor outside the function that created it - it is an automatic v8::Local reference that is allocated on the stack - you need a persistent reference to do this: #include <napi.h> class C1: public Napi::ObjectWrap<C1> { public: C1(const Napi::CallbackInfo &info); static void Initial...
70,777,344
70,777,836
How to write an infinite sequence compatible with std::ranges?
I would like to write a struct which will generate an infinite sequence of fibonacci numbers in a way compatible with std::ranges and range adaptors. So if I wanted the first 5 even fibonacci numbers, I would write something like this: #include <iostream> #include <ranges> using namespace std; int main() { auto is_...
Edit: As it was pointed out by 康桓瑋 in the comments, there has been a better, cleaner solution presented at Cppcon, link, by Tristan Brindle. I think this could serve as a quick reference to make custom iterator-based generators. By your requirements, something must be a std::ranges::view, meaning it must be a moveable ...
70,778,047
70,782,227
Access pixel value of mask using opencv
I got a problem where I need to access pixels of a opencv Mat image container. I use opencv inRange function to create a mask. In that mask I need to check the value of different pixels, but I won't receive the values I expect to receive. // convert image to hsv for better color-detection cv::Mat img_hsv, maskR, maskY,...
I finally found the answer to my own question. It works when I use uchar: maskR.at<uchar>(position.x, position.y) == 255 I thought this wouldn't work because printing this with std::cout wouldn't give me an output, but the reason for that is that I forgot to cast uchar so it could be printed in the console
70,778,633
70,778,698
Time/space complexity of string splitting/object creation in c++
I'am struggling to figure out the time complexity of a piece of code that I have that takes a user input from 1 line e.g open 1 0, and splits the input via spaces, then allows the user to create a new 'account' object on the heap. I am thinking it is an O(n^2) operation as it contains 2 while loops, plus an additional ...
The complexity is linear in the total user input length on both space and time. All the individual operations iterate over user input only a constant amount of times, including the inner loop. Therefore with n the total length of user input time the time complexity is Theta(n). Similarly memory is only used to store a ...
70,778,770
70,779,029
Launching executable in C++
I wish to launch an executable by API call, but I am not sure if one is supposed to check for executable bit using posix APIs before hand. What is best practice in this regard?
All Posix APIs you'll use to launch a process (e.g. execve() and friends) will do any and all required filesystem permissions checks in a context that is atomic and secure (and doing so in user space is neither). Best practice is to simply use the syscalls that are available. As a side note, you can browse the source c...
70,779,104
70,779,135
How to create a wrapper for `std::make_unique<T>`?
I'd like to create a wrapper for std::unique_ptr<T> and std::make_unique<T> because I think they look ugly and take too long to type. (Yes, I'm that kind of person). I have completed my UniquePtr type alias with no problem but cannot get my MakeUnique to work. It seems to be a bit of a rabbit hole, and was wondering if...
You need to forward properly the values, and you need to expand the pack. First, make it compile: template<typename T, typename... Args> UniquePtr<T> MakeUnique(Args... args) // not recursive { // ^---- no need for <T> when defining function template return std::make_unique<T>(args...); // the .....
70,779,376
70,779,499
How to initialize std::span<const T*>? Problems with const-ness
I am trying to initialize a span<const T*> — that is, a list of pointers to const data. However, the rules for const conversion amongst pointers and span<>'s available constructors are thwarting me. I'm sure there's a way to do it, but I cannot find the right casting/invocation. Aside: I'm actually not using C++20, but...
What's wrong with: #include<span> #include<vector> #include<iostream> using std::cout; using std::endl; int main() { int a = 0; int b = 1; int c = 2; std::vector<int*> pointers = { &a, &b, &c }; std::span<const int*> cspan(const_cast<const int**>(pointers.data()), pointers.size()); std::sor...
70,779,554
70,779,922
Error when trying to linking libcurl in static
I'm new in C++ and I got a problem about linking libcurl in static, I downloaded sources and build it myself: ./configure && make install Everything is okay, I write my cmake file, build my program and run, it's working, so I try to link in static and I got many errors about ssl and thread, so I go back in the doc and...
If you link your app with the static libcurl.a, you have to link your app with all other libs that would be linked with the dynamic libcurl.so. You need to build and link your app with following flags: target_compile_options($(CMAKE_PROJECT_NAME) -pthread) target_link_libraries($(CMAKE_PROJECT_NAME) curl pthread z) Pe...
70,780,287
70,780,904
Negative indexing of 2d array in C++
In the following code section: // Convolution Operation + Sigmoid Activation for (int filter_dim=0; filter_dim<5; filter_dim++) { for (int i=0; i<28; i++) { for (int j=0; j<28; j++) { max_pooling[filter_dim][i][j] =0; conv_layer[filter_dim][i][j] = 0; ...
Wouldn't that be index out of bound? Yes it is out of bounds of the array which leads to undefinded behavior. Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined beh...
70,780,820
70,782,300
How to use bool member function in is_integral_v?
From this cppreference link, is_integral has bool as a member function. How to use it? I could understand other members, and am able to code a simple example as follows. But how to use the bool member function? #include <iostream> #include <type_traits> using namespace std; int main(){ cout << boolalpha; // me...
When you call is_integral<float>(), you are actualy calling the operator bool. The following calls the operator() instead: is_integral<float>()() It can be seen more clear in the following code: std::is_integral<int> x; if (x) { // operator bool std::cout << "true" << std::endl; } std::cout << ...
70,781,635
70,781,930
Making a memory card flipping game in C++
I need some help with this program: Write a program that presents the backs of a number of cards to the player. You should have at least 10 cards. The player selects 2 cards (one at a time), if they match, the player gets a point and the cards remain face up. If they do not match, the cards must turn back over. The gam...
I don't know what these boards' functions are, but if you want to judge if the selected pair is match, you can try this: if (displayLetter[firstChoice / 5][firstChoice % 5] == displayLetter[secondChoice / 5][secondChoice % 5]) { cout << "Match!" << endl; Sleep(2000); } Then you can chan...
70,781,838
70,782,561
c++ virtual inheritance doesn't work, how do I use the multiple parents' members?
Example of using virtual inheritance class AA { public: AA() { cout << "AA()" << endl; }; AA(const string& name, int _a):n(name),a(_a) {}; AA(const AA& o) :n(o.n), a(o.a) {}; virtual ~AA() { cout << "~AA()" << endl; }; protected: int a = 0; std::string n; }; class A1 : public virtual AA { publi...
The result is correct, while the real reason is when you are using virtual inheritance, D ctor first uses AA's default ctor, n is not assigned. If you want to use AA(name, a), you need to explicitly use that in D.
70,781,863
70,784,310
Is it possible to increment setw?
I need to display something that looks like: / - / / - / / / - I currently have the following which does not print the slashes properly. for (int i = 1; i <= numberOfDolls; i++) { for(int j = 1; j <= i; j++) cout << setw(numberOfDolls) << '/' << endl; cout << "-" ...
I am not sure about your doubt but you will get desired output using following: for (int i = 1; i <= numberOfDolls; i++) { for(int j = 1, n=numberOfDolls; j <= i; j++) cout << setw(n--) << '/' << endl; cout <<setw(numberOfDolls-1)<< "-" << endl; }
70,782,051
70,782,100
unique_ptr inside a variant. Is it safe to use?
Id like to ask, is safe having a variant like this? struct A { unique_ptr<T> anything; }; struct B { int x = 0; int y = 0; }; variant<A, B> myVar; myVar = ... A object; myVar = ... B object; myVar = ... another A object; Would the std::unique_ptr destructor be invoked for all compilers? The idea would be ...
The paragraph you quoted is a guarantee by the standard; As with unions, if a variant holds a value of some object type T, the object representation of T is allocated directly within the object representation of the variant itself. Variant is not allowed to allocate additional (dynamic) memory. It means std::variant ...
70,782,158
70,782,833
How to read paragraphs from a file while avoiding the blank space between them into an array?
I have been trying to figure this out. I'm very new to C++. I have tried using this: (what modifications would be needed?) while(!openFile.fail()) { getline(openFile,myArray[size]) } My array size is the same as the number of paragraphs. However, I can't figure out how to consider the paragraphs as one element of th...
I'm not entirely sure what step you're having trouble with, but if I understand correctly. You have a file of some kind that you want to read from and a std::string array initialized to have size equaling the number of lines in the file. You can easily open a file with <ifstream> using open() and then read the file lin...
70,782,217
70,782,235
Qt5 slot lambda why captured local variable is random for the first time lambda is called
In the following code, I think p2 should print 10. But in fact it prints random value. The I starts to understand why it is not 10, with the following (1)-(3) thougths. { int m = 10; // local var m qDebug() << "m0: " << &m; connect(btn2, &QPushButton::clicked, this, [&]() { qDebug() << "m2: " << &m; qDebug(...
Because you capture it by reference. Once the function ends, so does the life-time of all its local variables. The local variables cease to exist. Any reference or pointer to them will become invalid. Using such references or dereferencing such pointers will lead to undefined behavior. The life-time of all variables ca...
70,782,546
70,791,991
Merge and/or Override flags of different configure presets in CMakePresets.json
I have two configure presets in my CMakePresets.json were I would like to merge the flags of the inherit configurePresets (gcc) with the other preset (gcc-arm-embedded) Here is a simplified version: "configurePresets": [ { "name": "gcc", "hidden": true, "cacheVariables": { "CMAKE_CXX_FLA...
First, simplify the inherits entry to: "inherits": ["gcc-arm-embedded"] The resolution order works left to right, never overwriting, but since gcc-arm-embedded inherits from gcc already, there's no need to specify both. So that gets you to this: CMAKE_CXX_FLAGS: "-ffunction-sections -fdata-sections" CMAKE_EXE_LINKER_F...
70,782,552
70,782,820
What is wrong with this code? The answer should be 24 for this question right?
What is wrong with this code? The answer should be 24 for this question right? int t; vector<int>arr={24,434}; for(int i=arr.size()-1;i>=(arr.size()-2);i--) { t=i; } cout<<arr[t];
This loop for(int i=arr.size()-1;i>=(arr.size()-2);i--) is an infinite loop. When i is equal to 0 it is decremented due to the third expression of the loop and becomes equal to -1. And then in this condition i>=(arr.size()-2) as the operand arr.size()-2 has unsigned integer type with the rank not less than the rank o...
70,782,570
70,785,675
Dart/Flutter FFI: Convert List to Array
I have a struct that receives an array of type Float from a C++ library. class MyStruct extends Struct{ @Array.multi([12]) external Array<Float> states; } I am able to receive data and parse it in Dart. Now I want to do the reverse. I have a List<double> which I want to assign to this struct and pass to C++....
There's no way to get around copying elements into FFI arrays. for (var i = 0; i < listObject.length; i++) { my_struct.states[i] = listObject[i]; } This may seem inefficient, but consider that depending on the specialization of listObject, the underlying memory layout of the data may differ significantly from the co...
70,782,643
70,783,249
warning: '*' in boolean context, suggest '&&' instead [-Wint-in-bool-context]?
i've this code (which is pretty all "float"): #define sincf(x) (x == 0.0f) ? (1.0f) : (sinf(M_PI * x) / (M_PI * x)) // ... for (int i = 0; i < num_taps; i++) proto[i] = 2.0f * f * sincf(2.0f * f * (i - m / 2.0f)); // ... why gcc says warning: '' in boolean context, suggest '&&' instead [-Wint-in-bool-context]* for...
After the macro has been substituted, this part 2.0f * f * sincf(2.0f * f * (i - m / 2.0f)); becomes 2.0f * f * (2.0f * f * (i - m / 2.0f) == 0.0f) ? ... and according to operator precedence, the multiplication 2.0f * f * condition will be done before checking if the condition is true (with ?). Like so: (2.0f * f * ...
70,782,888
70,783,876
Strange errors of compiling pcl1.8 with cuda 11.3
System: cuda 11.3, gcc 7.5, boost 1.65.1, pcl 1.8.0 When I compile code that uses PCL library, it shows the following error /usr/include/pcl-1.8/pcl/io/file_io.h(264): error: namespace "boost" has no member "numeric_cast" /usr/include/pcl-1.8/pcl/io/file_io.h(264): error: type name is not allowed /usr/include/pcl-1.8...
Right, I solved it by using normal gcc compiler... DONT USE NVCC!
70,782,966
70,783,451
Why does requires-expression behave differently in template and not-template for checking private member access?
In the following code class A has a private member function f. I want to write a static assertion that will check whether this function is accessible from the current context (as was suggested in the comment to this question). There are 3 similar cases all based on requires-expression: class A{ void f(); }; // #1: acc...
Whilst https://eel.is/c++draft/expr.prim.req.general#1 describes that A requires-expression provides a concise way to express requirements on template arguments the grammar of a requires-expression requires-expression: requires requirement-parameter-list(opt) requirement-body requirement-body: { requirement-seq...
70,783,028
70,783,471
Cast uint8_t-array to readable format
I have this code, which receives a row of byte-values, inserted in an array. How can I show the content "readable" and not like this: R$⸮⸮>⸮⸮⸮ Here's the relevant code: // Read data from UART. uint8_t myData[8]; String myDataString = ""; int length = 0; ESP_ERROR_CHECK(uart_get_buffered_data_len(uart_num, (si...
You are correct with your assumption that myData[i] gets interpreted as ASCII-code, but you can easily convert it into a HEX-string as follows: myDataString += String(myData[i], HEX);
70,783,449
70,783,627
Question about Bitwise Shift in Microsoft C++
I am doing the following bitwise shift in Microsoft C++: uint8_t arr[3] = {255, 255, 255}; uint8_t value = (arr[1] << 4) >> 4; The result of these operations confused me quite a bit: value = 255 However, if I do the bitwise shift separately: value = (arr[i] << 4); value = value >> 4; the answer is different and make...
Expression (arr[1] << 4) will implicitly promote the value of arr[1] to type unsigned int before applying the shift operation, such that the "intermediate" result will not "loose" any bits (cf, for example, the explanation in implicit conversions). However, when you write value = (arr[i] << 4);, then this "intermediate...
70,783,542
70,788,205
Preprocessor definitions based on visual studio configuration type
I am working on a C++ project in Visual Studio 2019, which should have the ability to be compiled as an executable and as a DLL. It is legacy code and contains the preprocessor flags AS_EXE and AS_DLL, which is presumably the flags I need to set. I just don't know how to do this based on different values in Project -> ...
You can use Condition attribute of ItemDefinitionGroup node in your .vcxproj. <ItemDefinitionGroup Condition="'$(Configuration)'=='MyConfigForDLL'"> <ClCompile> <PreprocessorDefinitions>AS_DLL;%(PreprocessorDefinitions)</PreprocessorDefinitions> ... </ClCompile> </ItemDefinitionGroup> <ItemDefinitionGroup C...
70,783,880
70,783,952
Unit tests for C++ criterion
I'm trying to make unit tests with criterion for my C++ code but I can't figure out how to test a function that only print and do not return anything. Here's what I tried: //the function to test #include <iostream> #include <fstream> void my_cat(int ac, char **av) { if (ac <= 1) std::cout << "my_cat: Usag...
With gtest, I think this can help you testing::internal::CaptureStdout(); std::cout << "My test"; std::string output = testing::internal::GetCapturedStdout(); refer from : How to capture stdout/stderr with googletest?
70,784,182
70,784,444
Where exactly are variables stored while vectors store in RAM?
I used this and compiled it: #include <iostream> #include <string> #include <vector> int main() { std::vector<std::string> articles (119999999,"ads"); std::cout << articles[1]; getchar(); return 0; } Then a memory error occurred that the memory is full (because no loss of information occurred). I o...
sizeof(std::string) is typically 32 bytes. Even with short string optimisation, the memory request is a contiguous block of 119999999 * 32 bytes. That's of the order of 4Gb and beyond the capability of your computer. If you require the storage of duplicate strings then consider std::reference_wrapper as the vector elem...
70,784,323
70,785,115
What data type should I use in cv::Mat.at<data_type> when using CV_8SC3, CV_16FC3, CV_16FC1?
When looing through the image and to index the (i, j) , OpenCV provides the method at in cv::Mat. In order to get the correct value of that pixel we need to specify data type carefully ,or we might get some unexpected value. For example, if you use CV_16SC3 to create cv::Mat like below : cv::Mat img(h, w, CV_16SC3, cv...
You can define your own specialization on your demand. cv::Vecxx are just a bunch of shorter aliases for for the most popular specializations of Vec<T,n> So: for CV_8SC3, you might use cv::Vec<char, 3>, for CV_16FC3, you might use cv::Vec<cv::float16_t, 3>. for CV_16FC1, you might use cv::Vec<cv::float16_t, 1>. Besid...
70,784,593
70,823,620
Confused with some Vulkan concept
i have some few questions about Vulkan concepts. 1. vkCmdBindDescriptorSets arguments // Provided by VK_VERSION_1_0 there is prototype: void vkCmdBindDescriptorSets( VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint, VkPipelineLayout ...
Understanding Vulkan uniform layout's 'set' index vkCmdBindDescriptorSets update the current descriptorSet array. the index of set define your shader use the one of array[index].
70,784,873
70,784,960
C++ Using Boost logging with Cmake fails to compile
I am trying to compile C++ using boost logging library with CMake. Heres a simple example my CPP file - logtests.cpp #include <iostream> #include <boost/log/trivial.hpp> #include <boost/log/utility/setup/file.hpp> #include <boost/log/expressions.hpp> namespace logging = boost::log; void init_logging() { logging:...
If you want to use dynamic multi-threaded Boost libraries, you need to set the Boost_USE_STATIC_LIBS and Boost_USE_MULTITHREAD flags before looking for Boost: set(Boost_USE_STATIC_LIBS OFF) set(Boost_USE_MULTITHREAD ON) FIND_PACKAGE(Boost log log_setup) These flags are documented. I also recommend you use the Boost::...
70,784,886
70,787,564
How can I compare system_clock::now() to a local time in c++20?
I am testing a library like follows: std::chrono::system_clock::time_point FromDateTime(const DateTime& dateTime) { std::tm tm{}; tm.tm_year = dateTime.Year - 1900; tm.tm_mon = dateTime.Month - 1; tm.tm_mday = dateTime.Day; tm.tm_hour = dateTime.Hour; tm.tm_min = dateTime.Minute; tm.tm_sec =...
Here's the equivalent C++20 code to your first version of FromDateTime: std::chrono::system_clock::time_point FromDateTime(const DateTime& dateTime) { using namespace std::chrono; auto local_tp = local_days{year{dateTime.Year}/dateTime.Month/dateTime.Day} + hours{dateTime.Hour} + minutes{dateTime.Minute...
70,785,189
70,785,575
How to push pair from priority queue into a 2D array?
I am doing a leetcode problem, and I am required to return a 2d array of results. But I am using a priority queue for that and am unable to move elements to a 2d array. I am not able to come up with a syntax for this. The push_back(), is not working when I try to push the pair in a 2d array. here is the link to the pro...
// if closet should be your answer then its size will be k /* Here we tell how many rows the 2D vector is going to have. And Each row will contain a vector of size 2 */ int row = k; vector<vector<int>>closest(row, vector<int>(2)); int index = 0; while(heap.size() > 0) { pair<int,int>ptr = heap.top().second; ...
70,785,205
70,785,376
Access Derived class (forward declaration) using base class pointer
How to access derived class member variable in my unit test framework(i.e. Gtest_main.cpp) from below scenario. imp.cpp class base{ public: virtual void foo()=0; }; class derived : public base{ public: int abc; // how to access this from Gtest_main.cpp ...
How to access abc in Gtest_main.cpp You can't. Without seeing the full definition of class derived, the compiler has no clue what derived::abc means.
70,785,297
70,998,018
How to make C++ program a Terminal program (UNIX)
I wrote this simple C++ program to compare two strings for a match. Although basic, it's very useful to me as I often need to verify details multiple times a day. I want to initiate the program with a command name e.g. check4match (the program name) so I can run the program in the terminal. #include <iostream> #include...
Ok, as always relatively simple in the end. So chmod a+x didn't work to make the cpp program executable. Simple make filename (without the .cpp extension). Then I moved the newly made .exe file to /usr/local/bin. I had to drag & drop the file, as moving via terminal command wasn't allowed, even with sudo.
70,785,390
74,406,914
Code Runner in vsCode ignoring my compiler arguments in my tasks.json file
I am using vsCode with the C/C++ extension and code runner. I want to compile with a -DLOCAL flag so that I can do #ifdef LOCAL ... #endif The problem is that when I compile my code with the code runner extension, it seems to ignore that flag and the #ifdef doesn't work. However, when I use run and debug, the ifdef wo...
It looks like the code runner is not honoring the tasks.json at all. For me I need to modify the the Code Runner's executorMap by going to: Extensions -> Code Runner -> extension settings -> edit in JSON -> add the -DLOCAL flag in the "cpp" command entry.
70,785,430
70,785,741
How can you catch memory corruption in C++?
I have an std::string which appears to be getting corrupted somehow. Sometimes the string destructor will trigger an access violation, and sometimes printing it via std::cout will produce a crash. If I pad the string in a struct as follows, the back_padding becomes slightly corrupted at a relatively consistant point in...
In general you have to solve problem of code sanitation, which is quite a broad topic. It sounds like you may have either out-of-bound write, or use of a dangling pointer or even a race condition in using a pointer, but in latter case bug's visibility is affected by obsevation, like the proverbial cat in quantum superp...
70,785,853
70,786,413
Iterating over pointer array C++
I am new to C++ but I have an experience in C. Now I am trying to iterate over an array of objects but I am getting segmentation fault because it runs out of the range of the array. I have a class ZombieHorede which keeps a pointer to an array of zombies. #pragma once #include "Zombie.hpp" class ZombieHorde { private...
question is how to iterate over the zombies array in order to not get a segmentation fault. One way to resolve this would be to have a data member called zombieSize that stores the value of N as shown below in the modified snippets: class ZombieHorde { private: static std::string namepool[7]; sta...
70,785,866
70,786,578
C++ coroutine's return_void's and return_value's return type
return_void consider the coroutine's ReturnObject below and note the comments before the method ReturnObject::promise_type::return_void : struct ReturnObject { struct promise_type { int val_{23}; ReturnObject get_return_object() { return {std::coroutine_handle<promise_typ...
[stmt.return.coroutine]/2 says that the expressions promise_object.return_value(...) and promise_object.return_void() (whichever is used by the co_return) shall be of type void. So the return type of either function must be void (if it is used by a co_return). MSVC does correctly reject the program: <source>(31): err...