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
72,822,279
72,822,289
Move an object containing a unique_ptr to vector
Just wondering if there is a way to move an object holding a unique_ptr into a vector of those objects? Example: class A { public: std::unique_ptr<someData> ptr; }; std::vector<A> objects; A myObject; //move myObject to objects??? Now, is there a way I could move myObject into objects and avoiding unique_ptr errors?
You'll need to do std::move: std::vector<A> objects; A myObject; objects.push_back(std::move(myObject));
72,823,028
72,823,422
How to test a protected member from multiple inheritance in GoogleTest?
Imagine I have a Foo class which contains a protected member. Foo is my template base class. Then I have a Bar class, which inherits from Foo. The protected member will be private within Bar. I need to make a test which I need to access the protected member from my Foo base class as seen below. #include <gtest/gtest.h> template <typename T> class Foo { public: int set() { mMember=1; } protected: int mMember; }; class Bar : public Foo<int> {}; namespace { class myTestUT : public Foo<Bar>, public testing::Test { }; TEST_F(myTestUT, how_can_i_test_this){ Bar bar; bar.set(); // ALL GOOD, set() is public! ASSERT_EQ(bar.mMember, 1); // ERROR! mMember is protected! Why can't I access it since I am inheriting it? } } On my test setup I have class myTestUT : public Foo<Bar> which will be a bridge to have access to the Foo members (public and protected), so why can't I access my mMember method? Please note that I know that mMember could be set on the constructor of Foo, but that is not the question here as I created this small snippet to illustrate my problem. I saw this question, but this doesn't contain my problem with multiple-inheritance.
why can't I access my mMember method? It is not my mMember, it is bar's member. GoogleTest manual: When you need to test the private or protected members of a class, use the FRIEND_TEST macro to declare your tests as friends of the class. template <typename T> class Foo { public: void set() { mMember=1; } protected: int mMember; FRIEND_TEST(myTestUT, how_can_i_test_this); }; class Bar : public Foo<int> {}; class myTestUT : public Foo<Bar>, public testing::Test { }; TEST_F(myTestUT, how_can_i_test_this){ Bar bar; bar.set(); ASSERT_EQ(bar.mMember, 1); } You have to remove the unnamed namespace, or use a named namespace. https://godbolt.org/z/3h8q96Ecj
72,823,620
72,874,932
Use SDK (libraries, header files, etc) during creating a C++ ROS package
I am working with Teledyne Lumenera USB Camera. I installed lucam-sdk_2.4.3.94 for Linux on my Ubuntu 18.04. It includes these files: The api folder contains this files: One of the folders is example which contains several examples for working with Teledyne Lumenera USB Camera. Each example in example folder, shows one of the aspects of the camera like setting focus, reading camera info, etc. Each example has a folder that contains some .cpp, .h and one make file. I want to write a C++ ROS node that uses this SDK. First, I create a ROS package in my catkin_ws/src then I copy one of the examples in SDK into the src package folder. When I use catkin_make, it says that it does not recognize lucamapi.h, which is one of the header files in the SDK. My question is two parts: 1- the code that I copied from example folders contains some .cpp and .h files. Also, that has a make file beside themselves. I do not know how to handle the make file. How can I put parameters of the following MakeFile into CMakeList.txt? 2- I do not know how to change CMakeList.txt in my ROS package in order to have access to SDK headers, lib, etc. This is make file for one of of the examples in the SDK: # CC = g++ LD = $(CC) ifndef ARCH ARCH := $(shell uname -m | sed -e s/i.86/i386/ -e s/sun4u/sparc64/ -e s/arm.*/arm/ -e s/sa110/arm/ -e s/x86_64/x86-64/) endif LU_LDFLAGS = -lm -lpthread -lstdc++ PROG = livePreview VERSION = 0.1 INCLUDES = $(LUMENERA_SDK)/include CFLAGS = -DVERSION=\"$(VERSION)\" -I$(INCLUDES) -g CFLAGS += -DLUMENERA_LINUX_API OBJS = ALL_INCLUDES = all lu: $(PROG) clean: rm -f $(PROG) *.o *.core core *.bak *~ livePreview: verify_environment livePreview.o Camera.o $(LD) livePreview.o Camera.o `pkg-config --libs opencv` -llucamapi $(LU_LDFLAGS) -o $@ verify_environment: @if test "$(LUMENERA_SDK)" = "" ; then \ echo "LUMENERA_SDK environment variable is not set!"; \ exit 1; \ fi Camera.o: Camera.cpp $(INCLUDES)/lucamapi.h $(CC) $(CFLAGS) -c Camera.cpp livePreview.o: livePreview.cpp $(INCLUDES)/lucamapi.h $(CC) $(CFLAGS) -c livePreview.cpp
I solved the problem. Working with CMakeList and ROS was confusing. Go to this repository, and read instalation part, then look at CMakeList.txt: https://github.com/farhad-dalirani/lumenera_camera_package
72,823,670
72,823,829
How does conversion constructor work in this case?
How does conversion constructor work? Does the compiler creates a temporary object of myClass and uses the constructor myClass(int i) initialize the temporary object first and then pass the object to function output? OR Does the compiler directly initializes the output() parameter rhs using the myClass(int i) constructor. quite confused with the flow of the conversion constructor. #include <iostream> using namespace std; class myClass { public: myClass(int i) { a = i; } int getA() const { return a; } private: int a; }; void output(const myClass& rhs) { cout << "rhs.getA(): " << rhs.getA() << endl; } int main() { output(120); }
The parameter is a reference. A reference is not an object. It must be bound to some object instead and the type of the object must be compatible with the type of the reference. So yes, a temporary object to which the reference can bind must be created. This temporary object is initialized by a call to the myClass(int i) constructor with 120 as argument. This is also why the program won't compile if you remove the const in void output(const myClass& rhs). Binding a non-const lvalue reference to a temporary is generally not allowed.
72,823,777
72,824,146
Can initializing an object with a prvalue function result call the move constructor?
I started with this piece of code to show the effects of NRVO: struct test_nrvo { bool b; long x[100]; // Too large to return in register }; test_nrvo tester(test_nrvo* p) { test_nrvo result{ p == &result }; return result; } bool does_nrvo() { test_nrvo result(tester(&result)); return result.b; } int main() { __builtin_printf("nrvo: %d\n", does_nrvo()); } Which happily prints nrvo: 1 at -O0 on my compiler. I tried to do a similar thing for RVO for returning a prvalue: struct test_rvo { bool b; test_rvo(test_rvo* p) : b(p == this) {} }; test_rvo tester(test_rvo* p) { return test_rvo(p); } bool does_rvo() { test_rvo result(tester(&result)); return result.b; } int main() { __builtin_printf("rvo: %d\n", does_rvo()); } https://godbolt.org/z/abh9v14bv (Both of these snippets with some logging) And this prints rvo: 0. This implies that p and this are different pointers, so there are at least two different objects (and it is moved from). If I delete the move constructor or make it non-trivial, this prints rvo: 1, so it seems like this elision is allowed. Confusingly the constexpr version fails in GCC, even with a deleted move constructor (where there absolutely could not have been two different objects, so it seems like a GCC bug). Clang seems to just have different behaviour to the non-constexpr version, so it seems like this is permitted-but-not-mandatory copy elision. Is that right? If so, what makes a function call different from other prvalues that must have their moves elided?
Per [class.temporary]/3 RVO on the return value of a function has an exception. If the type has at least one eligible copy or move constructor, all of them trivial, and if it has a trivial or deleted destructor, then the compiler is allowed not to apply RVO and create a temporary in which the function return value is held before it is copied/moved to initialize the variable. test_rvo as shown satisfies these requirements and therefore RVO is not mandatory. With a deleted move constructor the requirements are not satisfied anymore so RVO must apply. That GCC does not do so in constant evaluation context seems like a bug to me as well. In constant evaluation context optional copy elision is never applied ([exp.const]/1), but that shouldn't affect the mandatory elision here. (I am not sure how [class.temporary]/3 is supposed to be handled in constant expressions though, since it is not mentioned.) The Itanium C++ ABI specifies the type property non-trivial for the purpose of calls which mostly overlaps with the (inverse) of the condition in [class.temporary]/3. A return type without this property is passed according to the base C ABI, instead of having RVO applied as the Itanium C++ ABI specifies. The underlying base C API is here the System V x86-64 psABI, which specifies (in 3.2.3 Returning of Values on page 24) that the return value for large structures (MEMORY class) is passed indirectly. Similarly to RVO the caller provides storage for the return value and passes a pointer to that space as additional argument to the function. However the ABI specification also includes the sentence This storage must not overlap any data visible to the callee through other names than this argument. Which I guess is the reason that an additional copy needs to be performed. The ABI requires here that the explicitly provided pointer argument doesn't refer to the implicitly reserved storage for the return value, making RVO impossible.
72,824,003
72,824,136
Overload pattern as a storage
I am trying to use overload pattern as a storage, but I am having trouble appending a new element. Is it actually possible? There is an example - https://godbolt.org/z/ohvY4sx9q PS stackoverflow doesn't allow to paste that much code template<typename... Ts> struct Container : Ts... { template <typename H> auto append(H h) { return Container<Ts..., H> { ( static_cast<Ts>(*this),... ), h }; } };
godbolt Is this what you want? #include <iostream> #include <typeinfo> template<typename... Ts> struct Container : Ts... { void operator()(auto&&... args) { ( [&]() { std::cout << "type => " << typeid(Ts).name() << std::endl; Ts::operator()(std::forward<decltype(args)>(args)...); }(), ... ); } // here just return your new container with appended type template <typename H> auto append(H h) { return Container<Ts..., H> {}; } }; template<class... Ts> Container(Ts...) -> Container<Ts...>; int main() { auto foo = Container { []() { std::cout << "1" << std::endl; }, []() { std::cout << "2" << std::endl; }, }; foo(); auto bar = foo.append([]() { std::cout << "3" << std::endl; }); bar(); }
72,824,256
72,824,494
OpenMP: Assign threads one iteration at a time
Say you have a loop containing a varying number of iterations and 4 cores I understand that #pragma omp parallel for will basically divide the iterations in like this with chunks of size/4 length | T1 | T2 | T3 | T4 | However, in my particular situation, this behavior would be more advantageous. Where each chunk is size/size length. So thread 1 would not get iterations 0..size/4, but instead iterations 0,size/4,2*size/4,3*size/4 |T1|T2|T3|T4|T1|T2|T3|T4|T1|T2|T3|T4|T1|T2|T3|T4| How can I have my code execute like this when the number of iterations is not known until runtime?
What you are describing -- assuming that your heuristic is size/total threads -- is a round-robin scheduling (i.e., static scheduling) with chunk_size = 1. For that you simply need : #pragma omp parallel for schedule(static,1) In this case, it makes no difference if the number of iterations is known (or not) at runtime.
72,824,276
72,824,308
Not getting expected answer using this approach?
I am solving a question on LeetCode , Here is the Link I got the solution but I wanted to know what wrong I am doing here , There are some testCases below or you can visit the link . A helping attempt is always appreciated from my side. class Solution { public: static bool comparator(vector<int>&a,vector<int>&b){ return a[1]>b[1]; } int maximumUnits(vector<vector<int>>& boxTypes, int truckSize) { sort(boxTypes.begin(),boxTypes.end(),comparator); int sum=0; for(int i =0;i<boxTypes.size();i++){ if(truckSize>boxTypes[i][0]){ sum+=boxTypes[i][0] * boxTypes[i][1]; truckSize= truckSize - boxTypes[i][0]; }else{ sum += truckSize * boxTypes[i][1]; } } return sum; } }; TestCases: [[1,3],[2,2],[3,1]] 4 [[5,10],[2,5],[4,7],[3,9]] 10 Expected: 8 91 OutPut: 8 101
You need to add a break in the else statement. If truckSize <= boxTypes[i][0], we just load truckSize boxes and it will no longer accept any boxes (which means we need to break the for loop and return the result). Otherwise, it will continue the for loop, and try to load the following boxes.
72,824,401
72,824,424
Mounting memory buffer as a file without writing to disk
I have a server and needs to feed data from clients to a library; however, that library only supports reading files (it uses open to access the file). Since the data can get pretty big, I rather not write it out to a temporary file, read it in with the library then delete it afterwards. Instead I would like to do something similar to a ramdisk where there's a file in which the content is actually in memory. However, there can be multiple clients sending over large data, I don't think constantly calling mount and umount to create a ramdisk for each client is efficient. Is there a way for me to mount an existing memory buffer as a file without writing to disk? The library does not support taking in a file descriptor nor FILE*. It will only accept a path which it feeds directly to open I do have the library's source code and attempted to add in a function that uses fmemopen; however, fmemopen returns a FILE* with no file descriptor. The internals of the library works only with file descriptors and it is too complex to change/add support to use FILE* I looked at mmap, but it appears to be no different than writing out the data to a file Using mount requires sudo access and I prefer not to run the application as sudo bool IS_EXITING = false; ssize_t getDataSize( int clientFD ) { /* ... */} void handleClient( int clientFD ) { // Read in messages to get actual data size ssize_t dataSize = getDataSize( clientFD ); auto* buffer = new char[ dataSize ]; // Read in all the data from the client ssize_t bytesRead = 0; while( bytesRead < dataSize ) { int numRead = read( clientFD, buffer + bytesRead, dataSize - bytesRead ); bytesRead += numRead; // Error handle if numRead is <= 0 if ( numRead <= 0 ) { /* ... */ } } // Mount the buffer and get a file path... How to do this std::string filePath = mountBuffer( buffer ); // Library call to read the data readData( filePath ); delete[ ] buffer; } void runServer( int socket ) while( !IS_EXITING ) { auto clientFD = accept( socket, nullptr, nullptr ); // Error handle if clientFD <= 0 if ( clientFD <= 0 ) { /* ... */ } std::thread clientThread( handleClient, clientFD ); clientThread.detach( ); } }
Use /dev/fd. Get the file descriptor of the socket, and append that to /dev/fd/ to get the filename. If the data is in a memory buffer, you could create a thread that writes to a pipe. Use the file descriptor of the read end of the pipe with /dev/fd.
72,825,008
72,825,047
Why does my UniquePtr implementation double free?
When I run this program I get a double free for my implementation of unique ptr. Any idea why this happens? #include <iostream> #include <memory> using namespace std; template <class T> class UniquePtr { public: UniquePtr(T* t = nullptr) : t_(t) {} UniquePtr(const UniquePtr&) = delete; UniquePtr& operator=(const UniquePtr& oth) = delete; UniquePtr(UniquePtr&& oth) { std::swap(t_, oth.t_); } UniquePtr& operator=(UniquePtr&& oth) { std::swap(t_, oth.t_); return *this; }; ~UniquePtr() { delete t_; } private: T* t_; }; struct Obj { Obj(int x): x_(x) { cout << "new " << x_ << endl; } ~Obj() { cout << "delete " << x_ << endl; } int x_; }; template <class UP> void test(UP&&) { { UP ptr(new Obj(1)); } { UP ptr(UP(new Obj(2))); } { auto lambda = []() { UP ptr(new Obj(3)); return ptr; }; UP ptr2(lambda()); } } int main() { cout << "unique_ptr" << endl; test(unique_ptr<Obj>()); cout << endl; cout << "UniquePtr" << endl; test(UniquePtr<Obj>()); cout << endl; return 0; } unique_ptr new 1 delete 1 new 2 delete 2 new 3 delete 3 UniquePtr new 1 delete 1 new 2 delete 2 new 3 delete 3 delete 0 free(): double free detected in tcache 2 Aborted
t_ is uninitialised in your move constructor so the moved from pointer ends up pointing to an uninitialised pointer and has undefined behaviour (this will cause problems when the moved from object destructs and deletes the uninitialised pointer). You need: UniquePtr(UniquePtr&& oth) : t_(nullptr) { std::swap(t_, oth.t_); } Or possibly simpler: UniquePtr(UniquePtr&& oth) : t_(std::exchange(oth.t_, nullptr) { }
72,825,894
72,826,111
Get all combinations of changing characters in a sring (C++)
Okay, I've been tearing my hair out for the past 5 hours on this. I'm still new to C++, so bear with me if this is a stupid question. I would like to get all possible character combinations, and put them in a string, in C++. void changeCharInString(std::string &str, int index, char ch) { str[index] = ch; } for (int i = 0; i < globals::numOfValidChars; i++) //numOfValidChars is just sizeof validChars { changeCharInString(test, 0, globals::validChars[i]); //validChars is valid characters, which is an array of lowercase letters and some symbols //'test' is just my testing string for this. } If I wanted all combinations of a three-letter string, manually, what I would do would be: for (int a = 0; a < globals::numOfValidChars; a++) { changeCharInString(test, 0, globals::validChars[a]); //index 0 because first for loop //do something with string 'test' for (int b = 0; b < globals::numOfValidChars; b++) { changeCharInString(test, 1, globals::validChars[b]); //index 1 because second second loop //do something with string 'test' for (int c = 0; c < globals::numOfValidChars; c++) { changeCharInString(test, 2, globals::validChars[c]); //index 2 because third for loop //do something with string 'test' } } } This would print me "aaa" to "___" ('_' being the last special character in my validChars array), including duplicates, e.g. "aa_", "a_a", and "_aa". But, as with all programmers,I want some efficiency, and don't want to manually type out the for loops for myself. My question: does anyone have a method of doing this? I've seen some posts on Google, but didn't really understand them, including that most, if not all, were without duplicates... Thank you all. I hope this wasn't too much of a bother to read <3
You tagged your question as "recursion", so here is an answer that uses recursion: void generate(int idx, string& test) { if (idx == test.size()) { // do something with test } else { for (char c : globals::validChars) { test[idx] = c; generate(idx+1, test); } } } If the size is fixed and known at compile-time, you can use templates and if it is not too large the compiler will create a nice nested loop for you: template <size_t idx> void generate(string& test) { for (char c : globals::validChars) { test[test.size()-idx] = c; generate<idx-1>(test); } } template <> void generate<0>(string& test) { // do something with test } int main() { string test("aaa"); generate<3>(test); }
72,826,399
72,832,684
float pointer in ctypes python and pass structure pointer
I'm trying to pass a structure pointer to the API wrapper, Where the struct is containing float pointer member. I'm not sure that how we can pass float pointer value to the structure. /Structure/ class input_struct (ctypes.Structure): _fields_ = [ ('number1', ctypes.POINTER(ctypes.c_float)), ('number2', ctypes.c_float), #('option_enum', ctypes.POINTER(option)) ] /wrapper/ init_func = c_instance.expose_init init_func.argtypes = [ctypes.POINTER(input_struct)] #help(c_instance) inp_str_ptr = input_struct() #inp_str_ptr.number1 = cast(20, ctypes.POINTER(ctypes.c_float)) # want to pass pointer inp_str_ptr.number1 = 20 # want to pass as float pointer inp_str_ptr.number2 = 100 c_instance.expose_init(ctypes.byref(inp_str_ptr)) c_instance.expose_operation()
You can either create a c_float instance and initialize with a pointer to that instance, or create a c_float array and pass it, which in ctypes imitates a decay to a pointer to its first element. Note that ctypes.pointer() creates pointers to existing instances of ctypes objects while ctypes.POINTER() creates pointer types. test.c - for testing #ifdef _WIN32 # define API __declspec(dllexport) #else # define API #endif typedef struct Input { float* number1; float number2; } Input; API void expose_init(Input* input) { printf("%f %f\n",*input->number1, input->number2); } test.py import ctypes class input_struct (ctypes.Structure): _fields_ = (('number1', ctypes.POINTER(ctypes.c_float)), ('number2', ctypes.c_float)) c_instance = ctypes.CDLL('./test') init_func = c_instance.expose_init # Good habit to fully define arguments and return type init_func.argtypes = ctypes.POINTER(input_struct), init_func.restype = None inp_str_ptr = input_struct() num = ctypes.c_float(20) # instance of c_float, similar to C "float num = 20;" inp_str_ptr.number1 = ctypes.pointer(num) # similar to C "inp_str_ptr.number1 = &num;" inp_str_ptr.number2 = 100 c_instance.expose_init(ctypes.byref(inp_str_ptr)) # similar to C "float arr[1] = {30}; inp_str_ptr = arr;" inp_str_ptr.number1 = (ctypes.c_float * 1)(30) c_instance.expose_init(ctypes.byref(inp_str_ptr)) Output: 20.000000 100.000000 30.000000 100.000000
72,826,538
72,831,701
binding reference of type const node*& to node*const
I am trying to implement a generic tree and in the function getSizeRecursive line 1why cannot i use const node* &root. Similarly, i am getting the same mistake in line 2.The compiler is giving an error which i am not able to comprehend. graph.cpp: In function 'int getSizeRecursive(const node*&)': graph.cpp:56:40: error: binding reference of type 'const node*&' to 'node* const' discards qualifiers 56 | for(const node* &child : root->children) // line 2 | ^~~~~~~~ graph.cpp: In function 'int main()': graph.cpp:69:36: error: binding reference of type 'const node*&' to 'node*' discards qualifiers 69 | cout << getSizeRecursive(t.root) << endl; | ~~^~~~ graph.cpp:51:35: note: initializing argument 1 of 'int getSizeRecursive(const node*&)' 51 | int getSizeRecursive(const node* &root){ // line 1 | ~~~~~~~~~~~~~^~~~ [Finished in 2.9s] #include <iostream> #include <vector> #include <stack> using namespace std; class node{ public: int data; vector<node*> children; node(int val){ data = val; // this->data = data } ~node(){ for(int i = 0 ;i<children.size();i++){ if(!children[i]) delete children[i]; } } }; class GenericTree{ public: node* root; // line 3 int size; GenericTree(vector<int> nums){ stack<node*> st; size = 0; for(int i = 0;i<nums.size();i++){ node *n = new node(nums[i]); if(i == 0){ root = n; st.push(n); ++size; }else{ if(n->data == -1){ st.pop(); }else{ // cout << "In me" << endl; st.top()->children.push_back(n); st.push(n); ++size; } } } } // tells us the number of nodes int getSize(){ return size; } }; int getSizeRecursive(const node* &root){ // line 1 if(root->children.size()==0) return 1; int size = 0; for(const node* &child : root->children) // line 2 size += getSizeRecursive(child); return size+1; } int main(){ #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); freopen("error.txt","w",stderr); #endif vector<int> v{10,20,-1,30,50,-1,60,-1,-1,40,-1,-1}; GenericTree t(v); // node that tree has been created cout << t.size << endl; cout << getSizeRecursive(t.root) << endl; return 0; } What i can understand from this is that compiler is not able to bind the reference to pointer to const node to const pointer to node but my question is that why it is taking t.root as const pointer to node whereas in actual it is just a pointer to node(see line no 3). I am novice in c++. Any help would be appreciated. EDIT: The reason i have used const* & root is because i did not want to pass a copy of root to getSizeRecursive but during that since i have passed by reference i have used const so that this reference just only reads the root pointer and not modify it.
Let's see the reason for getting each of the error on case by case basis. Moreover, i'll try to explain things in steps. Case 1 Here we consider the 1st error due to the statement: for(const node* &child : root->children) Now to understand why we get error due to the above statement, let's understand the meaning of each term in step by step manner: Step 1: root is a non-const lvalue reference to a non-const pointer to const node. This means that we're allowed to change the pointer to which root refers(since we've a nonconst lvalue ref) but we're not allowed to change the actual node object to which that pointer is pointing. Step 2 root->children is const vector<node*> since we're not allowed to change the node object to which the pointer is pointing as discussed in step 1 above. Basically, it is as if the pointed to object is itself const which in turn means its data members are treated as const as well. And as children is a data member so it is treated as const and thus root->children is const vector<node*>. Note the conclusion of this step is that we have a const vector with elements of type node*. Step 3 Now, const node* &child means that child is a non-const lvalue reference to a nonconst pointer to a const node. Again, this means that we're allowed to change the pointer residing inside the vector. But this is a problem because we learnt from step 2 above that we've a const vector<node*> meaning that we should not be allowed to change the pointer residing inside the vector. And hence you get the mentioned error. Solution to case 1 To solve this you need to make sure that there is no way to change the pointer residing inside the const vector by adding a low-level const as shown below: //-------vvvvv--------------------------->const added here for(node*const &child : root->children) The above works because now child is a lvalue reference to a const pointer to a nonconst node object. Case 2 Here we consider the 2nd error due to the expression: getSizeRecursive(t.root) Here the passed argument t.root is a node* while the parameter is a const node* &. Now, the passed argument is implicitly convertible to const node* but result of that conversion will be an rvalue. But since the parameter root is an nonconst lvalue reference to a non-const pointer to const node it cannot be bound to an rvalue. This is basically the same error that you will get using: node *ptr; const node*& ref = ptr; //will produce the same error saying: error: cannot bind non-const lvalue reference of type ‘const int*&’ to an rvalue of type ‘const int*’ Solution to Case 2 Basically, a given type T can be bound to T& or T const& while a given type const T can be bound to T const&. And in your example, the passed argument is node* meaning it can be bound to both node*& as well as node*const&. To solve this you can make the lvalue reference to a const lvalue reference as shown below: node *ptr; //---vvvvv--------------->const added here node*const& ref = ptr; In your example, this means: //------------------------vvvvv--------->const added here int getSizeRecursive(node*const &root){ // line 1 Working demo
72,826,704
72,826,957
From boiler plate code to template implementation
I am implementing a finite state machine where all possible states are stored within a std::tuple. This is a minimum compiling example of the problem I am facing and its godbolt link https://godbolt.org/z/7ToKc3T3W: #include <tuple> #include <stdio.h> struct state1 {}; struct state2 {}; struct state3 {}; struct state4 {}; std::tuple<state1, state2, state3, state4> states; template<size_t Index> void transit_to() { auto state = std::get<Index>(states); //Do some other actions over state.... } void transit_to(size_t index) { if (index == 0) return transit_to<0>(); if (index == 1) return transit_to<1>(); if (index == 2) return transit_to<2>(); if (index == 3) return transit_to<3>(); } int main() { for(int i=0; i<=3; ++i) transit_to(i); } In my case, I would like to change the void transit_to(size_t index) implementation to some template construction where all the boiler plate code can be simplified in case I add new states during development. The only constraints are: Use C++17 or below (sorry, no c++20 fancy features please). Do not change interface (do not propose accessing by type or so on things).
If you only want to avoid adding another line like if (index == 4) return transit_to<4>(); when you add a new state, e.g. struct state5, you may implement transit_to(std::size_t) like this: // Helper function: Change state if I == idx. // Return true, if the state was changed. template <std::size_t I> bool transit_if_idx(std::size_t idx) { bool ok{false}; if (idx == I) { transit_to<I>(); ok = true; } return ok; } template <std::size_t... Is> bool transit_to_impl(std::size_t idx, std::index_sequence<Is...>) { return (transit_if_idx<Is>(idx) || ...); } void transit_to(std::size_t index) { constexpr static auto tupleSize = std::tuple_size_v<decltype(states)>; [[maybe_unused]] auto const indexValid = transit_to_impl(index, std::make_index_sequence<tupleSize>{}); assert(indexValid); // Check if index actually referred to a valid state }
72,827,366
72,829,177
C++ output producing random long integers
I recently coded a question, and I have debugged and figured out where the problem is but cannot quite place a finger on it. My program aims to merge groups of sectors if they overlap or are next to each other, but the last section is scrambling the output. #include <cstdio> using namespace std; int main() { freopen("beachin.txt", "r", stdin); freopen("beachout.txt", "w", stdout); int n, u, k, x; scanf("%d %d %d %d", &n, &u, &k, &x); int umbrellas[u][2]; for (int i = 0; i < u; i++) { scanf("%d %d", &umbrellas[i][0], &umbrellas[i][1]); } int groups[u][2]; int len = 0; for (int i = 0; i < u; i++) { int s1 = umbrellas[i][0]; int e1 = umbrellas[i][1]; int found = false; for (int a = 0; a < len; a++) { int s2 = groups[a][0]; int e2 = groups[a][1]; if ((s1 <= e2 && s1 >= s2) || (e1 >= s2 && e1 <= e2) || (s1 <= s2 && e1 >= e2)) { int start, end; if (s1 < s2) start = s1; else start = s2; if (e1 > e2) end = e1; else end = e2; groups[a][0] = start; groups[a][1] = end; found = true; } } if (found == false) { len++; groups[len][0] = s1; groups[len][1] = e1; } } int largest = 0; // scramble bit here from for loop for (int i = 0; i < len; i++) { int current = groups[i][1]-groups[i][0]+1; if (current >= largest) largest = current; } printf("%d\n", largest); return 0; } My input for this is 7 2 5 2 4 5 5 6 The expected answer is 2, but the output varies between 2 and random long numbers like 1550870207. Does anyone know why this is happening? Note: If it's any help, problem statement is here
Pointing out some issues with the code above, many of which you can get reported by using compiler options: umbrellas[u][2] and groups[u][2]: these are variable length arrays; they're not standard C++. n, k, and x are declared, read from, but never used later on. groups is 1) not initialized, 2) filled only for groups[1], so that groups[0] values remain undefined (at if (found == false) block), and 3) accessed both for groups[0] and groups[1] (at bottom for loop). len is incremented before being used; in the second iteration of the top for loop, the if (found == false) loop is executed twice, so the second time you access groups[2]; that's an out of bounds access. Check it here. I've modified your code initializing umbrellas at the point of declaration, and using fixed length arrays for umbrellas and groups. #include <fmt/core.h> int main() { int umbrellas[2][2]{ { 4, 5 }, { 5, 6 } }; int groups[2][2]{}; int len{}; for (int i = 0; i < 2; i++) { fmt::print("*** i = {}\n", i); int s1 = umbrellas[i][0]; int e1 = umbrellas[i][1]; bool found{ false }; for (int a = 0; a < len; a++) { int s2 = groups[a][0]; int e2 = groups[a][1]; if ((s1 <= e2 && s1 >= s2) || (e1 >= s2 && e1 <= e2) || (s1 <= s2 && e1 >= e2)) { int start{ (s1 < s2) ? s1 : s2 }; int end{ (e1 > e2) ? e1 : e2 }; groups[a][0] = start; groups[a][1] = end; found = true; } } if (not found) { len++; fmt::print("\tAccessing groups[{}]\n", len); groups[len][0] = s1; groups[len][1] = e1; } } int largest = 0; // scramble bit here from for loop for (int i = 0; i < len; i++) { int current = groups[i][1] - groups[i][0] + 1; if (current >= largest) { largest = current; } } fmt::print("==> largest = {}\n", largest); } // Outputs: // // *** i = 0 // Accessing groups[1] // *** i = 1 // Accessing groups[2] // ==> largest = 2
72,827,398
72,828,942
MPI send and receive large data to self
I try to send and receive a large array to self-rank using MPI. The code works well for small arrays (array size <10000) when I further increase the array size to 100000, it will deadlock. Here is my code: #include <stdio.h> #include <stdlib.h> #include <mpi.h> int main(int argc, char *argv[]) { MPI_Init(&argc, &argv); int size; MPI_Comm_size(MPI_COMM_WORLD, &size); int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Status stat; int N = 100000; // Allocate memory for A on CPU double *A = (double*)malloc(N*sizeof(double)); double *B = (double*)malloc(N*sizeof(double)); // Initialize all elements of A to 0.0 for(int i=0; i<N; i++){ A[i] = 0.0; } int tag1 = 10; int tag2 = 20; //printf("rank=%d",rank); MPI_Send(A, N, MPI_DOUBLE, 0, tag1, MPI_COMM_WORLD); MPI_Recv(B, N, MPI_DOUBLE, 0, tag1, MPI_COMM_WORLD, &stat); MPI_Finalize(); return 0; } I compile the code by: mpicc command for the run: mpirun -np 1 ./
That's the definition of send and receive: they are blocking. The statement after the send will not execute until the send has been successfully completed. The safe way to solve this is using MPI_Isend and MPI_Irecv. The case for a small messages which don't block is an optimization that is system dependent and you can not count on it.
72,827,565
72,830,084
How to get 2 dimensional array from file (C++)
I'd like to input 2 dimensional array from text file. But my code doesn't work.. #pragma disable (warnning:c4996) #include<cstdio> #include<cstring> #include<iostream> #include<fstream> #include<conio.h> int main() { std::ifstream arrival; std::ifstream departure; arrival.open("arrival.txt"); departure.open("departure.txt"); int i, j, l = 0; char temp; if (arrival.is_open() && departure.is_open()) { temp = arrival.get(); while (temp != EOF) { if (temp == '\n') l++; temp = arrival.get(); } } else printf("error"); // file read int** arr = new int*[l]; for (i = 0; i < l; i++) arr[i] = new int[3]; for (i = 0; i < l; i++) { for (j = 0; j < 3; j++) arrival >> arr[i][j]; } for (i = 0; i < l; i++) { for (j = 0; j < 3; j++) printf("%d ", (int)arr[i][j]); } _getch(); delete[] arr; arrival.close(); departure.close(); return 0; } this is my code, and arrival 2018 01 05 2018 02 03 2019 04 03 2019 08 08 2020 07 08 2018 03 28 2018 05 04 2018 08 30 2019 01 06 2019 09 21 2020 02 18 this is the text file. I surmise in arrival >> arr[i][j]; this part, it doesn't get value from the file. I have no idea how to solve this problem.
This is what you can do with the 4 'basic' libraries vector, string, fstream and iostream. It is an example for "arrivals.txt" only: #include<vector> #include<string> #include<fstream> #include<iostream> int main() { std::ifstream arrivals; // open the file arrivals.open("arrivals.txt"); std::vector<std::vector<int>> matrix; // 2D container int l=0; std::string unused; while (std::getline(arrivals,unused)) // count the lines ++l; arrivals.clear(); // go back to start arrivals.seekg(0); matrix.resize(l); // resizing matrix for (int i=0; i<l; i++) { // fill the matrix matrix[i].resize(3); // resizing row for (int j=0; j<3; j++) arrivals >> matrix[i][j]; } arrivals.close(); // close the file for (int i=0; i<l; i++) { // print the matrix for (int j=0; j<3; j++) printf("%02d ",matrix[i][j]); printf("\n"); } } The most important things to remember are to resize the vector before filling out a new element (easier than dynamic allocation!) to go back to the start of the text file after counting the lines (you could if you want, also close the file and open again for reading).
72,827,569
72,828,326
How can I read message by message with recv in an AF_UNIX socket with C/C++?
I am trying to write a client for my AF_UNIX server. The server occasionally does a write(fd, buffer, bufferSize); where the message always ends in a newline. Now, I want a C client to read it, message by message. With bash, it's possible to do something like this: socat - UNIX-CONNECT:/tmp/myepicsocket.sock | while read line; do handle $line; done How would I go about implementing this in C/C++? I've tried a simple char buffer[1024]; // my sent messages are max 1024 bytes size_t recieved = recv(socketfd, buffer, 1024, NULL); std::string messageRecieved(buffer); messageRecieved = messageRecieved.substr(0, messageRecieved.find_first_of('\n')); in a loop, but it seems like recv() gets the message from the beginning of the "file" (meaning once the first message is sent, it will keep spamming that first one) is there a way to read it line by line, message by message, or flush?
recv(socketfd, buffer, 1024, NULL); With stream sockets, like AF_UNIX sockets, recv() is equivalent to read(). That's what makes them "stream" sockets. So, for all practical matters, this is: read(socketfd, buffer, 1024); And just like with a regular file you have no guarantees whatsoever that this reads only up until the first newline. If the peer managed to write two short messages before you get around here, this read() will cough up both of them, at once, and place them into the buffer. So what to do? Well, the answer here is the same answer this question always has: write C++ logic to implement it. The buffer needs to be persistent. You need to keep track of how many "unread" characters exist in the buffer, and the buffer is effectively "initialized" to an empty state by setting the unread count to 0. Each time your code decides to read a "line", it checks if the buffer contains anything, and that "anything" includes a newline. If so, there's your line. Pull it out of the buffer, and update the contents of the buffer, and the unread count, to reflect that this "line" is no longer there. If there isn't a newline in there, only then you read from the socket, and append what's read after the buffer's existing contents, so if the previous read left ended with a partially read line, this will correctly reassemble the pieces. Then go back to Step 1. Of course, if the buffer carries a fixed size, like 1024 bytes, there's a possibility that you'll read 1024 characters without seeing a newline. You don't have anywhere to read() anything more, into. You'll need to decide how to handle that situation, and implement the appropriate logic for that too. And you'll also need to figure out what you will do if your read() or recv() fails or indicates that the socket is closed. So that's the most direct and the simplest way of handling that. Another approach, that involves slightly more advanced C++ knowledge and expertise is to implement your own subclass of std::streambuf that uses the socket as the underlying data source, and override the appropriate methods, then use it to construct a std::istream, and then simply use std::getline() whenever you feel the need to pull out the next line out of it.
72,827,759
72,834,067
Is using ranges in c++ advisable at all?
I find the traditional syntax of most c++ stl algorithms annoying; that using them is lengthy to write is only a small issue, but that they always need to operate on existing objects limits their composability considerably. I was happy to see the advent of ranges in the stl; however, as of C++20, there are severe shortcomings: the support for this among different implementations of the standard library varies, and many things present in range-v3 did not make it into C++20, such as (to my great surprise), converting a view into a vector (which, for me, renders this all a bit useless if I cannot store the results of a computation in a vector). On the other hand, using range-v3 also seems not ideal to me: it is poorly documented (and I don't agree that all things in there are self-explanatory), and, more severely, C++20-ideas of ranges differ from what range-v3 does, so I cannot just say, okay, let's stick with range-v3; that will become standard anyway at some time. So, should I even use any of the two? Or is this all just not worth it, and by relying on std ranges or range-v3, making my code too difficult to maintain and port?
Is using ranges in c++ advisable at all? Yes. and many things present in range-v3 did not make it into C++20, such as (to my great surprise), converting a view into a vector Yes. But std::ranges::to has been adopted by C++23, which is more powerful and works well with C++23's range version constructor of stl containers. So, should I even use any of the two? You should use the standard library <ranges>. It contains several PR enhancements such as owning_view, redesigned split_view, and ongoing LWG fixes. In addition, C++23 brings not only more adapters such as join_with_view and zip_view, etc., but also more powerful features such as pipe support for user-defined range adaptors (P2387), and formatting ranges (P2286), etc. The only thing you have to do is wait for the compiler to implement it. You can refer to cppreference for the newest compiler support.
72,827,897
72,828,002
Why doesn't std::istream_iterator< std::string_view > compile?
Why can't GCC and Clang compile the code snippet below (link)? I want to return a vector of std::string_views but apparently there is no way of extracting string_views from the stringstream. #include <iostream> #include <sstream> #include <string> #include <string_view> #include <vector> #include <iterator> #include <algorithm> #include <ranges> [[ nodiscard ]] std::vector< std::string_view > tokenize( const std::string_view inputStr, const size_t expectedTokenCount ) { std::vector< std::string_view > foundTokens { }; if ( inputStr.empty( ) ) [[ unlikely ]] { return foundTokens; } std::stringstream ss; ss << inputStr; foundTokens.reserve( expectedTokenCount ); std::copy( std::istream_iterator< std::string_view >{ ss }, // does not compile std::istream_iterator< std::string_view >{ }, std::back_inserter( foundTokens ) ); return foundTokens; } int main( ) { using std::string_view_literals::operator""sv; constexpr auto text { "Today is a nice day."sv }; const auto tokens { tokenize( text, 4 ) }; std::cout << tokens.size( ) << '\n'; std::ranges::copy( tokens, std::ostream_iterator< std::string_view >{ std::cout, "\n" } ); } Note that replacing select instances of string_view with string lets the code compile.
Because there is no operator >> on std::stringstream and std::string_view (and std::istream_iterator requires this operator). As @tkausl points out in the comments, it's not possible for >> to work on std::string_view because it's not clear who would own the memory pointed to by the std::string_view. In the case of your program, ss << inputStr copies the characters from inputStr into ss, and when ss goes out of scope its memory would be freed. Here is a possible implementation that uses C++20's std::ranges::views::split instead of std::stringstream. It only supports a single space as the delimiter. #include <iostream> #include <sstream> #include <string> #include <string_view> #include <vector> #include <iterator> #include <algorithm> #include <ranges> [[ nodiscard ]] std::vector< std::string_view > tokenize( const std::string_view inputStr, const size_t expectedTokenCount ) { constexpr std::string_view delim { " " }; std::vector< std::string_view > foundTokens { }; if ( inputStr.empty( ) ) [[ unlikely ]] { return foundTokens; } foundTokens.reserve( expectedTokenCount ); for ( const auto token : std::views::split( inputStr, delim ) ) { foundTokens.emplace_back( token.begin( ), token.end( ) ); } return foundTokens; } int main( ) { using std::string_view_literals::operator""sv; constexpr auto text { "Today is a nice day."sv }; const auto tokens { tokenize( text, 4 ) }; std::cout << tokens.size( ) << '\n'; std::ranges::copy( tokens, std::ostream_iterator< std::string_view >{ std::cout, "\n" } ); } This works with gcc 12.1 (compile with -std=c++20), but it doesn't work with clang 14.0.0 because clang hasn't implemented P2210 yet.
72,828,750
72,829,850
Can the else clause be simplified in this if\else ladder?
I have thiselse clause: else if (iItemIndex == 1 || iItemIndex == 3 || iItemIndex== 5 || iItemIndex == 7 || iItemIndex == 10 || iItemIndex == 12 || iItemIndex == 14 || iItemIndex == 16 || iItemIndex == 19 || iItemIndex == 21 || iItemIndex == 23 || iItemIndex == 25) Can it be simplified in some way? Nothing wrong with the code. Just curious if there is a less verbose way of doing the test. In context I have: if(iItemIndex == 0 || iItemIndex == 9 || iItemIndex == 18) { // Do something } else if (iItemIndex == 1 || iItemIndex == 3 || iItemIndex== 5 || iItemIndex == 7 || iItemIndex == 10 || iItemIndex == 12 || iItemIndex == 14 || iItemIndex == 16 || iItemIndex == 19 || iItemIndex == 21 || iItemIndex == 23 || iItemIndex == 25) { // Do something else } else { // Do something else }
You can write const bool rng=i>=0 && i<27; if(const auto r=i%9; rng && !r) … else if(rng && (r&1)) … else … This can of course be much simplified if the value may be assumed to be in the relevant range: if(const auto r=i%9; !r) … else if(r&1) … else …
72,828,925
73,251,112
How to reset/delete Qcustomplot's axis ticker setting?
I have a QcustomPlot widget that I want to reuse it for plotting all kinds of plot. But there is a case that I need to set the xAxis ticker to DateTime.So I did this: QSharedPointer<QCPAxisTickerDateTime> dateTicker(new QCPAxisTickerDateTime); dateTicker->setDateTimeFormat("yyyy-MM-dd"); customplot->xAxis->setTicker(dateTicker); It changed the widget xAxis ticker forever. So when I want to switch it to other plots. The xAxis will always be 1970-01-01 on every tick. How do I reset the axis ticker setting to default/normal number setting? I've tride: customplot->clearPlottables(); customplot->xAxis->setRange(0,5); customplot->replot; but none of them worked. They only cleared the plot but not the xAixs ticks.Any suggestions?
ui->customPlot->xAxis->setTicker(QSharedPointer(new QCPAxisTicker)); - this will return them to their standard state
72,828,926
72,829,942
QTableWidgetItem displays three dots instead of full text
I'm using a QTableWidget with four column witch i programaticaly fill with QTableWidgetItem in a loop. it's working but the full text is not displaying, it show three dots instead like there isn't enough space: if i double click on a row it will display the whole text: How to set QTableWidgetItem programatically to fill all available space, or disable the 3 dots system and just display the whole text event if it will overflow ? Here my simplified code that just fill the second problematic column: vector<OperationLine> lines = db->getOperationLines(ui->dateEditFrom->date(),ui->dateEditTo->date()); ui->operationTableWidget->setRowCount(lines.size()); ui->operationTableWidget->setTextElideMode(Qt::ElideNone); for(int i=0;i<lines.size();i++){ QTableWidgetItem* libelle_item = new QTableWidgetItem(lines.at(i).libelle); libelle_item->setToolTip(lines.at(i).libelle); setDocumentMode(libelle_item); libelle_item->setSizeHint(QSize(500,50));// <-does not seem to work ui->operationTableWidget->setItem(i,1,libelle_item); } ui->operationTableWidget->resizeColumnsToContents(); ps: OperationLine is a simple class and .libelle is just a QString. Manualy resizing the column does not help. I also tried to disable editing and it does not help either. However if i comment my loop and manualy add item with QtCreator it seem to work as expected.
My original string contain return lines, removing them like: QString s = lines.at(i).libelle; s.replace('\n',' '); ui->operationTableWidget->setItem(i,1,s); is working. As @Scheff'sCat pointed out in the comment of my original post, using the accepted solution at How to prevent too aggressive text elide in QTableview? work too and will display multiple lines withouts the dots in the wrong place.
72,829,395
72,830,012
How function templates can accept functions as parameters even thought functions are not types?
This obvious question might be asked somewhere which i couldn't found, the nearest answer is this . I come from a C background and if you want to pass a function as argument in C You ought to use a pointer to function . but this : void increment ( int & n ) { n += 1; } template <typename T, typename F> void iterator(T *arr, size_t size, F f) { for (int i = 0; i < size; i++) f(arr[i]); } int main( void ) { int arr[] = {1, 2, 3, 4, 5}; iterator(arr, 5, increment); return 0; } One answer (see link above) state that templated function can only accept either a type or a value !! Well function are not types, so what's the matter with typename F , the other possible option is that the function actually evaluate and return it's value to templated function parameter which definitely doesn't make sense, so my question. How exactly are functions can be passed as arguments to templated functions? what's going on behind the scenes ?
Functions have a type. There is nothing fundamentally different from passing increment to the function template compared to passing arr. Their types get deduced and then replaced as the template arguments. Perhaps it get clearer without argument deduction: iterator<int, void()(int&)>(arr, 5, increment); or letting decltype deduce the type: iterator<int, decltype(increment)>(arr,5,increment); If iterator wasnt a template it would look something like this (for this particular call): using F = void(*)(int&); void iterator(int* arr, size_t size, F f);
72,829,821
72,829,898
c++: Generate random numbers with seed
I am new to c++. I am trying to generate 4 random unique numbers from 0 to 9. Here is my code: #include <iostream> #include <cstdlib> #include <ctime> #include <string> #include <vector> using namespace std; int main() { vector<int> vect; int randNums = 4; int countSameNums = 0; int randNumber; srand(time(0)); // Initialize random number generator by setting the seed // generate 4 random unique integers and insert them all into a vector while (true){ randNumber = rand()%10; for (int i = 0; i < vect.size(); i++){ if (randNumber == vect[i]){ countSameNums += 1; } } if (countSameNums == 0){ vect.push_back(randNumber); countSameNums = 0; } if (vect.size() == randNums) break; } for (int el : vect){ // print out the content of the vector cout << el <<endl; } } I can compile the code without problems. However when I run it, sometimes it prints out the correct result, i.e. the 4 unique integers, but other times the program just hangs. I also notice that If I comment the line srand(time(0)) (my random seed) it prints 4 unique numbers every time, i.e. the program never hangs. The problem of course is that by commenting srand(time(0)) I get always the same sequence of unique numbers and I want a different sequence every run. Any idea on why this isn't working? thanks
It can take long before you get 4 different numbers. There is a simpler and more efficient way to get 4 unique numbers. Take a vector containung number from 0 till 9, shuffle it, take the first 4. Anyhow the issue in your code is that once countSameNum is not 0 you will never reset it to 0. You only reset it when it is 0 already. Change it like this: while (true){ randNumber = rand()%10; countSameNums = 0; for (int i = 0; i < vect.size(); i++){ if (randNumber == vect[i]){ countSameNums += 1; } } if (countSameNums == 0){ vect.push_back(randNumber); } if (vect.size() == randNums) break; } As this is rather error-prone you should rather use std::find to see if the number is already in the vector: if (std::find(vect.begin(),vect.end(),randNumber) == vect.end()) vect.push_back(randNumber); And as mentioned before, there are better ways to get unique random numbers.
72,831,013
72,831,488
How to track source of rules (functions) in bazel? Is there any order of initialisation or query to discover it?
How to find places where the rule is defined and which definition bazel uses in this specific package? Say, I have gRPC installed and looking at grpc/examples/cpp/helloword/BUILD file. I can see a common rule for cpp builds: cc_binary. But this rule is not in grpc WORKSPACE file. Nor it in BUILD file. I do grep -rnw -e '"cc_binary"' and can't find it anywhere but /grpc/third_party/.. subdirectories. And this wouldn't make any sense for bazel to initiate this rule there. I do finding the dependencies of a rule bazel query "deps(//examples/cpp/helloworld:cc_binary)" and strangely, it doesn't want to query the rules - only targets. I get: ERROR: no such target '//examples/cpp/helloworld:cc_binary': target 'cc_binary' not declared in package 'examples/cpp/helloworld' When I do bazel query 'kind(cc_binary, deps(//examples/cpp/helloworld:greeter_client))' I think I'm getting closer with this list: //examples/cpp/helloworld:greeter_client @upb//upbc:protoc-gen-upbdefs @upb//upbc:protoc-gen-upb @com_google_protobuf//:protoc //src/compiler:grpc_cpp_plugin @bazel_tools//third_party/def_parser:def_parser But how can it help me? Is there a way to do it?
In general, query --output=build will emit a comment indicating where a target's rule class is defined: $ bazel query --output build //src/proto/grpc/core:stats_py_pb2 py_proto_library( name = "stats_py_pb2", deps = ["//src/proto/grpc/core:stats_descriptor"], ) # Rule stats_py_pb2 instantiated at (most recent call last): # grpc/src/proto/grpc/core/BUILD:35:17 in <toplevel> # Rule py_proto_library defined at (most recent call last): # grpc/bazel/python_rules.bzl:154:24 in <toplevel> cc_binary is a builtin rule, implemented in Java within Bazel. Therefore, Bazel cannot provide a Starlark source for its definition: $ bazel query --output build //examples/cpp/helloworld:greeter_client cc_binary( name = "greeter_client", deps = ["//:grpc++", "//examples/protos:helloworld_cc_grpc"], defines = ["BAZEL_BUILD"], srcs = ["//examples/cpp/helloworld:greeter_client.cc"], ) # Rule greeter_client instantiated at (most recent call last): # grpc/examples/cpp/helloworld/BUILD:17:10 in <toplevel>
72,831,564
72,831,787
Is it possible to pass one of the standard function templates as an argument without using a lambda?
For example, std::get<N>. Can I do the following without using a lambda somehow? #include <iostream> #include <tuple> #include <algorithm> #include <vector> #include <iostream> using str_and_int = std::tuple<std::string, int>; std::vector<std::string> just_strings(const std::vector<str_and_int>& tuples) { std::vector<std::string> strings(tuples.size()); std::transform(tuples.begin(), tuples.end(), strings.begin(), [](const auto& tup) { return std::get<0>(tup); } ); return strings; } int main() { std::vector<str_and_int> foo = { {"foo",1}, {"bar",2} ,{"quux",3}, {"mumble",4} }; for (const auto& str : just_strings(foo)) { std::cout << str << "\n"; } return 0; } Changing it to std::transform(tuples.begin(), tuples.end(), strings.begin(), std::get<0, str_and_int>) does not work. I am guessing because std::get is overloaded?
You don't have to use a lambda. You could provide an instance of your own type if you'd like: struct transformer { auto operator()(const auto& tup) const { // auto C++20 return std::get<0>(tup); } }; std::vector<std::string> just_strings(const std::vector<str_and_int>& tuples) { std::vector<std::string> strings(tuples.size()); std::transform(tuples.begin(), tuples.end(), strings.begin(), transformer{}); return strings; }
72,832,331
72,833,793
How do you display the array responses back to the user after establishing & validating their input? c++
newer at this but im drawing a blank on how to simply display the user's responses back. any feedback is so appreciated! currently what i have: int array[5] = {}; int i; int numbers; for(int i = 0; i < 5; i++) { std::cout << "Please enter a number: "; std::cin >> numbers; if (std::cin.fail()) { std::cin.clear(); std::cin.ignore(INT_MAX, '\n'); } } std::cout << "You entered: " << array[numbers] << std::endl;
what you really want is the printing of the array that is filled by the user inputs if i am not wrong.I want to bring to your consideration that the thing you have done is not even storing the inputs to the array. On going further assuming that you have the array concept. Now the problem you are facing is the access to that. Arrays have 2 things: Size : is the actual size in this case 5 Indexes: are the places as 0, 1, 2, 3, 4 these are called indexes like in the array if you want to access the first element you will go for the index 0. visual explanation of this. Now to access the first element you use the 0 index, thus for this we use subscript operator [], you will say array[0], this will access the first element that is on index 0. Check more description from here where as your code is concerned when you have taken input now you should save this in array as for(int i = 0; i < 5; i++) { std::cout << "Please enter a number: "; std::cin >> numbers; if (std::cin.fail()) { std::cin.clear(); std::cin.ignore(INT_MAX, '\n'); } array[i] = numbers; //now this will assign enter to array as i will be 0 then to 0 index first element, 1 index second element and so on } After this printing of the array elements can also be done similarly. Then statement you have written has problems as std::cout << "You entered: " << array[numbers] << std::endl; The problem here is that array[numbers] here number can be any entered by the user last time if he enters 8 then array[8] it will give you an error as out of bound the array was declared. Remember arrays are of fixed size. Similarly if 5 then also error as although size is 5 but have 4 index to access 5 element. Thus other problem is that you will only display a single number by it if in range was entered if as 0 then only first element. The solution to this can be as: std::cout << "You entered elements as : " << std::endl; for(int i = 0; i < 5; i++) { //this will now print all five elements as i will start from 0 and will end at 4 and all indexes will be displayed; std::cout << "Element " << i+1 <<" : " << array[i] << std::endl; } That's all and you are done :)
72,832,433
72,832,665
Preserving constness upon a cast
I want a way of preserving if the type is a pointer, const, etc upon a cast. See the following. template<typename type> void test(type t) { std::cout << "t const? = " << std::is_const<decltype(t)>() << std::endl; int x = (int) t; std::cout << "x const? = " << std::is_const<decltype(x)>() << std::endl; }; int main() { const int x = 0; int y = 0; test<const int>(x); test<int>(y); } >>> t const? = 1 >>> x const? = 0 >>> t const? = 0 >>> x const? = 0 How do I make it so that the function prints the following? In other words, how do I make it so that if the template argument is const, x is also const? >>> t const? = 1 >>> x const? = 1 >>> t const? = 0 >>> x const? = 0 I would like to avoid having to do anything like the following. // bad if constexpr (std::is_const<decltype(t)>()) { // do const cast } else { // do non const cast } The specific scenario I have is I have a const or non-const void pointer and want to cast it to a pointer with a type, whilst preserving the constness. Edit: This is a poor example. You can use type x = (type) t. I wanted a solution using type traits because this isn't a valid solution for me.
Your example isnt the best to illustrate the actual issue to cast a void*, possibly const, to some T* with same constness, because you can simply replace the line with type x = t; to get desired output. However, you can use a type trait: #include <iostream> #include <type_traits> template <typename From,typename To> struct preserve_const { using type = std::remove_const<To>::type; }; template <typename From,typename To> struct preserve_const<const From,To> { using type = const To; }; template <typename From,typename To> using preserve_const_t = typename preserve_const<From,To>::type; template<typename type> void test(type t) { std::cout << "t const? = " << std::is_const<decltype(t)>() << std::endl; preserve_const_t<type,int> x = t; std::cout << "x const? = " << std::is_const<decltype(x)>() << std::endl; }; int main() { const int x = 0; int y = 0; test<const int>(x); test<int>(y); } Or as mentioned in comments and perhaps much simpler: template <typename type,typename T> using the_type = std::conditional_t< std::is_const_v<type>,const T,T>;
72,832,521
72,832,768
is it safe to use std::move_iterator in std algorithm with lambda as pred
std::vector<std::string> foo{"a","b","c"}; std::set<std::string> check{"a"}; std::vector<std::string> bar{"something_here"}; typedef std::vector<std::string>::iterator Iter; std::copy_if(std::move_iterator<Iter>(foo.begin()), std::move_iterator<Iter>(foo.end()), std::back_inserter(bar), [&check](std::string && s)->bool{return check.find(s) == check.end();}); When I tested above code everything works but I am not sure why. My assumption was (likely wrong), in each "std::copy iteration", doesnt each string in foo gets "moved" into the lambda and when lambda returns, every variable(except captures) inside the lambda definition should go out of scope? Since the string was moved inside the lambda, why doesnt that invalidate whats been inserted into bar? Test link (https://onecompiler.com/cpp/3y8qeeqqr) Edit: Is it because although string is passed into lambda as rvalue, it was not used to construct another string, so effectively the input string was not "moved", i.e., ownership of that string resource is unchanged?
Is it because although string is passed into lambda as rvalue, it was not used to construct another string, so effectively the input string was not "moved", i.e., ownership of that string resource is unchanged? Yes. Simply forming an rvalue reference does not modify an object. The object doesn't even know it happened. Since your only use of the string in the lambda is reading it, its value is not changed.
72,832,782
72,833,491
How to make my ifstream "input" look the same in program like it does in file
I am new to programming, and currently I am learning C++. I am making this kind of project that I learn on, in which there already exists some "premade items", and items that you can create yourself and then be shown. For this, I am currently learning and using fstream. The text in my file looks like this: But this is how that same text looks in my output: How can I make it so that the text which I get in the output looks the same as the text in my file? Here is the part of code responsible for this action: void existingitems(){ ifstream existingitems("existingitems.txt",ios::in); vector<string>exitems; string inputs; while(existingitems >> inputs){ exitems.push_back(inputs); } for(string exisitems : exitems){ cout<<exisitems; } }
The lines of text in the file are delimited by line breaks. operator>> skips leading whitespace before reading data (unless std::noskipws is used), and then stops reading when it encounters whitespace. Spaces, tabs, and line breaks are all considered whitespace by operator>>. So, in your case, you end up reading individual words into your vector (ie Primordial, Mark, -Health, 300, etc), not whole lines as you are expecting. When you are then displaying the strings in the vector, you are not outputting any delimiters between each string, whether that be spaces or line breaks or whatever. So everything gets mashed together in one long string. If you want the output to look exactly like the file, use std::getline() instead of operator>>, and be sure to output a line break after each string: void existingitems(){ ifstream inputFile("existingitems.txt"); vector<string> existingitems; string input; while (getline(inputFile, input)){ existingitems.push_back(input); } for(string item : existingitems){ cout << item << '\n'; } }
72,832,953
72,833,655
How to get process name in an injected dll?
I have this basic internal dll: #include "pch.h" DWORD WINAPI HackThread(HMODULE hModule) { uintptr_t moduleBase = (uintptr_t)GetModuleHandle(L"Mainmodule123.exe"); AllocConsole(); FILE* f; freopen_s(&f, "CONOUT$", "w", stdout); std::cout << "Injected" << std::endl; while (!GetAsyncKeyState(VK_END) & 1) { Sleep(10) } fclose(f); FreeConsole(); FreeLibraryAndExitThread(hModule, 0); return 0; } BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: { CloseHandle(CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE)HackThread, hModule, 0, nullptr)); } case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } I want to get a handle to the main module of the application, for example: GetModuleHandle(L"Mainmodule123.exe") The problem, is that this application is changing the module numbers randomly. The main module name is the same as the process name. So I need to detect the process name that I'm attached to. How can I get the process name I'm attached to in an internal dll?
You can pass NULL for the lpModuleName parameter into GetModuleHandle: If this parameter is NULL, GetModuleHandle returns a handle to the file used to create the calling process (.exe file).
72,833,079
72,848,497
c++11 - list-initialization of an aggregate from an aggrrgate
On this page of the cppreference.com I read the following: If T is an aggregate class and the braced-init-list has a single element of the same or derived type (possibly cv-qualified), the object is initialized from that element (by copy-initialization for copy-list-initialization, or by direct-initialization for direct-list-initialization). But this page states this: An aggregate is one of the following types: array type class type (typically, struct or union), that has no private data members no user-provided, inherited, or explicit constructors But if an aggregate class has no user defined constructors, how it could be initialized in a manner stipulated above? I mean, it is not saying that aggregate members are getting their values from the members of the initializer, it explicitly mentions the constructor from the initializer. PS1 It seems like this one is a good exemplification: #include <iostream> #include <type_traits> class A { public: int a; int b; //this one does nothing to the code below: //A() = delete; //this one does BOOM //A(A &other) = delete; private: }; int main() { if( !std::is_aggregate<A>::value ) { std::cout << "A is not aggregate!" << std::endl; } A a = { 1, 2 }; A b = { a }; std::cout << "a is " << a.a << " " << a.b << std::endl; std::cout << "b is " << b.a << " " << b.b << std::endl; } So, copy constructor it is, I guess. PS2 I have the same behavior when compiling without std::is_aggregate and with c++11 flag on.
of the same or derived type That means that default copy-constructor will be used. That's why there is no contradiction between these two rules
72,833,113
72,833,153
How can a static void class function be initialized in the header of a C++ program?
I am supposed to initialize a static string, which is a private member of the class, with a setter which is a public member of the same class, from outside of the class, and in the same namespace. Here is the code template I was given. Changing the College class is not allowed. #include <iostream> using namespace std; class College { private: static string principal_name; // principal_name is common for all the students public: static void setPrincipalName(string name) { principal_name = name; } static string getPrincipalName() { return principal_name; } }; //Initialize the static principal_name variable with value "John" here string College::setPrincipalName("John");
string College::setPrincipalName("John"); is not legal or correct. You need to define the actual College::principal_name variable instead, eg: string College::principal_name = "John"; Even then, don't define it in the header file itself. Every file that includes the header will try to re-define the variable, leading to linker errors. Define the variable one time in a separate .cpp file instead, eg: College.h #ifndef CollegeH #define CollegeH #include <iostream> using namespace std; class College { private: static string principal_name; // principal_name is common for all the students public: static void setPrincipalName(string name) { principal_name = name; } static string getPrincipalName() { return principal_name; } }; #endif College.cpp #include "College.h" string College::principal_name = "John"; After that, you can use College::setPrincipalName() and College::getPrincipalName() anywhere else, as needed.
72,833,444
72,833,523
How to Return struct in a class when gthe struct is declared outside the class?
I am trying to get the structure of strings "Johna" "Smith" to return by calling a class. I am very new and confused on OOP and pointers and I wanted to know if Im on the right track and what I can do to get rid of the following errors: "cannot convert ‘name’ to ‘const char*’" on line 46... This line printf(s1.get_name()) Any help is appreciated, here is the full code #include <stdio.h> #include <algorithm> // for std::find #include <cctype> #include <ctime> #include <iostream> #include <iterator> // for std::begin, std::end #include <vector> using namespace std; enum year { FRESHMAN, SOPHOMORE, JUNIOR, SENIOR }; struct name { string firstName; string lastName; }; class Student : name { private: name Name; public: void setname(string fn, string ln) { Name.firstName = fn; Name.lastName = ln; } name get_name() { return Name; } }; int main() { Student s1; s1.setname("johna", "smith"); printf(s1.get_name()) return 0; }
Your code is totally fine, you're just confused about the printf function of C++. Maybe you have experience with python, javascript, or other scripting languages that the print function accepts anything and prints it out nicely. That is not the case with a strong typed language like C++. You should read the docs on printf. name s1_name = s1.get_name(); printf("%s %s\n", s1_name.firstName.c_str(), s1_name.lastName.c_str()); Alternatively, you could use std::cout, which will handle the format type for you. std::cout << s1_name.firstName << ' ' << s1_name.lastName << '\n'; You could also define a way to let std::cout know how to handle your struct: struct name { string firstName; string lastName; friend std::ostream& operator <<(ostream& os, const name& input) { os << input.firstName << ' ' << input.lastName << '\n'; return os; } }; ... std::cout << s1_name;
72,833,914
72,834,126
Does this count as an Insertion-Sort? And why does a random number show at the end?
I've been asked to create an insertion sort for an array. My program ended differently from the teacher's, but it sorts the array. However, I'm curious if it truly counts as a proper insertion sort. Also, at the end of the sorting, some random numbers appear. I would appreciate some help with this. #include <iostream> #define size 6 using namespace std; void insertion(int v[size]){ int i,temp; for(i=0;i<size;i++){ while(v[i+1] < v[i]){ temp = v[i+1]; v[i+1] = v[i]; v[i] = temp; printArr(v); i = 0; } } } int main(){ int vet[size] = {34,12,15,21,5,88}; printArr(vet); insertion(vet); return 0; } Here is the output, one line at a time: 34,12,15,21,5,88, 12,34,15,21,5,88, 12,15,34,21,5,88, 12,15,21,34,5,88, 12,15,21,5,34,88, 12,15,5,21,34,88, 12,5,15,21,34,88, 5,12,15,21,34,88, 5,12,15,21,34,44, Notice the 44 at the end there. I don't know why it's there since the code works nicely up until the end. Edit: Fixed a damn typo. My PC turns any lowercase i into uppercase, just forgot to adjust it, but it's not wrong in code.
For starters there is a typo in this statement v[i+1] = v[I]; ^^^^ It seems you mean v[i+1] = v[i]; ^^^^ The while loop while(v[i+1] < v[i]){ temp = v[i+1]; v[i+1] = v[I]; v[i] = temp; printArr(v); i = 0; } can invoke undefined behavior due to accessing memory beyond the array when i is equal to size - 1. In any case the approach with the while loop is incorrect and inefficient. The outer for loop again starts from 0 when a swap of adjacent elements occurred. And moreover the function depends on the magic named number 6. That is it is unable to sort arrays of different sizes.
72,833,916
72,835,160
c++11 - zero-initi of members insted of default-init
In the below code, I expect members of a being inited with gargabe as they are not mentioned in the members-init-list of the called constructor (with two int parameters). Instead, I'm constantly getting 0 in both i and j of a, b and c and I am failing to see why. Could anybody please point me in the right direction? #include <iostream> #include <type_traits> class A { public: int i; int j; A() = delete; A(int a, int b) { std::cout << "VOLOLO!" << std::endl; }; }; int smear_stack(int p) { int j = p++; int a[500] = {}; for(int i = 0; i < 499; i++) { a[i] = ++j; } std::cout << j << std::endl; return ++j; } int main(void) { int i = 2; i = smear_stack(++i); A a (i, 32 ); std::cout << "a is " << a.i << " " << a.j << std::endl; A b = { a }; std::cout << "b is " << b.i << " " << b.j << std::endl; A c = { a.i, a.j }; std::cout << "c is " << c.i << " " << c.j << std::endl; }
The i and j fields that you are accessing are, indeed, uninitialized. However, you are smearing the wrong part of the stack. It just so happens that on most OSes, the stack is initially all zeros. It even used to be common in C (long ago) to assume that automatic variables in main were zero-initialized. To see that the memory is indeed uninitialized, it suffices to put something else there. Here's an example: #include <iostream> #include <memory> class A { public: int i; int j; A() = delete; A(int a, int b) { std::cout << "VOLOLO!" << std::endl; }; }; union U { int is[2]; A a; U() : is{3,4} {} }; int main() { U u; std::construct_at(&u.a, 5, 6); std::cout << u.a.i << ", " << u.a.j << std::endl; // output: // VOLOLO! // 3, 4 }
72,834,348
72,834,516
Make generic Lambda with exactly N arguments
I want to dynamically create math expressions with lambdas, as reviewed here. using Func = std::function<double(double)>; Func operator+(Func const& lhs, Func const& rhs){ return [lhs, rhs](double x){ return lhs(x) + rhs(x); }; } My next goal is to generalize this. Thanks to this answer I managed to implement a generic type with exactly n arguments. But I do not know - if at all possible - how to specify the lambda arguments. check it on godbolt #include <functional> template <std::size_t, typename T> using alwaysT = T; template <typename FLOAT, typename Seq> struct func_struct; template <typename FLOAT, std::size_t... Is> struct func_struct<FLOAT, std::index_sequence<Is...>> { using type = std::function<double(alwaysT<Is, FLOAT>... floats)>; }; template <std::size_t N> using func_t = typename func_struct<double, std::make_index_sequence<N>>::type; template <std::size_t N> func_t<N> operator+(func_t<N> const& lhs, func_t<N> const& rhs){ return [lhs, rhs](alwaysT<N, std::make_index_sequence<N>> args...){// how to do this? lhs(args) + rhs(args); }; } int main(){ func_t<1> f1 = [](double x){return x*2;}; func_t<2> f2 = [](double x, double y){ return x*y;}; func_t<1> f3 = f1 + f1; } I'm also getting an error that the template argument N can not be deduced, in the last line.
Not sure the standard allows you to manage argument count restriction like that, but you can definitely have an assert if the arg count is in mismatch. E.g.: #include <functional> template <std::size_t, typename T> using alwaysT = T; template <typename FLOAT, typename Seq> struct func_struct; template <typename FLOAT, std::size_t... Is> struct func_struct<FLOAT, std::index_sequence<Is...>> { using type = std::function<double(alwaysT<Is, FLOAT>... floats)>; }; template <std::size_t N> struct func_t : func_struct<double, std::make_index_sequence<N>>::type { using Base = typename func_struct<double, std::make_index_sequence<N>>::type; using Base::Base; }; template <std::size_t N> func_t<N> operator+(func_t<N> const& lhs, func_t<N> const& rhs){ return [lhs, rhs](auto&&... args){ return lhs(args...) + rhs(args...); }; } int main(){ func_t<1> f1 = [](double x){return x*2;}; func_t<2> f2 = [](double x, double y){ return x*y;}; func_t<1> f3 = f1 + f1; } Note, I've changed the template<size_t N> using func_t to a template<size_t N> struct func_t so that matching on template argument is possible. using declarations are always replaced before matching and the compiler (as per current standard) is not expected to be able to deduce N from <double, 0, 1, 2, ...>.
72,834,444
72,834,546
How to concat string and float
I have a simple variable: float t = 30.2f; How do I add it to a string? char* g = "Temperature is " + h? Any guaranteed way (I don't have Boost for instance, and unsure of what version of c++ I have) I can get this to work on a microcontroller?
For simple cases, you can just use the std::string class and the std::to_string function, which have both been part of C++ for a long time. #include <string> #include <iostream> int main() { float t = 30.2; std::string r = "Temperature is " + std::to_string(t); std::cout << r; } However, std::to_string doesn't give you much control over the formatting, so if you need to specify a field width or a number of digits after the decimal point or something like that, it would be better to see lorro's answer. If you have an incomplete implementation of the C++ standard library on your microcontroller so you can't use the functions above, or maybe you just want to avoid dynamic memory allocation, try this code (which is valid in C or C++): float t = 30.2; char buffer[80]; sprintf(buffer, "Temperature is %f.", t); Note that buffer must be large enough to guarantee there will never be a buffer overflow, and failing to make it large enough could cause crashes and security issues.
72,834,496
72,834,604
Explicit template instantiation of templated friend of templated class in C++
I have a main class MainClass whose private member variables should be visible to a friend class FriendClass. Both are templated by an int called dim, and they both have their respective header and source files (and are thus in different translation units). Since MainClass doesn't really depend on FriendClass (and to avoid circular dependency) I forward declare FriendClass as a template class when doing the friend declaration in MainClass. Additionally, at the end of the source files I explicitly instantiate both classes for dim = 2 and dim = 3. However, when I compile I get an error that the private member variable of MainClass is private within this context when I try to use it in a method of FriendClass. I suspect this has something to do with the fact that a particular instantiation of FriendClass does not recognize that the corresponding instantiation of MainClass has declared it a friend, but I'm not sure how to fix the problem. Code: // MainClass.hpp #ifndef MAIN_CLASS_HPP #define MAIN_CLASS_HPP template <int dim> class MainClass { public: MainClass(){}; private: template <int friend_dim> class FriendClass; friend class FriendClass<dim>; double private_member = 3.0; }; #endif // MainClass.cpp #include "MainClass.hpp" template class MainClass<2>; template class MainClass<3>; // FriendClass.hpp #ifndef FRIEND_CLASS_CPP #define FRIEND_CLASS_CPP #include "MainClass.hpp" template <int dim> class FriendClass { public: FriendClass(){}; void print_main_class(MainClass<dim> &main_class); }; #endif // FriendClass.cpp #include "FriendClass.hpp" #include <iostream> template <int dim> void FriendClass<dim>::print_main_class(MainClass<dim> &main_class) { std::cout << main_class.private_member << std::endl; } template class FriendClass<2>; template class FriendClass<3>; // main.cpp #include "MainClass.hpp" #include "FriendClass.hpp" int main() { const int dim = 2; MainClass<dim> main_class; FriendClass<dim> friend_class; friend_class.print_main_class(main_class); return 0; } Code available to compile live at onlinegdb.com
You have declared two different class templates both named FriendClass. Probably unintentionally. One is the global FriendClass and the other is MainClass::FriendClass. You can fix this by forward declaring your class template in the namespace it exists in. // MainClass.hpp #ifndef MAIN_CLASS_HPP #define MAIN_CLASS_HPP template <int> class FriendClass; template <int dim> class MainClass { public: MainClass(){}; private: friend FriendClass<dim>; // Now the global FriendClass is a friend. double private_member = 3.0; }; #endif
72,834,725
72,834,877
How to obtain iterator type from template parameter, if template parameter is a reference type
The question title may not be super clear, but hopefully the below explains what is my problem. Let's say I have the following (simplified) class template: template <typename T, typename Container = std::vector<T>> class MyVector { using iterator = typename Container::iterator; Container data{}; public: MyVector(initializer_list<T> l) : data(l) {} iterator begin() { return data.begin(); } }; If I create an object like MyVector<int> vec {1, 2, 3}; it works fine. However, if I try to create an object like MyVector<int, std::vector<int>&> vec; (note the &), then in the iterator type definition I get the error: Type 'std::vector<int> &' cannot be used prior to '::' because it has no members I tried exploring std::remove_reference and changed the line to: using iterator = typename std::remove_reference<Container>::type::iterator; but this also doesn't work - the error I get in this case is: No type named 'iterator' in 'std::remove_reference<std::vector<int>>' What I would like to achieve is to have a type definition (for iterator) that works if Container is a std::vector<T> as well as a reference to std::vector<T> (or whatever Container type is used, e.g. std::array - which means I cannot simply use std::vector<T>::iterator in the typedef). Is there any way to achieve this?
The std::remove_reference will work here. Or you need std::remove_reference_t version of it using iterator = std::remove_reference_t<Container>::iterator; // ^^^^^^^^^^^^ That is mean, if you do not have access to the c++14, provide a type alias for this template< class T > using remove_reference_t = typename remove_reference<T>::type; Also note that, in order to work with MyVector<int, std::vector<int>&> vec(v); // ^^^^^^^^ --> not an ini-list class MyVector must have a constructor MyVector(Container c) : data(c) {} The std::initializer_list will not work with reference qualified container type. Here is the demo
72,834,729
72,899,394
Thrust inplace copy_if operation
I wanted to know if you can use copy_if as an in-place operation? i.e. void copy(thrust::device_vector<int> & input){ auto end = thrust::copy_if(input.begin(), input.end(), input.begin(), thrust::placeholder.1_ < 10); input.erase(end, input.end()); } is equivalent to: void copy(thrust::device_vector<int> & input){ thrust::device_vector<FullOptixRayPayload> dest(input.size()); auto destEnd = thrust::copy_if(input.begin(), input.end(), dest.begin(), thrust::placeholder.1_ < 10); dest.erase(destEnd, dest.end()); input = dest; } (order does not matter to me. I just want to reduce the amount of device space allocation. The copy_if operation and data types are just placeholders)
According to the documentation: Preconditions: The ranges [first, last) and [result, result + (last - first)) shall not overlap. So no, one is not allowed to use thrust::copy_f in-place. The reason is probably that the algorithm would need to create an internal copy (especially costly due to the potential allocation) before scattering the data to the right positions safely.
72,834,775
72,835,147
ZLib: DeflatePrime number of bits of Z_PARTIAL_FLUSH
In the ZLIB Manual it is stated that Z_PARTIAL_FLUSH always flush an extra 10 bits. So that we correct for that using deflatePrime when we want to append later. But why then is gzlog.c containing logic to find dynamically the bit count if *buf . According to the specs this is not needed and only the else is needed to set it to 10? if (*buf) { log->back = 1; while ((*buf & ((uint)1 << (8 - log->back++))) == 0) ; /* guaranteed to terminate, since *buf != 0 */ } else log->back = 10;
Because most of the time not all of the ten bits are written. Only in the case where the last byte is a zero are all ten bits written, because by chance (a one-in-eight chance) there were six bits pending to be written before the ten-bit empty static block.
72,835,323
72,835,392
C++ class object default constructor bug
I am trying to create a class object s2 with some customized attributes and some attributes from default constructor however my output is the wrong output for the get_year function. It should be outputing 0 which is the key for FRESHMAN but it is out putting 2 instead. The rest of the code is outputting as expected: #include <stdio.h> #include <iostream> #include <algorithm> // for std::find #include <iterator> // for std::begin, std::end #include <ctime> #include <vector> #include <cctype> using namespace std; enum year {FRESHMAN, SOPHOMORE, JUNIOR, SENIOR}; struct name { string firstName; string lastName; friend std::ostream& operator <<(ostream& os, const name& input) { os << input.firstName << ' ' << input.lastName << '\n'; return os; } }; class Student: name{ private: name Name; year Year; int idNumber; string Department; public: void setname(string fn="", string ln="") { Name.firstName =fn; Name.lastName =ln; } name get_name() { return Name; } void set_year(year yr=FRESHMAN) { Year=yr; } year get_year() { return Year; } void set_ID(int ID=0) { idNumber=ID; } int get_ID() { return idNumber; } void set_Department(string Dept="") { Department=Dept; } string get_Department() { return Department; } }; int main() { Student s2; s2.setname("Nikolai", "Khabeboolin"); s2.set_ID(12436193); cout<<"ID is: "<< s2.get_ID()<<", name is "<< s2.get_name()<<", year in school is: "<<s2.get_year()<<", Department is "<<s2.get_Department()<<endl; return 0; }
Student lacks a constructor, so all its members are default initialized, and the default initialization of year Year and int idNumber is "no initialization", so reading from them is undefined behavior. Reading them might find 0, 2, a random value each time, or crash. I see that your class contains a void set_year(year yr=FRESHMAN) member, but your code never called set_year, so no part of this executed. You should make a default constructor for Student, or as Goswin von Brederlow stated, use year Year{FRESHMAN}; and int idNumber{-1}; when declaring the members, to give them default initializations.
72,835,462
72,835,502
Comparator for lower_bound for vector of pairs
I wanna make lower_bound for vector of pairs but I wanna use it only for first elements of pairs. I tried to make my own comparator like this: bool find(const std::string& key) const { auto finder = std::lower_bound(words_.begin(), words_.end(), key, [](const std::string& key, std::vector<std::pair<std::string, std::string>>::iterator it) {return key != it->first;}); } but it doesn't work. How I should use comparator to compare only first elements of pairs?
Your lambda is the wrong signature and comparison for lower_bound(). It is expected to compare a container element against the provided value. Which means it does not accept an iterator as input at all. The 1st parameter of the lambda needs to accept the container element, and the 2nd parameter needs to accept the input value. So, you are probably looking for something more like this instead: bool find(const std::string& key) const { auto finder = std::lower_bound(words_.begin(), words_.end(), key, [](const std::pair<std::string, std::string> &elem, const std::string &value) { return elem.first < value; } ); ... } That being said, if all you are trying to do is find an exact match to the specified key, std::find_if() would make more sense: bool find(const std::string& key) const { auto finder = std::find_if(words_.begin(), words_.end(), [&key](const std::pair<std::string, std::string> &elem) { return elem.first == key; } ); ... }
72,835,571
72,835,611
constexpr C++ error: destructor used before its definition
I'm experiencing an error using g++-12 which does not occur in clang++-13. In particular, this code: struct A { constexpr virtual ~A() = default; constexpr A() = default; }; struct B : public A { constexpr ~B() = default; constexpr B() = default; }; constexpr int demo(){ B *b = new B(); delete b; return 2; } int main(){ constexpr int demod = demo(); return demod; } Compiles with clang++, but with g++ gives the error: minimize-error.cpp: In function ‘int main()’: minimize-error.cpp:18:31: in ‘constexpr’ expansion of ‘demo()’ minimize-error.cpp:13:12: error: ‘virtual constexpr B::~B()’ used before its definition 13 | delete b; | Curiously, if I just remove the constexpr requirement on demod, the example compiles and runs without error. Any ideas as to what's happening here?
It is a GCC bug, see this report. Virtual defaulted destructors don't seem to work at all in constant evaluation with current GCC. As also mentioned in the bug report, simply struct A{ constexpr virtual ~A() = default; }; constexpr A a; also fails. As a workaround you can provide definitions for the destructors manually instead of defaulting: constexpr virtual ~A() {} /*...*/ constexpr ~B() {} Then GCC seems happy.
72,835,703
72,837,755
Sort 2d C++ array by first element in subarray
I am trying to sort a c++ subarray by first element. My code is currently set up like this: int umbrellas[3][2] = {{5, 6}, {2, 7}, {9, 20}}; int n = sizeof(umbrellas) / sizeof(umbrellas[0]); sort(umbrellas, umbrellas + n, greater<int>()); The sort function doesn't seem to be functioning properly and when I run the code it generates errors. Is there a way to sort the array from {{5, 6}, {2, 7}, {9, 20}} into {{2, 7}, {5, 6}, {9, 20}} ?
Use a std::vector of std::vector as your container and the sort becomes much easier to do with. Not only is std::vector the preferred container for C++ but using STL functions on it is way simpler and direct , without any substantiable overhead. Define your data as std::vector<std::vector<int>> umbrellas{ {5, 6}, {2, 7}, {9, 20} }; Now you can use a custom comparator lambda that takes in two vector element references and returns True when the first element of the above vector is smaller than that of the one below. std::sort(umbrellas.begin(), umbrellas.end(), [](const std::vector<int> &above, const std::vector<int> &below) { return (above[0] < below[0]); }); And the output : for (auto &&row : umbrellas) { for (auto element : row) { std::cout<< element<< " "; } std::cout<< "\n"; } 2 7 5 6 9 20 Taking this to C++20 it's even easier: std::ranges::sort(umbrellas, std::less(), [](const auto &v) { return v[0];});
72,835,974
72,836,053
Return Expression Check Condition in C++
Still getting used to the formatting when writing C++ code, come from a Lua background. How do I correctly format a if/conditional expressions as my example highlights below. This will correctly run, but with warnings which is unideal: return (boolean == true) and init() or 0; Highlighted Warning: expected a ';'C/C++ (between "(boolean == true)" "and")
and and or are keywords are considered a bit archaic. They are technically valid C++ keywords in modern C++ (since C++98 it seems). You must be using a very old C++ compiler that was written before they were added to C++. They, and their usage, never took off. Classical && and || operators continue to rule the roost and are not going anywhere. Therefore: although it is true that this expression should be logically equivalent to boolean && init(), you might want to consider assigning somewhat higher priority of updating your C++ compiler to something more modern, if that's indeed the reason for the compilation error.
72,836,070
72,838,182
Speeding up boost::iostreams::filtering_streambuf
I am new to the C++ concept of streams and want to ask for some general advice to speed up my code in image processing. I use a stream buffer boost::iostreams::filtering_streambuf to load and decompress the image from a file, as suggested in this post and another post. The performance is not satisfactory. The relavent code is the following: template <int _NCH> class MultiChImg { public: ... ... private: std::atomic<bool> __in_operation; std::atomic<bool> __content_loaded; char **_IMG[_NCH]; int _W, _H; void dcmprss ( const std::string & file_name, bool is_decomp = true) { ... ... // decompress int counter = 0, iw = -1, ih = -1, _r = 0; auto _fill_ = [&](const char c){ _r = counter % _NCH ; // was 3 for RGB mindset if ( _r == 0 ) { iw++; // fast index if ( iw%_W==0 ) { iw=0; ih++; } // slow index } _IMG[_r][_H-1-ih][iw] = c; counter ++ ; } ; auto EoS = std::istreambuf_iterator<char>() ; // char buf[4096]; // UPDATE: improved code according to @sehe if ( is_decomp ) { // decompress bio::filtering_streambuf<bio::input> input; input.push( bio::gzip_decompressor() ); // input.push( fstrm ); std::basic_istream<char> inflated( &input ); auto T3 = timing(T2, "Timing : dcmprss() prepare decomp ") ; // assign values to _IMG (0=>R, 1=>G, 2=>B) // TODO // bottleneck std::for_each( std::istreambuf_iterator<char>(inflated), EoS, _fill_ ); // UPDATE: improved code according to @sehe , replace the previous two lines // while (inflated.read(buf, sizeof(buf))) // std::for_each(buf, buf + inflated.gcount(), _fill_); auto T4 = timing(T3, "Timing : dcmprss() decomp+assign ") ; } else { // assign values to _IMG (0=>R, 1=>G, 2=>B) // TODO // bottleneck std::for_each( std::istreambuf_iterator<char>(fstrm), EoS, _fill_ ); // different ! // UPDATE: improved code according to @sehe , replace the previous two lines // while (fstrm.read(buf, sizeof(buf))) // std::for_each(buf, buf + fstrm.gcount(), _fill_); auto T3 = timing(T2, "Timing : dcmprss() assign ") ; } assert(counter == _NCH*_H*_W); ... ... }; ... ... } The bottleneck appears to be the for_each() part, where I iterate the stream, either inflated via std::istreambuf_iterator<char>(inflated), or fstrm via std::istreambuf_iterator<char>(fstrm), to apply a lambda function _fill_. This lambda function transfers the bytes in the stream to the designated place in the multi-dimensional array class member _IMG. UPDATE: the timing was incorrect due to memory leakage. I've corrected that. The timing results of the above function dcmprss() are 450ms for a .gz file of 30MB size, 400ms for uncompressed file. I think it takes too long. So I am asking the community for some kind advice to improve. Thanks for your time on my post!
You can use blockwise IO char buf[4096]; inflated.read(buf, sizeof(buf)); std::for_each(buf, buf + inflated.gcount(), _fill_); However, I also think considerable time might be wasted in _fill_ where some dimensions are reshaped. That feels arbitrary. Note that several libraries have the features to transparently re-index multi-dimensional data, so you may potentially save time just linearly copy the source data and accessing that: Boost MultiArray (allows you to specify storage order, direction and offsets: https://www.boost.org/doc/libs/1_79_0/libs/multi_array/doc/user.html#sec_storage Boost GIL allows you to use image data directly from interleaved/planar buffers: https://www.boost.org/doc/libs/1_79_0/libs/gil/doc/html/design/dynamic_image.html
72,836,346
72,836,441
How do I can I get notified of an object collision and object trigger in Box2D?
Unity3D has the OnCollisionEnter2D, OnCollisionExit2D, OnTriggerEnter2D etc. However, I am using Box2D and am looking for a way to implement something similar or the same in my C++ project, but I do not know how. I saw something about implementing a listener but I believe it was for the whole world. I am looking to report these events only to the code that physics body is attached to.
Enabling an event listener is necessary for collision events in Box2D, as explained in this video. Alternatively, you could implement your own collision logic. For rectangular hitboxes, that would look something like this: (Please note: this only works for rectangles with no rotation relative to the screen.) if (rect1.x < rect2.x + rect2.w && rect1.x + rect1.w > rect2.x && rect1.y < rect2.y + rect2.h && rect1.h + rect1.y > rect2.y) { // collision detected } else { // no collision } For circles, that would look something like this: auto dx = (circle1.x + circle1.radius) - (circle2.x + circle2.radius); auto dy = (circle1.y + circle1.radius) - (circle2.y + circle2.radius); auto distance = sqrt(dx * dx + dy * dy); if (distance < circle1.radius + circle2.radius) { // collision detected } else { // no collision } You can see these detection algorithms in more detail here.
72,836,555
72,836,752
How can I delink an element from a c++ std::list without deallocating it?
Suppose I have a c++ std::list object containing a few elements and an iterator it to one of the elements. How can I remove this element from the list but still be able to access it? In other words, I want it delinked from the list, but not deallocated. Curiously, using list::erase does seem to achieve this: #include <iostream> #include <cstdio> #include <list> using namespace std; int main() { std::list<int> a; a.push_back(1); a.push_back(2); a.push_back(3); auto it = (--a.end()); a.erase(it); cout << *it << endl; /// outputs '3' anyway, without any error } But I assume this isn't really safe? Questions: Is it a guarantee behavior that an element erased by list::erase is still accessible by the original iterator? If yes, how can I deallocate its memory? If no, how can I erase some element without deallocating its memory and be able access it after erasal?
This can be done provided you don't mind using a second list to receive the erased item auto it = (--a.end()); std::list<int> b; b.splice(b.end(), a, it); cout << *it << endl; /// outputs '3' splice removes the it element from list a and adds it to the end of list b. It's a constant time operation and does not invalidate any iterators.
72,836,628
72,836,662
How good is the Visual Studio compiler at branch-prediction for simple if-statements?
Here is some c++ pseudo-code as an example: bool importantFlag = false; for (SomeObject obj : arr) { if (obj.someBool) { importantFlag = true; } obj.doSomethingUnrelated(); } Obviously, once the if-statement evaluates as true and runs the code inside, there is no reason to even perform the check again since the result will be the same either way. Is the compiler smart enough to recognize this or will it continue checking the if-statement with each loop iteration and possibly redundantly assign importantFlag to true again? This could potentially have a noticeable impact on performance if the number of loop iterations is large, and breaking out of the loop is not an option here. I generally ignore these kinds of situations and just put my faith into the compiler, but it would be nice to know exactly how it handles these kinds of situations.
Branch-prediction is a run-time thing, done by the CPU not the compiler. The relevant optimization here would be if-conversion to a very cheap branchless flag |= obj.someBool;. Ahead-of-time C++ compilers make machine code for the CPU to run; they aren't interpreters. See also Matt Godbolt's CppCon2017 talk “What Has My Compiler Done for Me Lately? Unbolting the Compiler's Lid” and How to remove "noise" from GCC/clang assembly output? for more about looking at optimized compiler-generated asm. I guess what you're suggesting could be making a 2nd version of the loop that doesn't look at the bool, and converting the if() into an if() goto to set the flag once and then run the other version of the loop from this point onward. That would likely not be worth it, since a single OR instruction is so cheap if other members of the same object are already getting accessed. But it's a plausible optimization; however I don't think compilers would typically do it for you. You can of course do it manually, although you'd have to iterate manually instead of using a range-for, because you want to use the same iterator to start part-way through the range. Branch likelihood estimation at compile time is a thing compilers do to figure out whether branchy or branchless code is appropriate, e.g. gcc optimization flag -O3 makes code slower than -O2 uses CMOV for a case that looks unpredictable, but when run on sorted data is actually very predictable. My answer there shows the asm real-world compilers make; note that they don't multi-version the loop, although that wouldn't be possible in that case if the compiler didn't know about the data being sorted. Also to guess which side of a branch is more likely, so they can lay out the fast path with fewer taken branches. That's what the C++20 [[likely]] / [[unlikely]] hints are for, BTW, not actually influencing run-time branch prediction. Except on some CPUs, indirectly via static prediction the first time a CPU sees a branch. Or a few ISAs, like PowerPC and MIPS, have "branch-likely" instructions with actual run-time hints for the CPU which compilers might or might not actually use even if available. See How do the likely/unlikely macros in the Linux kernel work and what is their benefit? - They influence branch layout, making the "likely" path a straight line (branches usually not-taken) for I-cache locality and contiguous fetch. Is there a compiler hint for GCC to force branch prediction to always go a certain way?
72,837,193
72,837,214
C++ Socket libraries are not being identified by the compiler
I am trying to to learn how to stream image frames via UDP in C++ and I was following this tutorial for the server part to receive my frames, this tutorial clearly uses code from question stackoverflow question. However, after following up both sources, whenever I attempt to load my libraries in geany/c++: #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <iostream> using namespace std; using namespace cv; #define width 320 #define height 240 int imgSize; int bytes=0; bool running = true; char key; const int ah = 230400; int main(int argc, char * argv[]) { SOCKET server; SOCKADDR_IN addr; server = socket(AF_INET, SOCK_STREAM, 0); addr.sin_addr.s_addr = inet_addr("127.0.0.1"); addr.sin_family = AF_INET; addr.sin_port = htons(9999); connect(server, (SOCKADDR *)&addr, sizeof(addr)); return 0; } This gives me the following errors: /home/pi/Documentos/cam.cpp: In function ‘int main(int, char**)’: /home/pi/Documentos/cam.cpp:27:2: error: ‘SOCKET’ was not declared in this scope 27 | SOCKET server; | ^~~~~~ /home/pi/Documentos/cam.cpp:28:2: error: ‘SOCKADDR_IN’ was not declared in this scope 28 | SOCKADDR_IN addr; | ^~~~~~~~~~~ /home/pi/Documentos/cam.cpp:29:2: error: ‘server’ was not declared in this scope; did you mean ‘servent’? 29 | server = socket(AF_INET, SOCK_STREAM, 0); | ^~~~~~ | servent /home/pi/Documentos/cam.cpp:30:2: error: ‘addr’ was not declared in this scope 30 | addr.sin_addr.s_addr = inet_addr("127.0.0.1"); | ^~~~ /home/pi/Documentos/cam.cpp:30:25: error: ‘inet_addr’ was not declared in this scope; did you mean ‘in6_addr’? 30 | addr.sin_addr.s_addr = inet_addr("127.0.0.1"); | ^~~~~~~~~ | in6_addr /home/pi/Documentos/cam.cpp:33:19: error: ‘SOCKADDR’ was not declared in this scope 33 | connect(server, (SOCKADDR *)&addr, sizeof(addr)); | ^~~~~~~~ /home/pi/Documentos/cam.cpp:33:29: error: expected primary-expression before ‘)’ token 33 | connect(server, (SOCKADDR *)&addr, sizeof(addr)); Forgive my ignorance, I'd like to know what is the right way to create a UDP socket for a specific IP/Port
You are using SOCKET or SOCKADDR_IN which is Microsoft dedicated but I see Linux headers. You need to select what you want to do: You need code only for Windows. You need code only for Linux. You need a cross-platform code. Your approach somehow differs based on what you want to do. If your code is supposed to work on Windows only, replace: #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> with: #include <windows.h> #include <winsock2.h> and also add WSAStartup() and WSACleanup() to your code (I'm almost sure you will miss this part if you are socket programming on Windows). You also need to link your code with Ws2_32.lib. If you are coding for Linux, replace SOCKET with int, SOCKADDR_IN with sockaddr_in, and SOCKADDR with sockaddr and try again.
72,837,408
72,837,533
Passing a templated function as argument without instantiation?
I've been doing some exercises in C++ and stumbled upon one, it was about creating a simple a templated function iterator that takes an array of any type and another templated function to do some processing in each element in the array, i've completed the exerisce to look like the following: template <typename T > void increment(T& t) { t += 1; } template <typename T, typename F> void iterate(T *arr, size_t size, F f) { for (size_t i = 0; i < size; i++) f(arr[i]); } int main( void ) { int tab[]= {0,1,2,3,4}; SomeClass tab2[5]; iterate(tab, 5, increment<int>); iterate(tab2, 5, increment<SomeClass>); return (0); } Those 2 tests in the main function is those which i wrote my self, now the exercise too provide some tests to check the solution, and it's tests almost the same, it uses a simple print() templated function instead of increment() template <typename T > void print(const T& t) {std::cout << t << " "; }; Now the problem here is it uses the following instantiation for templated function iterate(): iterate(tab, 5, print); iterate(tab2, 5, print); Now according to what my understanding you cannot pass a templated function as argument without instantiation because it's not a regular function, it should be instantiated otherwise the compiler wouldn't know what type to create for the actual function ?? and indeed when i compiled the exercise's tests i got a: no matching function for call to 'iterate' so my question is am i correct and this is just a mistake in the exercise or the tests are correct and i'm the one who's missing something ?
Yes, you are correct. A function template cannot be passed as a template argument because it does not have a type yet. What you can pass is a functor, either custom one with overloaded operator() or just a lambda. Are you sure the wording does not talk about functors? The following code works: auto print = [](const auto& t) {std::cout << t << " "; }; iterate(tab, 5, print); iterate(tab2, 5, print); This is also the approach many STL algorithms took.
72,837,598
72,837,674
Class template argument deduction for class with additional non-type arguments
Is it possible to make CTAD work for T in this case? enum class boundary_type:int{inclusive, exclusive}; template<class T, boundary_type left, boundary_type right> struct interval { using value_type = T; T begin; T end; }; I tried to add the decuction guide template<boundary_type left, boundary_type right, class T> interval(T, T) -> interval<T, left, right>; But still gets error wrong number of template arguments (2, should be 3) when trying interval<boundary_type::inclusive, boundary_type::exclusive>{0, 2}
CTAD cannot work with the partially explicitly specified template parameter. But you can do this using normal template function template<boundary_type left, boundary_type right, class T> auto make_interval(T begin, T end) { return interval<T, left, right>{begin, end}; } int main() { auto intval = make_interval<boundary_type::inclusive, boundary_type::exclusive>(0, 2); }
72,837,730
72,837,731
How does the setw stream manipulator work?
How does the setw stream manipulator (space count) work? When there is one \t, for example, I want to print a with four spaces, so I use \t and I compare \t with setw. The code that I wrote: # include <iostream> # include <iomanip> int main() { std::cout<<"\t"<<"a\n"; std::cout<<std::setw(9)<<"a\n"; return 0; } Output: a // This is 1 '\t' a // This is setw() So what I thought was: setw(18) = \t\t The code worked. But when I deleted the \n, it did not become one straight line. # include <iostream> # include <iomanip> int main() { std::cout<<"\t\t"<<"a\n"; std::cout<<std::setw(18)<<"a"; return 0; } It gives me this output: a a What's wrong?
That's because you need to add a \n at the setw(18). And this applies to any setw. Sample code: # include <iostream> # include <iomanip> int main() { std::cout<<"\t\t"<<"a\n"; std::cout<<std::setw(18)<<"a\n"; // And you add the \n here return 0; } Output: a a And another solution is: # include <iostream> # include <iomanip> int main() { std::cout<<"\t\t"<<"a\n"; std::cout<<std::setw(18)<<"a "; // And you add the a space here return 0; } And the output will be the same. The reason behind why should we put the \n or a space is because: It's because it justifies the whole two-character string "a"\n, not only the a. If you print the newline separately (... << 'a' << '\n') then you would get the same "error". You could also have solved it by using almost any space character, like ... << "a "; You might want to print both with and without the newline in the same program to see the difference. - Some Programmer Dude
72,837,932
72,837,987
Is " const wchar_t* " a pointer?
Normally when we write: int a = 10; int* ptr = &a; std::cout << *ptr; Code output is: > 10 But when I write this: const wchar_t* str = L"This is a simple text!"; std::wcout << str << std::endl; std::wcout << &str << std::endl; Code output is: > This is a simple text! > 012FFC0C So this makes me confused. Doesn't that Asterisk symbol stand for pointer? If it is a pointer, how is it possible for us to assign a value other than the address value? Shouldn't the top output be at the bottom and the bottom output at the top?
L"This is a simple text!" is an array of type const wchar_t[23] containing all the string characters plus a terminating 0 char. Arrays can decay in which case they turn into a pointer to the first element in the array which is what happens in const wchar_t* str = L"This is a simple text!"; std::wout can be used with a << operator that takes such a null terminated character as second operand; this operator prints the string. The second print simply prints the address of the pointer, since there is no overload for the << operator handling an argument of type const wchar_t** differently to arbitrary pointer types (except for some specific pointer types as seen in the first print).
72,838,017
72,839,302
multiple shared_ptr that point to the same object
Just for studying purpose I'm coding binary search tree rotation now. I normally use std::unique_ptr but I used std::shared_ptr this time This works correctly: // Node implementation template <Containable T = int> struct Node { T key_ = T{}; bool black_ = false; // red-black tree std::shared_ptr<Node> left_; std::shared_ptr<Node> right_; }; // this is a protected member function of red-black tree class // xp is parent node of x void left_rotate(Node *xp, Node* x) { assert(x); auto y = x->right_; x->right_ = y->left_; std::shared_ptr<Node> x_ptr; if (!xp) { x_ptr = root_; root_ = y; } else if (x == xp->left_.get()) { x_ptr = xp->left_; xp->left_ = y; } else { x_ptr = xp->right_; xp->right_ = y; } y->left_ = x_ptr; } This crashes: void left_rotate(Node *xp, Node* x) { assert(x); auto y = x->right_; x->right_ = y->left_; std::shared_ptr<Node> x_ptr(x); if (!xp) { root_ = y; } else if (x == xp->left_.get()) { xp->left_ = y; } else { xp->right_ = y; } y->left_ = x_ptr; } cppreference says: Link std::shared_ptr is a smart pointer that retains shared ownership of an object through a pointer. Several shared_ptr objects may own the same object. The object is destroyed and its memory deallocated when either of the following happens: the last remaining shared_ptr owning the object is destroyed; the last remaining shared_ptr owning the object is assigned another pointer via operator= or reset(). To avoid destroying the node pointed to by x before assigning, I created another std::shared_ptr<Node> that owns *x, but in the second implementation, the node object pointed by x is already destroyed before y->left_ = x_ptr is called. The node object is actually destroyed when one of root_ = y, xp->left_ = y and xp->right_ = y is called. There are clearly multiple std::shared_ptr objects that own the same node object. root_, xp->left_ or xp->right_ is clearly NOT the last remaining std::shared_ptr owning the object. Why this happens?
void left_rotate(Node *xp, Node* x) { ... std::shared_ptr<Node> x_ptr(x); ... When you create the shared_ptr it takes over ownership of x. The problem here is that it is not yours to give. Someone else, another shared_ptr, already has ownership of the pointer. So some of the operations you do before y->left = xptr will assign a new value to the shared_ptr owning x and that deletes the x. The problem is that you use raw pointers as arguments. Whenever you extract the pointer from a shared_ptr be very careful about the lifetime of the obejct. The extracted raw pointer does not keep the object alive. Something that becomes exceedingly difficult to reason about with function calls. Easy to mess up as you experienced. It's easily avoided by passing shared_ptr as arguments because they will keep your objects alive: void left_rotate(std::shared_ptr<NodeY> xp, std::shared_ptr<Node> x) { PS: I hope your root_ is a shared_ptr too.
72,838,038
72,838,111
(C++) Using multiple operator overloads with const reference parameters
I have been working on a matrix class and I have recently learnt about passing const references to operator overloads so that I can have multiple of them on the same line. The problem I encountered is when defining a function for an operator overload, which takes a parameter by const reference, and then tries using another operator overload on that parameter. Some minimal code for this is shown below: class Matrix { private: int col, row; typedef std::vector<double> Column; std::vector<Column> data; public: Matrix(int rows, int columns) : col(columns), row(rows), data(rows, std::vector<double>(columns)) {} Column& operator[](int i) //Operator overload to allow for use of Matrix[i][j] { return data[i]; } Matrix& operator*(const Matrix& matrix2) { Matrix* matrix1 = new Matrix(row, col); matrix1->data = this->data; double tempValue = matrix1[0][0] * matrix2[0][0]; //Error here when accessing matrix2[0][0] return *matrix1; } }; As you can see inside the operator* code I am trying to use the overload of the [] operator, which normally helps me use matrix[i][j] notation to enumerate through its data. This was working fine until I started using const Matrix& as a parameter to pass. Now when trying to access the indices of matrix2 it gives me this error: no operator "[]" matches these operands Does anyone know why this is happening or how to fix it ? I tried using const int& as a paramter for the operator[] overload but it did not seem to help. Accessing the indices of matrix1 seems to work fine otherwise.
For starters matrix1 is a pointer but you need to apply the subscript operator for an object of the type Matrix. matrix2 is a constant object but the subscript operator is not a constant member function. You need to overload the operator [] as a constant member function Column& operator[](int i) //Operator overload to allow for use of Matrix[i][j] { return data[i]; } const Column& operator[](int i) const //Operator overload to allow for use of Matrix[i][j] { return data[i]; } And the operator * should be declared like Matrix operator*(const Matrix& matrix2) const { Matrix matrix1(row, col); matrix1.data = this->data; double tempValue = matrix1[0][0] * matrix2[0][0]; return matrix1; } though it is unclear what this statement double tempValue = matrix1[0][0] * matrix2[0][0]; is doing here.:) Pay attention to that dynamically allocating an object in the operator * is a very bad idea.
72,838,235
72,838,443
C++ How to choose file size as array size
I can't use file size as array size, because it should be a constant. But I made it constant. ifstream getsize(dump, ios::ate); const int fsize = getsize.tellg(); // gets file size in constant variable getsize.close(); byte dumpArr[fsize] // not correct array<byte, fsize> dumpArr // also not correct byte *dumpArr = new byte[fsize]; // correct, but I can't use dynamic array I need to create std::array with the file size.
You need a compile-time constant to declare arrays so you have two options: Give up the idea to create an array and use a std::vector instead: std::ifstream file("the_file"); std::vector<std::uint8_t> content(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>{}); If the file you want to read isn't supposed to change after you've compiled the program, make the file a part of the build system. Example makefile: program: source.cpp filesize.h g++ -o program source.cpp filesize.h: the_file stat --printf '#pragma once\n#define FILESIZE %sULL\n' the_file > header.h ... and use FILESIZE inside source.cpp to declare your array.
72,838,522
72,841,372
C++ how to make a series of statements atomic?
I have a program which have multiple threads running. Inside the main thread, a class variable maybe changed by operations from different threads. So I will like to make sure that within a series of steps involving the variable, no other threads may change the variable midway through that series of steps. E.g. this->a = b / c; if( this->a < d) { this->e = 7; } In the above code, how do I make sure no interruptions from other thread occur E.g. thread 2 int j = 7 / 2 this->a *= j Both threads tried to change the value of "a". How can I make sure that after this->a = b / c, the if(this->a < d) block will execute immediately before the this->a *= j statement has a chance to execute in thread 2? Thanks!
From the comments, it seems your view of a mutex is that it serves to protect a single block of code, so that no two threads can execute it simultaneously. But that is too narrow a view. What a mutex really does is ensure that no two threads can have it locked simultaneously. So you can have multiple blocks of code "protected" by the same mutex; then, whenever one thread is executing one of those blocks, no other thread can execute that block nor any of the other protected blocks. This leads to the idiom of having a mutex that protects a variable (or set of variables); meaning, you set a rule for yourself that every block of code accessing those variables must be executed with the mutex locked. A simple example (untested) could be: class foo { public: void f1(); void f2(); private: int a, e; std::mutex m; }; void foo::f1() { m.lock(); this->a = b / c; if( this->a < d) { this->e = 7; } m.unlock(); } void foo::f2() { m.lock(); int j = 7 / 2; this->a *= j; m.unlock(); } Now other threads can safely execute any combination of f1 and f2 in parallel without causing a data race or risking an inconsistent view of the data. In practice, take advantage of RAII by using something like std::scoped_lock instead: void foo::f1() { std::scoped_lock sl(m); this->a = b / c; if( this->a < d) { this->e = 7; } } Among other benefits (that would become relevant in more complex code), it automatically unlocks the mutex for you at the end of the block, so you don't have to remember to do it manually.
72,838,658
72,838,677
How can I deal with pointer assignment compile error (error: no viable overloaded "=") in C++
I'm a rookie, and when I was doing Leetcode 21. Merge Two Sorted Lists I submitted this code: /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { p1 = list1; p2 = list2; while (p1 && p2) { if (p1->val <= p2->val) { p->next = p1; p1 = p1->next; } else if (p2->val <= p1->val) { p->next = p2; p2 = p2->next; } p = p->next; } if (!p1) { p->next = p2; } if (!p2) { p->next = p1; } return head->next; } private: ListNode* p1, p2; ListNode* head = new ListNode(-101); ListNode* p = head; }; but got a compile error: error: no viable overloaded '=' p2 = list2; ~~ ^ ~~~~~ also: this->p1 = list1; this->p2 = list2; got the same error message. But after I modified the error code (inside the mergeTwoLists() function) to: ListNode* p1 = list1; ListNode* p2 = list2; The code can pass the testcases and no errors occured. Q1 : I want to know why it is necessary to implement operator "=" for such a pointer assignment (p1 or p2 are ListNode* type and list1 and list2 are also ListNode* type) issue. Q2: Also can someone show me how to implement the operator "=" according to the error message(which can passed the testcases)? Q3: Or if there is another solution (other than my above modification and implement the operator=)to this compile error message (which can passed the testcases). Thanks!
Very common error ListNode* p1, p2; should be ListNode *p1, *p2; You need to use * on both variables to make both of them pointers. Since this is confusing, and easily forgotten, most style guides recommend splitting the declaration. ListNode* p1; ListNode* p2;
72,838,717
72,838,751
Assignment and retrieval along with Post increment in single line in c++
This is the code which I ran. int minimumCardPickup(vector<int>& cards) { int N = cards.size(); int l = 0, r = 0, res = INT_MAX; unordered_map<int, int> pos; while (r < N) { if (pos.find(cards[r]) != pos.end()) { l = pos[cards[r]]; res = min(res, r - l + 1); } pos[cards[r]] = r++; //Here } return res == INT_MAX ? -1 : res; } let's take an example: cards = [1, 2, 3, 2, 4] The line with the comment should update the map to the following after 3 iterations: pos = {[1, 0], [2, 1], [3, 2]} But instead it updates the map like this: pos = {[2, 0], [3, 1]} It should have done something like this: get value of cards[r] and then assign pos[cards[r]] with the value of r and then do r++ for next iteration but instead, it did r++ then get value of cards[r] and then assign pos[cards[r]] with value of r before increment. If I do this, it works fine. pos[cards[r]] = r; r++; Can someone explain why it works like that?
As you correctly identified, the problem is here: pos[cards[r]] = r++; //Here In earlier standards: If you post-increment or post-decrement a variable, you should not read the value of it again before a sequence point (in this case, ;). This is because post-increment might occur any time during the statement (as long as the expression evaluates to the old value). From C++17, for any operation l = r, the evaluation of r is sequenced-before the evaluation of l (including side effects), so it’s a valid expression, but still not what’s expected in the code. Either do the post-increment on the left-hand side of the = (thereby restricting to c++17 and newer), or simply do the increment as a distinct statement (as you correctly specified).
72,838,808
72,839,485
C++ How to copy a part of vector into array?
I was making a copy from a large dynamic array to a small fixed size array. for (int i = 0; i <= dumpVec.size() - 16; i++) { copy(dumpArr + i, dumpArr + i + 16, temp); // to copy 16 bytes from dynamic array } But I should use a vector instead of dynamic array. How to copy 16 bytes from vector into array? for (int i = 0; i <= dumpVec.size() - 16; i++) { array<byte, 16> temp; // place to copy each 16 bytes from dumpVec(byte vector) into temp(byte array) }
copy(dumpArr + i, dumpArr + i + 16, temp); // to copy 16 bytes from dynamic array can be written as copy(&dumpArr[i], &dumpArr[i + 16], &temp[0]); // to copy 16 bytes from dynamic array and now the same code works for vector and array too. You can also use copy_n(&dumpArr[i], 16, &temp[0]);
72,839,048
72,839,119
XCode project's choice of C++ standard is not being respected
I'm playing around with XCode and C++, and I noticed that I change the C++ standard (i.e. C++98, C++11, GNU17, etc.) by clicking my project in the left sidebar. See screenshot at bottom of this post. However, when I change to C++98, the C++ statement auto x = 6; still compiles and runs with no complaints. This is bad because auto requires C++11, so clearly my setting of the standard to C++98 is not in effect. Note that when I say "still compile and run", I mean that I'm clicking the "play" button in XCode. I imagine several possibilities here: there's some super hidden "save" button that I missed that I'm required to click to actually get the setting to stick the action of "clicking the play button in XCode" does not actually use the new setting but rather uses old settings (and there needs be some kind of "make clean"-like ritual I need to do first in order to get the "play" button to respect new project settings this setting is not working at all and it's a bug in XCode Anyone know what I'm doing wrong here? I'm using XCode 13.4.1 (latest version as of July 2022) on macOS monterey on 2021 macbook pro 14 inch with M1 pro.
There's another possibility you overlooked: auto x = 6; This happens to be a perfectly valid declaration in prehistoric times. auto meant something else entirely, and traces its lineage to C. Nobody was using it, so the keyword was re-purposed in C++11. But, this just happens to be valid code. You might want to try something like: auto y = "hello world"; and then verify the behavior of your C++ compiler at various C++ levels.
72,839,318
72,839,678
How to use vector<MyObject> with ImGui::ListBox?
I'm trying to display a vector of objects in a listbox that will be rendered dynamically in every frame. This is my class and I want to display every attribute later in the listbox: class Waypoint { public: int x, y, z; char action; }; What I'm trying now as I don't really know is this: Waypoint wp1; wp1.action = 'R'; wp1.x = 100; wp1.y = 100; wp1.z = 7; Waypoint wp2; wp2.action = 'S'; wp2.x = 100; wp2.y = 100; wp2.z = 6; std::vector<Waypoint> listbox_items { wp1, wp2 }; static int listbox_item_current = 1; ImGui::ListBox("listbox::Cavebot", &listbox_item_current, listbox_items); Of course this is not working, and I'm getting this error: E0304 no instance of overloaded function "ImGui::ListBox" matches the argument list How can I display dynamically all my objects attributes in the listbox?
ImGui::ListBox takes a char* as a displayed text, so you could not use a single char. You should re-design your class like this: class Waypoint { public: int x, y, z; std::string action; }; Then use this function: bool ImGui::ListBox(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int height_in_items) Example: bool waypoint_getter(void* data, int index, const char** output) { Waypoint* waypoints = (Waypoint*)data; Waypoint& current_waypoint = waypoints[index]; *output = current_waypoint.action.c_str(); // not very safe return true; } ImGui::ListBox( "listbox::Cavebot", &listbox_item_current, waypoint_getter, listbox_items.data(), listbox_items.size() );
72,839,746
72,839,804
c++ problem | i want to NOT open the console while an program running
Ya know the console opens everytime when u execute an c++ script in any way i am making currently an GDI effect and this Console shows in the background up Here is the script but i dont think the script affects everything :/enter image description here
You should use /SUBSYSTEM:WINDOWS with WinMain. Alternatively, you could hide the console. ShowWindow(GetConsoleWindow(), SW_HIDE);
72,839,766
72,839,794
Resizing makes the window's content become thinner on each loop
I was trying to fix an issue where the window stretched out the content, and I finished fixing that. But after trying it out, it works halfway through only. Here are some images and below is the explanation of the problem: Image A: (when the app starts) Image B: (after resizing once in any direction) When I start the application, it is like Image A, a square startup window as expected, without stretching. Then, if I resize the window in any direction, it begins to stretch more and more each time I resize, as Image B shows. The resize function runs each time the window is resized thanks to this line in the main function: glutReshapeFunc(resizeCallback); Here's the function's code, which I'd assume is causing this: void resizeCallback(int w, int h) { glViewport(0, 0, w, h); glMatrixMode( GL_PROJECTION ); const GLfloat aspectRatio = (GLfloat)w / (GLfloat)h; gluOrtho2D(-aspectRatio, aspectRatio, -1.0f, 1.0f); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); } I'd appreciate it if anyone helped. It's been a year since I last used OpenGL in C++ and I never got around fixing stretched content issues.
gluOrtho2D not only sets the projection matrix, but defines an orthographic projection matrix and multiplies the current matrix by the new matrix. You need to load the Identity matrix with glLoadIdentity before gluOrtho2D: glMatrixMode(GL_PROJECTION); glLoadIdentity(); const GLfloat aspectRatio = (GLfloat)w / (GLfloat)h; gluOrtho2D(-aspectRatio, aspectRatio, -1.0f, 1.0f);
72,839,908
72,840,004
Pointer to an object
I have a problem. I am developing a small chess-like game. I am creating a class that manages the round, dividing them into 3 phases. In the first step, check if the mouse has clicked on a Token. In the second check select a location And in the third he moves the selected Token. I had thought in the first phase (after clicking on a Token) to make the token point to a pointer, and to continue phases two and three with this pointer (so as to save code when adding more tokens). But I am having problems, the program does not give errors, but when I get to the third phase it crashes. TurnSystem.h enum PHASE {pawnSelection=0, positionSelection=1, motionAnimation=2}; class TurnSystem{ private: short phase = PHASE::pawnSelection; //TOKEN Token* soldier; Token* demon; Token* A; void InizializedToken(); public: TurnSystem(); virtual ~TurnSystem(); void Update(sf::Vector2i& mousePos); }; TurnSystem.cpp TurnSystem::TurnSystem() { this->InizializedToken(); } TurnSystem::~TurnSystem() { } void TurnSystem::InizializedToken() { sf::Image image; image.loadFromFile("C:/Progect/Sprites/Soldier.png"); this->soldier= new Token(image,false,10,10,5,1,1); image.loadFromFile("C:/Progect/Dimon.png"); this->demon= new Token(image,true,6,7,6,4,4); } void TurnSystem::Update(sf::Vector2i &mousePos) { if (this->phase == PHASE::pawnSelection){ if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) { if(soldier->sprite.getGlobalBounds().contains(mousePos.x,mousePos.y)){ Token* A = soldier; phase=PHASE::positionSelection; } else if (demon->sprite.getGlobalBounds().contains(mousePos.x,mousePos.y)){ std::cout << "Enemy token, select another one \n"; } } } else if (this->phase == PHASE::positionSelection){ //doSomthing phase=PHASE::motionAnimation; } else if(this->phase == PHASE::motionAnimation){ A->move(); //the program stops here } } The Token class has a method called Move. But I don't know how to use it via the pointer Thanks in advance and sorry for any grammatical errors, I'm not native speakers
You've redeclared your A pointer hiding the version you meant to assign to. See the comments class TurnSystem{ ... Token* A; // class member A ... }; void TurnSystem::Update(sf::Vector2i &mousePos) { if (...){ if (...) { if(...){ Token* A = soldier; // this is a local variable called A phase=PHASE::positionSelection; } ... } } ... else if(...){ A->move(); // this is the class member called A } The fix is to remove the declalration. A = soldier; // now this is the class member called A
72,840,405
72,864,396
How to create something like a sniffer?
I want to create an app to monitor and save the received data (for test my program!). The device I'm working with have an API itself, and I want to create an app to get data from the device using CyPress CyAPI (FX3). For that the device should open and start streaming data. My code is something like this for now: #include <iostream> #include <thread> #include <vector> #include <tuple> #include <future> #include <DeviceAPI.h> #include <WrapperCyAPI.h> int main() { std::promise<void> prm; std::future<void> fut{ prm.get_future() }; std::thread th1{ [&prm]() { Device device; device.open(); device.init(); // init and open send/receive some data, so I don't want to get them prm.set_value(); device.getData(); device.close(); } }; std::thread th2{ [&fut]() { WrapperCyAPI usb; usb.open(); usb.init(); fut.wait(); std::vector<uint8_t> data{ usb.getData() }; usb.close(); } }; th1.join(); th2.join(); } So far so good. The device.open() and device.init() send configure parameters and receive some information and when I call device.getData(), the device sends data and I want to get that data. lets say it sends 100KB data in one endpoint, then in th2 I use WrapperCyAPI which is a wrapper of CyAPI. usb.open() and usb.init() just open the device with a handler and then with usb.getData() I just received the data. All of this works just fine, BUT when we have only one endpoint! In the usb.getData(): std::vector<uint8_t> USB::getData() { long receivedSize{ static_cast<long>(buffer.size()) }; device->EndPointOf(ENDPOINT_IN)->XferData(&buffer[0], receivedSize); return { buffer }; // imagine buffer2 is empty, a dummy vector reserved for future } There is no problem. Device sends the data and I get all of them. But when I want to get data from two endpoint (device sends the data to 2 endpoints too, lets say two 100KB in two endpoints, total data size will be 200KB) I get the error on XferData function. // ... int main() { // ... std::thread th2{ [&fut]() { WrapperCyAPI usb; usb.open(); usb.init(); fut.wait(); std::tuple<std::vector<uint8_t>, std::vector<uint8_t>> data{ usb.getData() }; usb.close(); } }; // ... } // ... std::tuple<std::vector<uint8_t>, std::vector<uint8_t>> USB:getData() { long receivedSize{ static_cast<long>(buffer1.size()) }; device->EndPointOf(ENDPOINT_IN1)->XferData(&buffer1[0], receivedSize); receivedSize = static_cast<long>(buffer2.size()); device->EndPointOf(ENDPOINT_IN2)->XferData(&buffer2[0], receivedSize); return { buffer1, buffer2 }; } For second endpoint XferData return false. Which means I get half of data (100KB) in the first endpoint, and for the second endpoint XferData return false.
After sometimes, figuring out that I should read two endpoint asynchronously not synchronously. std::tuple<std::vector<uint8_t>, std::vector<uint8_t>> USB::getData() { OVERLAPPED ov1, ov2; ov1.hEvent = CreateEvent(NULL, false, false, L"CYUSB_IN"); ov2.hEvent = CreateEvent(NULL, false, false, L"CYUSB_IN"); UCHAR* inCtx1{ device->EndPointOf(ENDPOINT_IN1)->BeginDataXfer(&buffer1[0], buffer1.size(), &ov1) }; UCHAR* inCtx2{ device->EndPointOf(ENDPOINT_IN2)->BeginDataXfer(&buffer2[0], buffer2.size(), &ov2) }; device->EndPointOf(ENDPOINT_IN1)->WaitForXfer(&ov1, 3000); device->EndPointOf(ENDPOINT_IN2)->WaitForXfer(&ov2, 3000); long buffer1Size{ static_cast<long>(buffer1.size()) }, buffer2Size{ static_cast<long>(buffer2.size()) }; device->EndPointOf(ENDPOINT_IN1)->FinishDataXfer(&buffer1[0], buffer1Size, &ov1, inCtx1); device->EndPointOf(ENDPOINT_IN2)->FinishDataXfer(&buffer2[0], buffer2Size, &ov2, inCtx2); return { buffer1, buffer2 }; }
72,840,675
72,840,945
How to create a vertical group of buttons in ImGui?
I have this ImGui menu: I want to move the "Del" button to the red selected area in the previous image. This is that part of the menu snippet: class Waypoint { public: int x, y, z; std::string action; std::string display; Waypoint(std::string action, int x, int y, int z) { this->action = action; this->x = x; this->y = y; this->z = z; this->display = action + " " + std::to_string(x) + " " + std::to_string(y) + " " + std::to_string(z); } }; static int listbox_item_current = 0; Waypoint wp1("ROPE", 100, 100, 7); Waypoint wp2("WALK", 100, 100, 6); Waypoint wp3("WALK", 110, 131, 6); std::vector<Waypoint> listbox_items{ wp1, wp2, wp3 }; if (ImGui::CollapsingHeader("Cavebot")) { ImGui::ListBox( "##listbox::Cavebot", &listbox_item_current, waypoint_getter, listbox_items.data(), listbox_items.size() ); ImGui::SameLine(); if (ImGui::Button("Clean")) listbox_items.clear(); ImGui::SameLine(); if (ImGui::Button("Del")) listbox_items.erase(listbox_items.begin() + listbox_item_current); How can I move the "Del" button to be below the "Clean" button? EDIT: Testing removing ImGui::SameLine(); between both buttons:
I normally use ImGui::SetCursorPos() for this, as suggested by @thedemons. But there is also ImGui::BeginGroup();. Remove the last ImGui::SameLine(); and wrap the two buttons in Begin/EndGroup. Here's a simplified example: ImGui::Begin("Window"); ImGui::Button("x", ImVec2(200,100)); ImGui::SameLine(); ImGui::BeginGroup(); ImGui::Button("Alpha"); ImGui::Button("Beta"); ImGui::EndGroup(); ImGui::End();
72,841,415
72,841,514
Is something wrong with my tasks.json settings?
I've been trying to use VSCode's tasks.json settings to automate the compiling process of my code. When I run the task I get an infinite loading loop, no errors are shown just the loading symbol and nothing happens. { "version": "2.0.0", "tasks": [ { "label": "MSVC Build", "type": "shell", "options": { "shell": { "executable": "C:/Program Files/Microsoft Visual Studio/2022/Community/Common7/Tools/LaunchDevCmd.bat" } }, "command": "cl {$file} user32.lib && del *.obj" } ] } I've tried to compile different files in case my code was wrong, the results remain the same, here's an example. #include <iostream> using namespace std; int y = 6; int x = 4; int main(){ cout << y + x; } Since there are no error messages there's nothing that can point me to the problem. This is what the console is displaying It stalls before running the command and I have no idea why.
"executable": "C:/Program Files/Microsoft Visual Studio/2022/Community/Common7/Tools/LaunchDevCmd.bat" This above launches cmd.exe in the terminal of Visual Studio Code. Since LaunchDevCmd.bat never finishes, the queued command cl {$file} user32.lib && del *.obj does not run, until you enter exit in the running cmd.exe inside the terminal. You definitely wanted "executable": "C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Auxiliary/Build/vcvars64.bat" Or any other .bat file in C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build. It will not run a new cmd.exe, it will run directly in the terminal of Visual Studio Code.
72,841,438
72,841,469
How to store array data as map key or increment frequency if array already in map?
My code: map<array<byte, aes>, int> possible; array<byte,aes> temp; if (!possible.count(temp)) // if not found possible.insert(pair<array<byte,aes>,int>(temp,1)); // insert else possible[temp]++; // if found increment frequency I need to use an array with its data as a map key. An integer indicates the frequency of occurrence of the array. However, the new array is only written the first time, the other times the code considers it to be the same array. As I understand it, the program takes the address of the array, not its data. How to pass an array with data to the map instead of the address of the array? I know that in Qt this code works fine: QMap<QByteArray,int> possible; QByteArray temp; if(!possible.count(temp)) // if not found possible.insert(temp, 1); // insert else possible[temp]++; // if found increment frequency What is alternative for std::array and std::map to do this?
In C++ this code will work fine possible[temp]++; If temp exists then it's frequency will be incremented. If it does not exist then it will be inserted with a frequency of 0, which will then be incremented. This gives you exactly the same result as your code. Looking at the documentation for QMap, it seems the above code would also work on Qt. Sometimes (not often) things are easier than you imagined.
72,841,621
72,841,670
finding all the values with given key for multimap
I am searching for all pairs for a particular key in a multimap using the code below. int main() { multimap<int,int> mp; mp.insert({1,2}); mp.insert({11,22}); mp.insert({12,42}); mp.insert({1,2}); mp.insert({1,2}); for (auto itr = mp.find(1); itr != mp.end(); itr++) cout << itr->first<< '\t' << itr->second << '\n'; }
You're calling find only a single time in your code. It's perfectly acceptable for this call to return the same value as mp.begin() resulting in you iterating though all the entries in the map before reaching mp.end(). You can use the equal_range member function to get iterators for the start and end of the elements with key 1: for (auto[itr, rangeEnd] = mp.equal_range(1); itr != rangeEnd; ++itr) { std::cout << itr->first<< '\t' << itr->second << '\n'; }
72,841,913
72,841,956
Why doesn't RVO happen with structured bindings when returning a pair from a function using std::make_pair?
Consider this code, which defines a simple struct Test (with a default constructor and copy constructor) and returns a std::pair <Test, Test> from a function. #include <iostream> #include <utility> using namespace std; struct Test { Test() {} Test(const Test &other) {cout << "Test copy constructor called\n";} }; auto func() { return make_pair(Test(), Test()); } int main() { auto [a, b] = func(); // Expectation: copies for a and b are both elided return 0; } Surprisingly, the output is Test copy constructor called Test copy constructor called Whereas modifying func to auto func() { return Test(); } int main() { Test a(func()); return 0; } Results in the copy constructor not being called. My g++ version is 11.2.0, so I thought that copy elision was guaranteed in this case, but I could be wrong. Could someone confirm if I am misunderstanding RVO?
std::make_pair is a function that takes the arguments by reference. Therefore temporaries are created from the two Test() arguments and std::make_pair constructs a std::pair from these, which requires copy-constructing the pair elements from the arguments. (Move-constructing is impossible since your manual definition of the copy constructor inhibits the implicit move constructor.) This has nothing to do with structured bindings or RVO or anything else besides std::make_pair. Because std::pair is not an aggregate class, you cannot solve this by simply constructing the std::pair directly from the two arguments either. In order to have a std::pair construct the elements in-place from an argument list you need to use its std::piecewise_construct overload: auto func() { return std::pair<Test, Test>(std::piecewise_construct, std::forward_as_tuple(), std::forward_as_tuple()); }
72,841,986
72,842,271
why does C++ allow a declaration with no space between the type and a parenthesized variable name?
A previous C++ question asked why int (x) = 0; is allowed. However, I noticed that even int(x) = 0; is allowed, i.e. without a space before the (x). I find the latter quite strange, because it causes things like this: using Oit = std::ostream_iterator<int>; Oit bar(std::cout); *bar = 6; // * is optional *Oit(bar) = 7; // * is NOT optional! where the final line is because omitting the * makes the compiler think we are declaring bar again and initializing to 7. Am I interpreting this correctly, that int(x) = 0; is indeed equivalent to int x = 0, and Oit(bar) = 7; is indeed equivalent to Oit bar = 7;? If yes, why specifically does C++ allow omitting the space before the parentheses in such a declaration + initialization? (my guess is because the C++ compiler does not care about any space before a left paren, since it treats that parenthesized expression as it's own "token" [excuse me if I'm butchering the terminology], i.e. in all cases, qux(baz) is equivalent to qux (baz))
One requirement when defining the syntax of a language is that elements of the language can be separated. According to the C++ syntax rules, a space separates things. But also according to the C++ syntax rules, parentheses also separate things. When C++ is compiled, the first step is the parsing. And one of the first steps of the parsing is separating all the elements of the language. Often this step is called tokenizing or lexing. But this is just the technical background. The user does not have to know this. He or she only has to know that things in C++ must be clearly separted from each others, so that there is a sequence "*", "Oit", "(", "bar", ")", "=", "7", ";". As explained, the rule that the parenthesis always separates is established on a very low level of the compiler. The compiler determines even before knowing what the purpose of the parenthesis is, that a parenthesis separates things. And therefore an extra space would be redundant. When you ever use parser generators, you will see that most of them just ignore spaces. That means, when the lexer has produced the list of tokens, the spaces do not exist any more. See above in the list. There are no spaces any more. So you have no chance to specify something that explicitly requires a space.
72,842,307
72,842,940
Measuring packet per second for connected clients IP addresses
How can we determine the packet rate of clients connected to our server in case of multi client server using Winsock. The idea I came up with is keeping a frequency map for IP addresses of all the clients and storing the packets count for some arbitrary amount k seconds. Now after k seconds we traverse the map and see what IP addresses have more than 100*k packets, now we block these IP addresses. After every k seconds we empty the map and start again. PSEUDO CODE: (k = 10) map<string,int> map; void calculate() { for(auto &ip : map){ if(ip.second>10000) blacklist(ip.first); } map.clear(); Sleep(10000); calculate(); } int s = socket(AF_INET,SOCK_STREAM, IPPROTO_TCP); // bind(), listen() calculate(); while(1) { if(recv(s,buff,len)>0) map[client.ip]++; }
Per comments: If someone is sending too fast, I'd like to block him permanently rather than receiving his messages less frequently. Something like this is what I'm trying to achieve If this was UDP, I'd 100% be onboard with what you are trying to do and give the code I have. But this is TCP and your assumptions are flawed. Let's say the sender invokes this: send(sock, buffer, 1000, 0); And then on the other side, you invoke this: recv(sock, buffer, 1000, 0) Did you know that recv may do any of the following: It may return any value less than or equal to 1000. It could return 1 and expect you to invoke it another 999 times to consume the entire message. One of the biggest confusions with TCP socket is assuming that each send call mirrors a recv call in a 1:1 fashion. Lots of buggy apps have shipped that way. More probably, you'll get 1 or 2 recv calls because of IP fragmentation and/or TCP segmentation. How fast you invoke recv also But this is never guaranteed or expected to be consistent. What you observe with local testing on your on LAN will not resemble actual internet behavior. How many recv calls you get has nothing to do with how many actual IP packets or TCP segments, because "the packets" will get coalesced anyway by the TCP stack on the recv side. Similarly, how many bytes you pass to send doesn't influence the packet count. TCP, including any number of routers and gateways in between, may split up this 1000 byte stream into additional fragments and segments. I'm going to offer two suggestions: Detect flood attacks by counting application protocol messages and/or the size of these application protocol messages - but not individual recv calls. That is, as you recv data, you'll accumulate this data stream into logical protocol messages based on a fixed size of bytes or a delimiter based message structure and pass it up to a higher part of your application for processing. Do the incremental count then. Instead of trying to thwart flood attacks at the message level, it's probably simpler to just throttle clients to a fixed rate of data. That is, each time you recv data, count how many bytes it returns and use with a timer to measure an incoming bytes/second rate. If the remote side exceeds your limit, insert sleep statements in between recv calls. This will implicitly make TCP slow the other side down from sending too fast.
72,842,442
72,846,416
How to draw a line along the Z axis in openGL
I'm stuck drawing a line along the Z-axis. I have checked the related topic that OpenGL Can't draw z axis but even if I change my camera position, I still can't see my line; meanwhile, I can see a square draw in XZ-plane. here is my code: int main() { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); GLFWwindow* window = glfwCreateWindow(1024, 768, "some program", NULL, NULL); glfwMakeContextCurrent(window); glewExperimental = true; // Needed for core profile if (glewInit() != GLEW_OK) { std::cerr << "Failed to create GLEW" << std::endl; glfwTerminate(); return -1; } glClearColor(0.2f, 0.298f, 0.298f, 1.0f); // Compile and link shaders here ... int shaderProgram = compileAndLinkShaders(); int lineVao = createLineVertexArrayObject(LineArray, sizeof(LineArray)); while (!glfwWindowShouldClose(window)) { GLuint worldMatrixLocation = glGetUniformLocation(shaderProgram, "worldMatrix"); // Each frame, reset color of each pixel to glClearColor glClear(GL_COLOR_BUFFER_BIT); glm::mat4 translationMatrix = glm::mat4(1.0f); glUniformMatrix4fv(worldMatrixLocation, 1, GL_FALSE, &translationMatrix[0][0]); glUseProgram(shaderProgram); glBindVertexArray(lineVao); glDrawArrays(GL_LINES, 0, 2); glBindVertexArray(0); glfwSwapBuffers(window); // Detect inputs glfwPollEvents(); if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); if (glfwGetKey(window, GLFW_KEY_1) == GLFW_PRESS)//see the object in other direction { glm::mat4 viewMatrix = glm::lookAt(glm::vec3(0.0f, 1.0f, 0.0f), // eye glm::vec3(0.0f, 0.0f, -1.0f), // center glm::vec3(0.0f, 1.0f, 0.0f));// up GLuint viewMatrixLocation = glGetUniformLocation(shaderProgram, "viewMatrix"); glUniformMatrix4fv(viewMatrixLocation, 1, GL_FALSE, &viewMatrix[0][0]); } } // Shutdown GLFW glfwTerminate(); return 0; } int createLineVertexArrayObject() int createLineVertexArrayObject(const glm::vec3* vertexArray, int arraySize) { // Create a vertex array GLuint vertexArrayObject; glGenVertexArrays(1, &vertexArrayObject); glBindVertexArray(vertexArrayObject); // Upload Vertex Buffer to the GPU, keep a reference to it (vertexBufferObject) GLuint vertexBufferObject; glGenBuffers(1, &vertexBufferObject); glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject); glBufferData(GL_ARRAY_BUFFER, arraySize, vertexArray, GL_STATIC_DRAW); glVertexAttribPointer(0, // attribute 0 matches aPos in Vertex Shader 2, // size GL_FLOAT, // type GL_FALSE, // normalized? 2 * sizeof(glm::vec3), // stride - each vertex contain 2 vec3 (position, color) (void*)0 // array buffer offset ); glEnableVertexAttribArray(0); glVertexAttribPointer(1, // attribute 1 matches aColor in Vertex Shader 2, GL_FLOAT, GL_FALSE, 2 * sizeof(glm::vec3), (void*)sizeof(glm::vec3) // color is offseted a vec3 (comes after position) ); glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); return vertexArrayObject; } my lineArray[] was like this glm::vec3 LineArray[] = { glm::vec3(-0.5f, 0.0f, -0.5f), // position glm::vec3(1.0f, 0.0f, 0.0f), // color (yellow) glm::vec3(0.0f, 0.0f, 0.0f), // position glm::vec3(1.0f, 0.0f, 0.0f), // color (yellow) }; But I can only see a horizontal line if I change my camera position.
Assuming that you want to draw a 3D line, the size argument of glVertexAttribPointer is wrong. By setting it to two, you tell OpenGL to read only two values and add 0 for z. Set the size to 3 as in glVertexAttribPointer(0, // attribute 0 matches aPos in Vertex Shader 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 2 * sizeof(glm::vec3), // stride - each vertex contain 2 vec3 (position, color) (void*)0 // array buffer offset ); and the z-value will also be read. Note, that your color binding has the same problem. You only read the read and green value, but not the blue value.
72,842,534
72,842,628
Manually validate date/time comes before another
I have to manually verify a time/date format of the type day_hh:mm:ss so 1_09:00:01 comes before another and return a boolean. Ive come with this but there are still some tests that are not validated correctly. Any ideas where I could refactor? bool DateHour::operator<(const DateHour& date_hour) const{ if(days <= dh.days){ if(hours <= dh.hours || dh.days > days){ if(minutes <= dh.minutes || dh.hours > hours || dh.days > days ){ if(seconds < dh.seconds || dh.minutes > minutes || dh.hours > hours || dh.days > days) return true; else if(days == dh.days && hours == dh.hours && minutes == dh.minutes && seconds == dh.seconds) return false; return true; } return false; } return false; } return false;
Attempting to squish days/hours/minutes/seconds together into one combined chunk of logic, in the shown code, leads to many hard to understand logical flaws. The easiest way to solve a complicated problem is break it up into smaller problems, and solve them individually. if(days < dh.days) return true; if(days > dh.days) return false; And now the problem is solved when the number of days are different, and the logic is provably correct. At this point, a brilliant observation becomes obvious: now that the days are the same, the same exact logic simply gets repeated for the hours: if(hours < dh.hours) return true; if(hours > dh.hours) return false; Still just as simple, and just as provably correct. And repeat the exact same thing for minutes and seconds. In the end, everything is the same, so the grand conclusion is just a return false; "The more you overthink the plumbing, the easier it is to clog up the drain" -- Scotty, Star Trek III.
72,842,789
72,850,198
What are all the requirements of a QObject derived class?
I'm working on my first non-trivial project using the Qt Framework and to help maintain consistency across documents and to ensure I don't forget some small requirement I've decided to make a template document demonstrating the member functions, macros, etc. needed to subclass QObject. I also want to be able to fully utilize the Meta Object system. Am I missing anything or misunderstanding anything? Also feel free to give any general C++ critiques as necessary. I'm especially concerned with the issue of whether or not to include a copy constructor. Is that only necessary for classes not derived from QObject? Requirements (links are to the document I got the requirements from) Public Default Constructor (link) Public Copy Constructor (see 1) (but conflicts with this) Public Destructor (see 1) Use the Q_OBJECT Macro (link) Ensure Properties Are Accessible with the Q_PROPERTY(...) Macro (link) Declare the Type with Q_DECLARE_METATYPE(T) in the Header (link) (link) Declare any Enums Used with Q_ENUM(E) in the Header (link) Template Header // Include guards #ifndef CLASSNAME_H #define CLASSNAME_H // Include statements #include <QObject> #include <T.h> // Enum definition enum E{ E0, E1, E2 }; // Q_ENUM Macro Q_ENUM(E) // Class declaration class ClassName : public QObject { // Q_OBJECT Macro Q_OBJECT // Q_PROPERTY Macros Q_PROPERTY(T* memberA READ memberA WRITE setMemberA NOTIFY memberAChanged) Q_PROPERTY(int memberB READ memberB WRITE setMemberB NOTIFY memberBChanged) Q_PROPERTY(E memberC READ memberC WRITE setMemberC RESET resetMemberC) public: // Constructors and Destructor ClassName(QObject *parent = nullptr); ClassName() = default; ClassName(const ClassName&) = default; ~ClassName(); // Getters T* memberA() const {return m_memberA;} int memberB() const {return m_memberB;} E memberC() const {return m_memberC;} // Setters void setMemberA(T* newA); void setMemberB(int newB); void setMemberC(E newC); signals: void memberAChanged(T*); void memberBChanged(int); public slots: void resetMemberC(); private slots: private: // Data Members T* m_memberA; int m_memberB; E m_memberC; }; // Meta Object Type Declaration Q_DECLARE_METATYPE(TypeName); // End include guard #endif // CLASSNAME_H The source file to accompany this header would likely be trivial, so I won't include it here. Though if anyone thinks it would be helpful to demonstrate some requirement or functionality, I'd be happy to write it out.
As Jeremy Friesner suggested, the requirements are not that strict. The situation is more like this: If your class uses signals and/or slots, it must both have the Q_OBJECT macro and be derived from QObject, If it only uses other meta-object functionality, such as Q_PROPERTY declarations, it can use the Q_GADGET macro and need not be derived from QObject, If it doesn't need any of that, but should still be compatible with Qt templates like QVariant, it should be declared with Q_DECLARE_METATYPE. The same applies to enums and Q_ENUM. A Q_PROPERTY/Q_INVOKABLE interface is only really needed if you need your class to be interoperable with QML code. As for your other question, yes that is an important difference between QObjects and non-QObjects. The metatype must be copyable, which is why that is required of types you manually declare as metatypes, and also why the system instead uses pointers for QObject types, which are not copyable themselves. A minimal QObject declaration could start like this: #ifndef CLASSNAME_H #define CLASSNAME_H #include <QObject> // Enums in the global namespace cannot be registered; they must be enclosed // in a class and registered with Q_ENUM, or in a namespace declared as // Q_NAMESPACE and registered with Q_ENUM_NS class ClassName : public QObject { Q_OBJECT public: // Default constructor, with explicit specifier to prevent accidental // implicit conversion from a QObject* explicit ClassName(QObject *parent = nullptr); }; // ClassName* is automatically declared as a metatype #endif // CLASSNAME_H In general I'd recommend the "rule of zero": if possible, do not declare a destructor, nor any copy and move operations, and leave them to the compiler. Of course I also recommend all of the other guidelines there, if you have the time!
72,843,016
72,843,033
"if" statement syntax differences between C and C++
if (1) int a = 2; This line of code is valid C++ code (it compiles at the very least) yet invalid C code (doesn't compile). I know there are differences between the languages but this one was unexpected. I always thought the grammar was if (expr) statement but this would make it valid in both. My questions are: Why doesn't this compile in C? Why does this difference exist?
This is a subtle and important difference between C and C++. In C++ any statement may be a declaration-statement. In C, there is no such thing as a declaration-statement; instead, a declaration can appear instead of a statement within any compound-statement. From the C grammar (C17 spec): compound-statement: "{" block-item-listopt "}" block-item-list: block-item | block-item-list block-item block-item: declaration | statement From the C++ grammar (C++14 spec): compound-statement: "{" statement-seqopt "}" statement-seq: statement | statement-seq statement statement: ... | declaration-statement | ... It is not clear why this difference exists, it is just the way the languages evolved. The C++ syntax dates all the way back to (at least) C++85. The C syntax was introduced sometime between C89 and C99 (in C89, declarations had to be at the beginning of a block) In the original 85 and 89 versions of C++, the scope of a variable defined in a declaration-statement was "until the end of the enclosing block"). So a declaration in an if like this would not immediately go out of scope (as it does in more recent versions) and instead would be in scope for statements following the if in the same block scope. This could lead to problems with accessing uninitialized data when the condition is false. Worse, if the var had a non-trivial destructor, that would be called when the scope ended, even if it had never been initialized! I suspect trying to avoid these kinds of problems is what led to C adopting a different syntax.
72,843,254
72,843,314
VSCode compile C++ with external classes - undefined reference to `MyClass::MyClass()'
Error when compiling my main file & external Class file using VScode. file structure: project/ --main.cpp --MyClass.cpp --MyClass.h MyClass.h #ifndef MY_CLASS_H #define MY_CLASS_H class MyClass { public: MyClass(); }; #endif MyClass.cpp #include "MyClass.h" #include <iostream> #include <string> MyClass::MyClass() { std::cout << "MyCLass is created" << std::endl; } main.cpp #include <iostream> #include <string> #include "MyClass.h" int main() { MyClass myClass; return 0; } Compile error: main.cpp:9: undefined reference to `MyClass::MyClass()'
Change main.cpp's includes to: #include <iostream> #include <string> #include "MyClass.cpp" By including MyClass.cpp in main.cpp and compiling like this: g++ -o main main.cpp you end up including MyClass.h by virtue of it being included in MyClass.cpp. By including MyClass.cpp, you can successfully compile. If you want to keep your code as it currently is, you can instead change your compilation to be: g++ -o main main.cpp MyClass.cpp Which will include MyClass.cpp in compilation.
72,843,313
72,843,487
Happens Before relationship in the same thread
I am reading the book "C++ Concurrency in Action" section 5.3 on Memory Model of C++ and listing 5.5 below confuses me: std::atomic<bool> x,y; std::atomic<int> z; void write_x_then_y() { // Is there a Happens-Before relationship for statement (1) and (2) below? x.store(true,std::memory_order_relaxed); // --> (1) y.store(true,std::memory_order_relaxed); // --> (2) } void read_y_then_x() { while(!y.load(std::memory_order_relaxed)); if(x.load(std::memory_order_relaxed)) ++z; } int main() { x=false; y=false; z=0; std::thread a(write_x_then_y); std::thread b(read_y_then_x); a.join(); b.join(); assert(z.load()!=0); } What confuses me is function void write_x_then_y(). The author says "This time the assert at the end of main() can fire" and statement (1) on atomic variable x has a "happens-before" relationship with statement (2) on atomic variable y. But I thought with std::memory_order_relaxed, there is no synchronization between different atomic variables, and compiler/CPU can reorder these two statements without violating the program semantics. The happensbefore relationships from listing 5.5 are shown in figure 5.4, along with a possible outcome.
An evaluation which is sequenced-before another evaluation also happens-before it. Sequenced-before is a relation between evaluations in the same thread and independent of synchronization mechanism like e.g. atomic load/stores with non-relaxed memory orders. Happens-before just extends the sequenced-before relation for evaluation order from the single-threaded case to the multi-threaded case by incorporating synchronization mechanisms between threads. See https://en.cppreference.com/w/cpp/atomic/memory_order for exact definitions. An evaluation in one statement preceding another statement is always sequenced-before the latter. (Basically there is a sequence point between two statements, although that term is not used anymore since C++11.) The compiler can reorder the two relaxed stores. That doesn't affect the happens-before relation though. Just because two stores (on different atomics) happen-before one another does not imply that the stores can't be observed in a different order by another thread, as demonstrated by the example in the diagram. You would need to establish a happens-before relation between the loads and stores to prevent the shown outcome. And for that inter-thread ordering in some way is required, e.g. via release/acquire atomic operations. Basically, you would need to establish some arrow betweeen the gray boxes in the diagram.
72,843,628
72,845,893
Getting buffer overflow even though I have included the condition that avoids buffer flow (Question 74. Search a 2D Matrix) from leetcode
I was solving Q 74. Search a 2D Matrix from leetcode and I am getting heap buffer overflow error for my solution even though I have included the statements which should avoid buffer overflow which are: row = (t1 + (t2 - t1) / 2) col = (t1 + (t2 - t1) / 2) Here is my code: bool searchMatrix(vector<vector<int>>& matrix, int target) { int row, col, t1, t2, rows = matrix.size(), cols = matrix[0].size(); t1 = 0, t2 = rows - 1; while (t1 <= t2) { row = (t1 + (t2 - t1) / 2); if (target > matrix[row][cols - 1]) t1 = row + 1; else if (target < matrix[row][cols - 1]) t2 = row - 1; else break; } t1 = 0, t2 = matrix[0].size(); while (t1 <= t2) { col = (t1 + (t2 - t1) / 2); if (target > matrix[row][col]) t1 = col + 1; else if (target < matrix[row][col]) t2 = col - 1; else if (target == matrix[row][col]) return true; } return false; } Test Case it showed error for Last executed input [[1,3,5,7],[10,11,16,20],[23,30,34,60]] 13 Runtime Error Details: ================================================================= ==33==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000000200 at pc 0x000000345c27 bp 0x7fff3ffa6370 sp 0x7fff3ffa6368 READ of size 4 at 0x602000000200 thread T0 #2 0x7ffbc11d20b2 (/lib/x86_64-linux-gnu/libc.so.6+0x270b2) 0x602000000200 is located 0 bytes to the right of 16-byte region [0x6020000001f0,0x602000000200) allocated by thread T0 here: #7 0x7ffbc11d20b2 (/lib/x86_64-linux-gnu/libc.so.6+0x270b2) Shadow bytes around the buggy address: 0x0c047fff7ff0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0x0c047fff8000: fa fa fd fa fa fa fd fa fa fa fd fa fa fa fd fa 0x0c047fff8010: fa fa fd fd fa fa fd fa fa fa fd fa fa fa fd fd 0x0c047fff8020: fa fa fd fa fa fa fd fa fa fa fd fd fa fa fd fa 0x0c047fff8030: fa fa fd fa fa fa fd fa fa fa fd fa fa fa 00 00 =>0x0c047fff8040:[fa]fa fd fa fa fa fd fa fa fa 00 00 fa fa fd fa 0x0c047fff8050: fa fa fd fa fa fa 00 00 fa fa fa fa fa fa fa fa 0x0c047fff8060: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa 0x0c047fff8070: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa 0x0c047fff8080: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa 0x0c047fff8090: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa Shadow byte legend (one shadow byte represents 8 application bytes): Addressable: 00 Partially addressable: 01 02 03 04 05 06 07 Heap left redzone: fa Freed heap region: fd Stack left redzone: f1 Stack mid redzone: f2 Stack right redzone: f3 Stack after return: f5 Stack use after scope: f8 Global redzone: f9 Global init order: f6 Poisoned by user: f7 Container overflow: fc Array cookie: ac Intra object redzone: bb ASan internal: fe Left alloca redzone: ca Right alloca redzone: cb Shadow gap: cc ==33==ABORTING What am I missing?
t2 = matrix[0].size(); is out-of-bounds. Did you mean t2 = cols - 1;
72,843,678
72,844,511
Cant make comparison between two values as total 1 is corrupted and become total 2 value
i have a problem. my total1 and total2 cant make comparison. my program will show that player 2 wins even player 1 score higher. so when i cout total1 and total2, it shows that total 1 value is corrupted and become total2 value and thats why they can compare. is it because if that turn for player 2 has came to calculate, they just ignore total 1 value? help me please anyone. i = turn. I make i as odd number because it indicates its player 1's turn.total 1 = player 1's score. total 2 = player 2's score if (i == 1 || i == 3 || i == 5 || i == 7 || i == 9) { cout << endl << "Your mark for this round is " << total1; } if (i == 2 || i == 4 || i == 6 || i == 8 || i == 10) { cout << endl << "Your mark for this round is " << total2; } if (i == 2 || i == 4 || i == 6 || i == 8 || i == 10) { if (total1 > total2) { cout << "player 1 wins"; cout << endl << "Total 1: " << total1 << " while total 2: " << total2; } else { cout << endl << "player 2 wins"; cout << endl << "Total 1: " << total1 << " while total 2: " << total2; } }
So essentially your code is this for (int i = 1 ; i <= count; ++i) { ... float total1 = 0, total2 = 0; total1 = ...; total2 = ...; if (i == 1 || i == 3 || i == 5 || i == 7 || i == 9) cout << endl << "Your mark for this round is " << total1; if (i == 2 || i == 4 || i == 6 || i == 8 || i == 10) cout << endl << "Your mark for this round is " << total2; if (i == 2 || i == 4 || i == 6 || i == 8 || i == 10) { if (total1 > total2) { cout << "player 1 wins"; cout << endl << "Total 1: " << total1 << " while total 2: " << total2; } else { cout << endl << "player 2 wins"; cout << endl << "Total 1: " << total1 << " while total 2: " << total2; } } } Can you see the problem now I've reduced the code? I think it is this. You calculate total1 and total2 each time round the loop. But you print total1 only when i is odd, but you compare total1 with total2 only when i is even. I imagine that you are expecting the printed value to be the same as the value used in the comparison, but they aren't. It's a different time round the loop, so the variable value is different. I think maybe you realise this is the root of the problem. So what to do about it? It's your code so it's your decision, but I suggest a redesign. How about instead of the loop being one players round (and alternating between player 1 and player 2) make the loop so that it does one round for both players. That way you don't have the problem of needed a variable from one iteration of the loop on the next iteration of the loop. And as a bonus you don't have to do all that messing around with odd and even numbers. Not the only solution, but it's the redesign that suggests itself to me.
72,844,051
72,844,087
using RtlCompareString to compare user data crashes OS
I have the following code which is responsible to receive and send data between my mini-filter driver and user-mode: NTSTATUS MiniSendRecv(PVOID portcookie, PVOID InputBuffer, ULONG InputBufferLength, PVOID OutputBuffer, ULONG OutputBufferLength, PULONG RetLength) { PCHAR msg = "Hi User"; PCHAR userData = (PCHAR)InputBuffer; DbgPrintEx(0, 0, "User said: %d:%s\n", strlen(userData), userData); DbgPrintEx(0, 0, "Before comparing strings\n"); if (RtlCompareString(userData, (PCHAR)"status=stop", TRUE) == 0) { DbgPrintEx(0, 0, "stop requested\n"); } //if((PCHAR)InputBuffer.contains("status=stopservice")) if (strlen(msg) > OutputBufferLength) { DbgPrintEx(0, 0, "message length too big\n"); return STATUS_SUCCESS; } strncpy((PCHAR)OutputBuffer, msg, 500); return STATUS_SUCCESS; } WinDBG output: User said: 11:status=stop Before comparing strings KDTARGET: Refreshing KD connection *** Fatal System Error: 0x0000003b (0x00000000C0000005,0xFFFFF8046D001E82,0xFFFF8580E9924C20,0x0000000000000000) Break instruction exception - code 80000003 (first chance) A fatal system error has occurred. Debugger entered on first try; Bugcheck callbacks have not been invoked. A fatal system error has occurred. nt!DbgBreakPointWithStatus: fffff804`6cdffc70 cc int 3 As you can see the data is received just fine, but as soon as it hit RtlCompareString, the driver crashes causing the OS to crash as well. Also prior to using PCHAR userData, I was doing if (RtlCompareString((PCHAR)InputBuffer, (PCHAR)"status=stop", TRUE) == 0) but that didn't do any good as well. Can anyone tell me what is wrong here? when I call RtlCompareString against OutputBuffer, it works just fine.
RtlCompareString compares counted strings. What you have are null terminated strings. Just use the regular strcmp function, or since you seem to be trying to do a case insensitive string comparison you could try the non-standard _stricmp function.
72,844,097
72,844,480
how to make cin only accept a single character and int accept only numbers?
How can I make cin accept only a single letter in char datatypes and numbers only in double/int datatypes. #include <iostream> using namespace std; int main (){ char opt; int num1, num2, sum; cout << "A. Addition" << endl << "B. Subtraction" << endl; cout << "Enter option: "; cin >> opt; //if I put "ab" here, I want to make cin only read the first letter if possible. switch(opt){ case 'A': case 'a':{ cout << "Enter first number: "; cin >> num1; //accept numbers only cout << "Enter second number: "; cin >> num2;//accept numbers only sum = num1+num2; cout << "The sum is " << sum; break; } } }
By definition, operator>> reading into a char will read in exactly 1 character, leaving any remaining input in the buffer for subsequent reading. You have to validate the read is successful and the character is what you are expecting before using it. And likewise, operator>> reading into an int will read in only numbers. You have to validate the read is successful before using the number, and discard any unused input if the read fails to return a valid number. Try something like this: #include <iostream> #include <string> #include <limits> using namespace std; char ReadChar(const char* prompt) { string s; do { cout << prompt << ": "; if (!(cin >> s)) throw ...; if (s.length() == 1) break; //cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << "Invalid input. Enter a single character" << endl; } while (true); return s[0]; } char ReadInt(const char* prompt) { int value; do { cout << prompt << ": "; if (cin >> value) break; cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << "Invalid input. Enter a valid number" << endl; } while (true); return value; } int main() { char opt; int num1, num2, result; cout << "A. Addition" << endl << "B. Subtraction" << endl; opt = ReadChar("Enter option"); switch (opt) { case 'A': case 'a': { num1 = ReadInt("Enter first number"); num2 = ReadInt("Enter second number"); result = num1 + num2; cout << "The sum is " << result << endl; break; } case 'B': case 'b': { num1 = ReadInt("Enter first number"); num2 = ReadInt("Enter second number"); result = num1 - num2; cout << "The difference is " << result << endl; break; } default: { cout << "Invalid option" << endl; break; } } }
72,844,799
72,844,859
insertion in unordered map in c++
#include<iostream> #include<unordered_map> #include<list> #include<cstring> using namespace std; class Graph { unordered_map<string, list<pair<string, int>>>l; public: void addedge(string x, string y, bool bidir, int wt) { l[x].push_back(make_pair(y, wt)); if (bidir) { l[y].push_back(make_pair(x, wt)); } } }; int main() { Graph g; g.addedge("A", "B", true, 20); return 0; } unordered map in c++ dont uses push_back() function for insertion then how this unordered map 'l' is using push_back() function.
When you use the subscript operator on l, like in l[x], it returns a reference to the value mapped to the key x (or inserts a default constructed value and returns a reference to that). In this case, the type of the value is a std::list<std::pair<std::string, int>> and that type has a push_back member function. It's the same as this: std::list<std::pair<std::string, int>>& listref = l[x]; listref.push_back(make_pair(y, wt));
72,844,949
72,847,501
Scalability Qt 5.15 Android
Since it is incredibly difficult to find a developer of android applications for qt, I will ask a question here, suddenly someone was doing this. How to solve the scalability problem on different devices? Ideally, the application should look the same on all screens, from m/hdmi to xhdpi, if there were only 6 types of screens, the task would be much easier, but in fact there are a huge number of phones with a variety of screen sizes, for example, 1280x2500. Everything is clear with icons, qt under the hood takes icons from folders 20x20, 20x20@2 etc. But with the positioning and sizes of fields, buttons, etc., not everything is so simple, in any case margin and padding will be needed during development, sometimes even a static size needs to be set, but how to make them look the same is the question. The official Qt documentation suggests using layouts, but for example on the authorization page, where there is a large logo and 2-3 fields, it is difficult to use layouts, and there are many examples of pages where layouts would be very difficult to use. If without layouts, qt suggests doing something like this: height: Screen.height / 13.63321 anchors.leftMargin: Screen.width / 31.5764 But I'm not sure if this is the right way, it looks strange. There is also an option to use: property int dpi: Screen.pixelDensity * 25.4 But this method does not always work, perhaps there is some way that I do not know about. If you have been developing for android on qt, please tell how you solved this problem?
In our case, we did not want to fill entire Pad and/or TV screen, and our appraoch for handling responsive-size was to: Make size-preset: find our prefered screen-size-preset, on which we base all view constants (sizes). We did pick 320x548, which is smallest iPhone safe-area. Fit-to-screen: hard-code said size-preset into a helper-class, which does calculate and resize said-constants to fit on current-screen. Where we always use short-dimension (320) in calculation (but long-dimension can be used instead, at least, for views that support vertical-scroll-bar). Document: mention screen-preset in README.md file. Example
72,845,811
72,848,384
Does localtime return a heap allocated tm*
As you know the <time.h> standard header defines the struct tm and a function called localtime. Does localtime make a heap allocation? Or is it allocated in the stack? It returns a pointer but this could be just a pointer to the stack value, right?
The relevant part of the C Standard (C18) has this language: 7.27.3 Time conversion functions Except for the strftime function, these functions each return a pointer to one of two types of static objects: a broken-down time structure or an array of char. Execution of any of the functions that return a pointer to one of these object types may overwrite the information in any object of the same type pointed to by the value returned from any previous call to any of them and the functions are not required to avoid data races with each other. The implementation shall behave as if no other library functions call these functions. localtime returns a pointer to a static struct tm object, ie: a global object that may or may not be thread local. The contents of this object can be overwritten by a subsequent call to this or another library function. It should not be accessed after the thread in which it the function was called has exited. The object is not allocated from the heap, You must not call free with this pointer. The object cannot be allocated with automatic storage as accessing it after the function localtime returns would have undefined behavior. Instead of localtime, you should use localtime_r, a POSIX function that will be included in the next version of the C Standard (C23): #include <time.h> struct tm *localtime_r(const time_t *timer, struct tm *buf); localtime_r takes a pointer to the destination object, which you can define or allocate as appropriate for your usage. MSVC might not support this function, but you can define it on its target platforms as a simple macro: #ifdef _MSC_VER #define localtime_r(a,b) localtime_s(a,b) #endif
72,846,005
72,846,040
Return Base class shared pointer using derived class C++
I have a an interface: /*base.hpp */ class Base { protected: Base() = default; public: Base(Base const &) = delete; Base &operator=(Base const &) = delete; Base(Base &&) = delete; Base &operator=(Base &&) = delete; virtual ~Base() = default; virtual void Function1() = 0; }; Also there is a function in this interface: std::shared_ptr<Base> **getBase**(); //this will return the instance of Base class Since function in base class is pure virtual, sample Derived class is below: #inclide "base.hpp" class Derived : public Base { public: Derived(); ~Derived(); virtual void Function1() override; }; In main.cpp -> there is a call to getBase() std::shared_ptr<Base> ptr{ nullptr }; void gettheproxy() { ptr = getBase(); //call to get baseclass instance } Implementation of getBase method (in separate file getBase.cpp) #include "base.hpp" #include "derived.hpp" Derived d; std::shared_ptr<Base> getBase() { std::shared_ptr<Base> *b= &d; return b; } Error: cannot convert ‘Base*’ to Base’ in initialization What is the correct way to get base class instance from derived class implementation? Note: I have to follow this design of classes due to code dependency.
This should do: std::shared_ptr<Derived> d = std::make_shared<Derived>(); std::shared_ptr<Base> getBase() { return d; }
72,846,231
72,848,984
Aggregation between two derived classes
Can there be an aggregation relationship type between two derived classes of one base class (for example, one class contains vector of another)? Can it be implemented in C++ and if so, is it considered a good practice and does not violate logic or not? Example in picture:
Short answer is yes, and your class diagram shows an example of when you'd do this. Except buttons are actual, "physical" items on screen, and have unique identity, you can't just copy them in a data structure, you would probably use pointers to these buttons, in C++ like this using smart pointer: std::vector <std::unique_ptr<Button> > buttons; Using pointers also allows for example MyWindow contain other MyWindow without you getting compiler errors about incomplete type.
72,847,056
72,847,508
Busy/wait or spinning pattern in multithreaded environment
https://www.linkedin.com/pulse/how-do-i-design-high-frequency-trading-systems-its-part-silahian-2/ avoiding cache misses and CPU’s context switching how does busy/wait and spinning pattern avoids context switches if it runs two threads in one core ? It will still have context switches between these two threads(producer thread and 1 consumer thread) right ? what are the consequences if I don't set thread affinity to one specific core ? I completely get why it avoids cache misses. But i am still having trouble how does it solve avoiding context switches.
how does busy/wait and spinning pattern avoids context switches if it runs two threads in one core ? When a thread perform a lock and the lock is taken by another thread, it make s system call so the OS can know that the thread is waiting for a lock and this should be worthless to let it continue its execution. This causes system call and a context switch (because the OS will try to execute another threads on the processing unit) which are expensive. Using a spin lock somehow lies to the OS by not saying the thread is waiting while this is actually the case. As a result the OS will wait the end of the quantum (time slice allocated to the thread) before doing a context switch. A quantum is generally pretty big (eg. 8 ms) so the overhead of context switches in this case does not seems a problem. However, it is if you care about latency. Indeed, if another thread also use a spin lock, this cause a very inefficient execution because each thread will be executed during the full quantum and the average latency will be half the quantum which is generally far more than the overhead of a context switch. To avoid this happening, you should be sure that there are more core than thread to be actively running and control the environment. Otherwise, spin locks are actually more harmful than context switches. If you do not control the environment, then spin locks are generally not a good idea. If 2 threads running on the same core and 2-way SMT is enabled, then each thread will likely be executed on each of the hardware thread. In this case spin locks can significantly slow down the other thread while doing nothing. The x86-64 pause instruction can be used to tell to the processor that the thread is doing a spin lock and let the other thread of the same core be executed. This instruction also benefit from reducing contention. Note that even with the pause instruction, modern processor will run at full speed (possibly in turbo frequency) causing them to consume a lot of energy (and so heat). what are the consequences if I don't set thread affinity to one specific core ? Threads can then move between cores. If a thread move from one core to another it generally needs to reload data to its cache (typically fill the L2 from the L3 or another L2 cache) during cache misses that may occur on the critical path of a latency-critical operation. In the most critical cases, a thread can move from one NUMA node to another. Data transfer between NUMA nodes are generally slower. Not to mention the core will then access to data own by the memory of another NUMA node which is more expensive. Besides, it can increase the overall cost of context switches.
72,847,398
72,847,823
Find key in std::unordered_map won't find an existing key
I'm trying to make a simple ResourceManager which uses an ordered_map to find how to import files using the extension : #include <iostream> #include <unordered_map> #include <string> class ResourceManager; typedef void (*ImporterFn)(const std::string& path); // manage files and what's in the assets/ folder class ResourceManager { public: ResourceManager() {}; ~ResourceManager() {}; void addImporter(const char* extension, ImporterFn fn) { // avoid adding multiple importers for one extension if(importers.find(extension) != importers.end()) return; // add importer std::cout << "Adding importer for " << extension << std::endl; importers.emplace(extension, fn); } void loadFile(const std::string& path) { std::size_t extDot = path.find_last_of("."); std::string ext = path.substr(extDot+1); auto it = importers.find(ext.c_str()); if(it != importers.end()) { std::cout << "Importer found for " << ext.c_str() << std::endl; it->second(path); } else { std::cout << "No importer found for " << ext.c_str() << std::endl; } } private: std::unordered_map<const char*, ImporterFn> importers{}; }; and I made a simple program to test it and it seems it can't find the key in the map... int main() { ResourceManager* rsx = new ResourceManager(); rsx->addImporter("png", [](const std::string& path){ std::cout << "Loading png image" << std::endl; }); rsx->loadFile("assets/imagetest1.png"); rsx->loadFile("assets/imagetest2.jpeg"); return 0; } And it output (using g++ to build this example): Adding importer for png No importer found for png No importer found for jpeg So I don't know what I can do to fix this, I tried to list the key in the importers map and it seems to be there, do I need to specify a custom predicate or is the problem somewhere else ?
Problem is that your container is using const char* as a key. Note that std::unorderd_map uses standard operator == for type provided as key. In case of const char * this equal operator compares only a pointers. So only case where you will find item is when you use same pointer. Pointed contest doesn't meter. Now when you were adding item pointer to string literal was used. When you tried get an item you used buffer of std::string created on runtime. This two pointers will never be the same. Note that in C++ for handling string you should use std::string (and/or std::string_view since C++17). So simple replacing type of key in map fixes problem: private: std::unordered_map<std::string, ImporterFn> importers{}; https://godbolt.org/z/GrsWcqEdT Extra: C++17 has introduced std::filesystem::path which will make this code simpler: https://godbolt.org/z/YxMME934h
72,847,606
72,847,759
about c++ templates and parameter pack
template<class... Cs> void func(Cs... cs){ }; template<class T, class... Cs> void func1(T s){ func<Cs...>(/* the problem */); }; int main(){ char s[]="HI THERE!"; func1<char*,char,char,char>(s); return 0; } so the func1() call the func(), the two functions are specialized by the same template parameter pack, the function func1() take a known parameter "s" and we assume that it can produce and provide the parameters values from that s to the func() , but how can we do that. the problem is hard to me to explain i hope u get the point. edit: lets say that the args that the func1() passes to func() follow this pattern s[0],s[1],... , is depend on the parameter pack actually
If I understand it correctly, you want to use the parameter pack and expand those number of elements in s: #include <cstddef> #include <utility> template<class... Cs> void func(Cs&&... cs){ // 'H', 'I', ' ' }; template<class T, std::size_t... I> void func1_helper(T s, std::index_sequence<I...>) { func(s[I]...); } template<class T, class... Cs> void func1(T s){ func1_helper(s, std::make_index_sequence<sizeof...(Cs)>{}); }; int main(){ char s[]="HI THERE!"; func1<char*, char,char,char>(s); return 0; } As you can see here, the actual types in the pack isn't needed. You could just as easily have supplied the number 3: #include <cstddef> #include <utility> template<class... Cs> void func(Cs&&... cs){ // 'H', 'I', ' ' }; template<class T, std::size_t... I> void func1_helper(T s, std::index_sequence<I...>) { func(s[I]...); } template<std::size_t N, class T> void func1(T s){ func1_helper(s, std::make_index_sequence<N>{}); }; int main(){ char s[]="HI THERE!"; func1<3>(s); return 0; } If you really want to pass a pack of types that are not exact matches to what you've got in your array: #include <cstddef> #include <utility> #include <iostream> template<class... Cs> void func(Cs... cs){ // 'H', 'I', ' ' // prints HI and the `int` value of ' ' (32 most likely): (..., (std::cout << cs)); }; template<class... Cs, class T, std::size_t... I> void func1_helper(T s, std::index_sequence<I...>) { func<Cs...>(s[I]...); } template<class T, class... Cs> void func1(T s){ func1_helper<Cs...>(s, std::make_index_sequence<sizeof...(Cs)>{}); }; int main(){ char s[]="HI THERE!"; func1<char*, char,char,int>(s); return 0; } std::make_index_sequence<sizeof...(Cs)>{} creates an object of type std::index_sequence<0, 1, 2> (in this case). In func1_helper the indices, 0, 1, 2 goes into the parameter pack size_t... I to match the anonymous index_sequence<I...> argument. I is then used to expand s[I]... into s[0], s[1], s[2].
72,848,060
72,848,083
Operator overload for ostream not working with user defined class
I have this simple program and when i try to cout << 75.0_stC ; i have multiple errors and i don't know why.This things only happen when i pass my temperature object via reference. class temperature { public: long double degrees; temperature(long double c): degrees{c}{} long double show()const {return degrees;} }; temperature operator"" _stC(long double t){ return temperature(t); } ostream & operator<<(ostream &ekran, temperature &t) { ekran << t.show(); return ekran; }
You likely need to take a const reference to the argument you'd like to print: ostream & operator<<(ostream &ekran, const temperature &t) Temporary won't bind to the non-const reference argument.
72,848,431
72,848,490
Constexpr methods for nonconstexpr class
Is there any reason to add constexpr to class's methods if class hasn't any constexpr constructor? Maybe compiler can do some optimizations in this case?
Yes, one obvious case is when the class is an aggregate class. Aggregate initialization doesn't call any constructor, but can still be used in constant expression evaluation. Even if the class is not an aggregate class, you can still call a constexpr member function in constant expression evaluation if the member function doesn't access any state of the class instance. This is obviously the case for static member functions, but can also apply to non-static member functions. For example, the following is valid: struct A { int i; // The only usable constructor is the default constructor, // which is not `constexpr`. // The class is also not an aggregate class because of these declarations. A() : i(0) {} A(const A&) = delete; constexpr int getZero() { // return i; would be IFNDR return 0; } }; int main() { A a; constexpr int x = a.getZero(); } You must be careful though, because if it is completely impossible to call the member function as subexpression of any constant expression, then marking it constexpr anyway makes the program ill-formed, no diagnostic required (IFNDR). In other words the compiler may refuse to compile such a program. Also, how often such a situation comes up and the constant evaluation use case is intended (especially for non-static member functions), is a different question.
72,848,537
72,848,768
Is this possible in c++11? A class with same name but one with template. Ex: Result and Result<T>
Is this possible in c++11? Two class with same name but one with template. Ex: A class with name Result and another with name Result<T> to use like return Result("Message"); or Result<Date>("Message", date); For example, I tried this without success: template<> class response { public: bool sucess; std::string message; int code; }; template<typename T> class response<T> { public: T data; };
A couple C++11 options: Provide a default template argument of void and specialize on that. template<class T = void> class response { public: bool success; std::string message; int code; T data; }; template<> class response<void> { public: bool success; std::string message; int code; }; Then response<> will mean response<void> and will not have a data member. However, you'd still have to write response<>("Message") instead of response("Message") (In your actual code you'd probably want to give response constructors so that they could be directly initialized like this.) One option you can use to augment this is with factory functions, because a function overload set can contain both non-templated functions and function templates. So, for instance, you can have a make_response function: // Assuming the appropriate response constructors exist response<> make_response(std::string t_message) { return response<>{t_message}; } template<class T> response<T> make_response(std::string t_message, T t_data) { return response<T>{t_message, t_data}; } Then make_response("Message") will make a response<> aka a response<void> that has no data member, and make_response("Message", date) will make a response<Date> that has one.
72,848,743
72,851,033
Forking a process with threads containing sockets in C++
I have the following C++ - scenario under CentOS. Process P1 contains: passive listening socket with descriptor D1. 1 incoming connection (socket with D2). 1 outgoing connection (socket with D3). thread T1 with 1 outgoing connection (socket with D4). Incoming socket connections are created with: socket( AF_INET,SOCK_STREAM,0 ); setsockopt( ...SO_REUSEADDR, ...); bind listen accept Outgoing socket connections are created with: socket(AF_INET, SOCK_STREAM,0); connect Process P1 is now forked to P2 and in P2 there should be a new outgoing connection in a new thread T2. I am not interested in the other old connections here. What exactly do I have to consider here after the fork in P2? What are the best practices here? Are all my assumptions correct? I would realize it like the following: After the fork I close D1 in P2 directly, because I don't want to listen in different processes at the same port, although this would be possible. Correct? Because all FD's were copied (Ref-Counted?), I can safely close D2 and D3 in P2 without endangering the communication in P1, right? T1 is "dead" when forking anyway and so I should close D4 in P2 here too, or? Finally, I can spawn T2 in P2 and create a new outgoing socket D5 there Would a following scenario also be possible where I want to reuse D4? After the fork I close D1 in P2 directly I close D2 and D3 in P2 T1 is "dead" but I do not close D4 in P2 I spawn T2 and share the usage of D4 together with T1 from P1. Is this race-conditon-safe? Is this a good/common practice/pattern? General question: If the live-time of P2 is always shorter than of P1 are not all descriptors automatically released/counted down after P2 terminates? Do I need to close any FD's in this case?
I close D1 in P2 directly, because I don't want to listen in different processes at the same port, although this would be possible. Correct? Yes. Because all FD's were copied (Ref-Counted?), I can safely close D2 and D3 in P2 without endangering the communication in P1, right? Yes. And if you are not going interact with 'dupped' D2,D3 in P2,you should close them. T1 is "dead" when forking anyway and so I should close D4 in P2 here too, or? Finally, I can spawn T2 in P2 and create a new outgoing socket D5 there Only the thread that calls 'fork' will be 'cloned' into child process, all others will 'vanish'. So, if T1 is not the one 'forking', it is 'dead'. Similar as previous item, if you are not going to access the 'dupped' D4 in P2, you should close it. I spawn T2 and share the usage of D4 together with T1 from P1. Is this race-conditon-safe? Is this a good/common practice/pattern? No, there is no 'race', the D4 in P2 is really 'dupped' from D4 in P1. You can operate the D4 in P2 with out concerning the 'original' D4.
72,848,816
72,849,041
Does compound assignment of two unsigned integers of the same type always operate as if using that type's modular arithmetic?
Here is a conjecture: For expression a op b where a and b are of the same unsigned integral type U, and op is one of the compound assignment operators (+=,-=,*=,/=,%=,&=,|=,^=,<<=,>>=), the result is computed directly in the value domain of U using modular arithmetic, as if no integral promotions or usual arithmetic conversions, etc. are performed at all. Is this true? What about signed integral types? To clarify: By definition integral promotions and usual arithmetic conversions do apply here. I'm asking if the result is the same as not applying them. I'm looking for an answer in C++, but if you can point out the difference with C, it would also be nice.
Counter example: int has width 31 plus one bit for sign, unsigned short has width 16. With a and b of type unsigned short, after integral promotions, the operation is performed in int. If a and b have value 2^16 - 1, then the mathematical exact result of a * b in the natural numbers would be 2^32 - 2^17 + 1. This is larger than 2^31 - 1 and therefore cannot be represented by int. Arithmetic overflow in signed integral types results in undefined behavior. Therefore a *= b has undefined behavior. It would not have this undefined behavior if unsigned arithmetic modulo 2^width(unsigned short) was used. (Applies to all C and C++ versions.)