question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
70,677,484
70,677,822
Why can't I std::apply for a member function
I'm trying to develop a wrapper to help people use pthread on calling any member function. template <typename> struct signature; template <typename C, typename R, typename... Args> struct signature<R (C::*)(Args...)> { using return_type = R; using pure_argument_type = std::tuple<C*, std::tuple<Args...>>; // obj, {args...} using argument_type = std::tuple<R (C::*)(Args...), pure_argument_type>; // obj.mem_fn, {obj, args...} }; struct Job { public: Job() = default; ~Job() = default; void join() { pthread_join(btd, nullptr); } template <typename C, typename F, typename... Args> int run(F C::*f, C* c, Args&&... args) { typename signature<decltype(f)>::pure_argument_type pureParams = std::make_tuple(c, std::forward_as_tuple(args...)); typename signature<decltype(f)>::argument_type params = std::make_tuple(f, pureParams); return pthread_create( &btd, nullptr, [](void* p) { auto param = static_cast<typename signature<decltype(f)>::argument_type*>(p); std::apply(std::get<0>(*param), std::get<1>(*param)); ////// ERROR! return (void*)nullptr; }, &params); } private: pthread_t btd; }; However, when I try to do as below, class Test { public: void func(int& a, double& d) { a = 2; d = 2.0; } void dojob() { int a = 0; double d = 0.0; Job job; job.run(&Test::func, this, std::ref(a), std::ref(d)); job.join(); std::cout << "a:" << a << " d:" << d << std::endl; } }; Test t; t.dojob(); I get the error: In file included from /opt/compiler-explorer/gcc-11.2.0/include/c++/11.2.0/bits/stl_map.h:63, from /opt/compiler-explorer/gcc-11.2.0/include/c++/11.2.0/map:61, from <source>:2: /opt/compiler-explorer/gcc-11.2.0/include/c++/11.2.0/tuple: In instantiation of 'constexpr decltype(auto) std::__apply_impl(_Fn&&, _Tuple&&, std::index_sequence<_Idx ...>) [with _Fn = void (Test::*&)(int&, double&); _Tuple = std::tuple<Test*, std::tuple<int&, double&> >&; long unsigned int ..._Idx = {0, 1}; std::index_sequence<_Idx ...> = std::integer_sequence<long unsigned int, 0, 1>]': /opt/compiler-explorer/gcc-11.2.0/include/c++/11.2.0/tuple:1854:31: required from 'constexpr decltype(auto) std::apply(_Fn&&, _Tuple&&) [with _Fn = void (Test::*&)(int&, double&); _Tuple = std::tuple<Test*, std::tuple<int&, double&> >&]' <source>:98:27: required from 'int Job::run(F C::*, C*, Args&& ...) [with C = Test; F = void(int&, double&); Args = {std::reference_wrapper<int>, std::reference_wrapper<double>}]' <source>:118:16: required from here /opt/compiler-explorer/gcc-11.2.0/include/c++/11.2.0/tuple:1843:27: error: no matching function for call to '__invoke(void (Test::*&)(int&, double&), Test*&, std::__tuple_element_t<1, std::tuple<Test*, std::tuple<int&, double&> > >&)' 1843 | return std::__invoke(std::forward<_Fn>(__f), | ~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~ 1844 | std::get<_Idx>(std::forward<_Tuple>(__t))...); | You can get my code here: https://godbolt.org/z/sMjcxvP33
The return type of std::get<1>(*param) is std::tuple<C*, std::tuple<Args...>>. Since the type of the second element of this tuple is also a tuple, you need to use std::apply to expand it again, something like this std::apply( [f = std::get<0>(*param)](auto* obj, auto&& args) { std::apply([&](auto&&... args) { (obj->*f)(std::forward<decltype(args)>(args)...); }, std::forward<decltype(args)>(args)); }, std::get<1>(*param)); Demo Another alternative is to flatten the nested tuple to std::tuple<C*, Args...> and then pass it to std::apply along with f. std::apply( std::get<0>(*param), std::tuple_cat( std::make_tuple(std::get<0>(std::get<1>(*param))), std::get<1>(std::get<1>(*param)))); Demo
70,677,792
70,679,150
Read multiple text file in Arduino ide
I have folder contain n txt file(files have numeric values) I need to read these files and save the file contains in array. How can I read the contents of the first file1 in the array and then clear the array ,and then read the second file2 in the same array and so on? #include "SPIFFS.h" void setup() { Serial.begin(115200); float *arr=(float*)malloc(1000*sizeof(float)); if (!SPIFFS.begin(true)) { Serial.println("An Error has occurred while mounting SPIFFS"); return; } File root = SPIFFS.open("/"); File file = root.openNextFile(); while(file){ for(int i=0;i<1000;i++){ arr[i] = file.parseFloat(); Serial.println(arr[i]);} //Serial.println(file.name()); //file = root.openNextFile(); } } void loop() {}
You could do something similar to this. Though you will need to check the proper behaviour of parseFloat() when it doesn't detect a float value, ie., what it actually returns. while(file) { int length = readFile(arr, file); file.close(); handleArray(arr, length); file = root.openNextFile(); } ... int readFile(float *arr, File f) { int i = 0; float val = 0.0; val = f.parseFloat(); // returns 0.0 when no float was found? while (val > 0.0) { arr[i++] = val; val = f.parseFloat(); } return i; }
70,678,522
72,659,872
Numerical integration of a 2-dim complex function in C++?
I am trying to integrate this integral numerically (so without evaluating the primitive) in C++: It is simpler than what it seems, in fact I know which algorithm I can implement to solve it (I consider fYsin as func(th,phi) and integrate it with trapezoidal rule in 2-D). The only problem is that Y is complex and in particular is proportional to e^ikx. How should I proceed with this problem? Should I modify my integral in a way or should I apply numerical integration to real and imaginary part separately? EDIT I found this formula: maybe it can be used to integrade real and complex part separated and numerically?
I solved this problem by simply integrating real and imaginary part separately. The complete code can be found in this repository, within the complete algorithm definition to integrate the function of the first image I posted.
70,678,772
70,735,847
Using C++ protobuf formatted structure in leveldb. set/get operations
I'd like to make a POC of using leveldb in order to store key-value table of different data types in protobuf format. So far I was able to open the database file, and I also saw the get function with the following signature : virtual Status Get(const ReadOptions& options, const Slice& key, std::string* value)=0 I understand that the value is actually refers to a binary string like vector and not regular alphanumeric string, so I guess it can fit for multi type primitives like string, uint, enum) but how can it support struct/class that represent protobuf layout in c++ ? So this is my proto file that I'd like to store in the leveldb: message agentStatus { string ip = 1; uint32 port = 2; string url = 3; google.protobuf.Timestamp last_seen = 4; google.protobuf.Timestamp last_keepalive = 5; bool status = 6; } and this is my current POC code. How can I use the get method to access any of the variables from the table above ? #include <leveldb/db.h> void main () { std::string db_file_path = "/tmp/data.db"; leveldb::DB* db; leveldb::Status status; leveldb::Options options; options.create_if_missing = false; status_ = leveldb::DB::Open(options, db_file_path, &db); if (!status_.ok()) { throw std::logic_error("unable to open db"); } Thanks !
You need to serialize the protobuf message into a binary string, i.e. SerilaizeToString, and use the Put method to write the binary string to LevelDB with a key. Then you can use the Get method to retrieve the binary value with the given key, and parse the binary string to a protobuf message, i.e. ParseFromString. Finally, you can get fields of the message.
70,678,778
70,682,996
ldfcn.h gives 0 instead of true or false
i have dummy.cpp #include <iostream> #ifndef EXPORT_API #define EXPORT_API __attribute__ ((visibility("default"))) #endif extern "C"{ using namespace std; bool dum = true; int main(){}; }; and main.cpp #include <iostream> #include <dlfcn.h> #include <string> using namespace std; int main() { void *test = dlopen("./dummy", RTLD_NOW); //bool sus = reinterpret_cast<void(*)()>(dlsym(test , "turd")); bool* give =(bool*) dlsym(test, "dum"); cout<<give<<"refrence"; }; and i compile them with g++ dummy.cpp -o dummy g++ main.cpp -o main -ldl but when i run ./exe i get 0refrence and i dont know how to fix this or what the issue is i also have tried making it a function and returning it but that didn't work
solved it with gcc -shared -o dummy.so -fPIC dummy.cpp to get a proper so file and if yours has a function like int foo(){} or something use std::invoke in your .sofile and then call it like bool* give = (bool *) dlsym(test, "dum"); auto answr = *give; where answr is the return val
70,678,788
70,679,026
Memory allocation in the C++ standard library
Recently, I became interested in tracking memory allocation and deallocation. When overloading the new and delete operators, I found that the C++ standard library sometimes calls the overloaded operators and sometimes allocates memory using other methods. (Probably std::allocator.) For instance, std::string seems not to use new. Although, std::vector seems to call new when push_back is called. This is surprising since I would think the standard library would have a uniform policy to manage memory allocation. When does the standard library choose to new vs std::allocator? Why?
The standard containers will use the allocator provided to them to allocate dynamic memory. By default, that is std::allocator. For most other dynamic memory uses in the standard library, the standard doesn't specify how the implementation should acquire memory, and the implementation has the freedom to do what they want. As for tracking memory allocations, I recommend wrapping malloc.
70,679,324
70,679,360
What does symbol # means in #define S(x) (cout<<#x<<endl)
#define S(x) (cout<<#x<<endl) Using # will print whatever string, int, float I place in S(x). For example: S(Door Class Default Constructor); will print Door Class Default Constructor I Wasn't able to find any documentation regarding it. Explain how is it able to do so.
It causes the expanded x to be wrapped in double quoates, " It's often called the stringize operator and you can find more information here.
70,679,724
70,680,415
Reference evaluation and constant expression
Consider the following snippet: struct test1 { static constexpr int get() { return 1; } }; struct test2 { constexpr int get() const { return 1; } }; template <class T> int get(T&& t) { if constexpr (t.get() == 1) { return 1; } return 2; } int main() { return get(test1{}) + get(test2{}); } When trying to compile with GCC-11.1 (-std=c++2a), get template successfully compiles with test1, but not with test2. The only difference between them is fact that test2::get is static. Obviously, it does not compile with test2, because t parameter is not a "core constant expression", as per 7.7 expr.const(5.13): An expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine, would evaluate one of the following expressions: an id-expression that refers to a variable or data member of reference type unless the reference has a preceding initialization... The question is why it does compile, when the function being accessed via the very same reference is static. Isn't the refence "evaluated" in this case? Is it a GCC bug or there's some wording in the Standard that allows it?
Pointers and references to unknowns in constant expressions being directly ill-formed will possibly be addressed in C++23 and, if so, as a Defect Report for earlier language versions. [...] when the function being accessed via the very same reference is static. Isn't the refence "evaluated" in this case? Is it a GCC bug or there's some wording in the Standard that allows it? Your program is ill-formed also for the static case, as is answered in detail in the follow Q&A: Static member access in constant expressions However, EWG considers this a defect in the specification of constexpr, and are recommending CWG to consider resolving it by P2280R3 (Using unknown pointers and references in constant expressions), targeted for C++23, and as a DR (defect report) for C++11 through C++20. jfbastien commented on Feb 3, 2021 EWG saw this paper in today's telecon. P2280 Using unknown references in constant expressions The use cases presented in P2280 are problems in C++’s specification of constexpr, and we would like to fix these problems, ideally in C++23. This should be a Defect Report against C++20, C++17, C++14, and C++11. The final decision however lies with CWG which is yet to look at the issue.
70,680,708
70,680,753
C++ Runtime Error 0xC0000005 Caused By Object Inside Struct
While working on a C++ project, a runtime error (0xC0000005) showed up. I managed to locate the problem and encapsulate it in the code below. #include <iostream> using namespace std; class TestC{ public: string test1[20]; string test2[10]; void initArrays(){ cout << "init start\n"; for(int i=0;i<20;i++){ cout << i << endl; this->test1[i] = "initialized"; } cout << "first for complete\n"; for(int i=0;i<10;i++) this->test2[i] = "initialized"; cout << "init finished\n"; } }; struct TestS{ int anint; int anotherint; TestC obj; }; int main(){ cout<<"Check :\n"; struct TestS *struct_instance = (struct TestS*) malloc(sizeof(struct TestS)); struct_instance->obj.initArrays(); cout<<"Ok Struct"; return 0; } Basically the error is only thrown when initArrays() is called through the TestC object located inside struct TestS. If initArrays() is called from an object created inside main(), like below, everything works fine. int main(){ TestC classObj; classObj.initArrays(); } Despite being able to locate the problem, I have been unsuccessful in fixing it. Does anyone know what would do the trick? I am using the Code::Blocks IDE NOTE: Creating the TestC object in main() and only maintaining a pointer to it within the struct, is not a suitable solution for the actual project.
You're using malloc to allocate a structure that contains a class, TestC. This means the TestC constructor won't run and the test1 and test2 arrays won't be correctly initialized. Instead, use new: TestS *struct_instance = new TestS; You should never use malloc to allocate and type that is a C++ class, or contains a C++ class.
70,680,967
70,685,553
Xcode offers -std=c++20 but command line clang does not
I have the Xcode command line tools installed and can use clang++ fine for versions up to C++17. In Xcode itself, I can select C++20 in the build settings: But when I try to compile using clang++ from the command line with this option: error: invalid value 'c++20' in '-std=c++20' note: use 'c++17' for 'ISO C++ 2017 with amendments' standard note: use 'gnu++17' for 'ISO C++ 2017 with amendments and GNU extensions' standard note: use 'c++2a' for 'Working draft for ISO C++ 2020' standard note: use 'gnu++2a' for 'Working draft for ISO C++ 2020 with GNU extensions' standard What would be the reason for this inconsistency? In case it matters: ~/ which clang++ /usr/bin/clang++ ~/ clang++ -v Apple clang version 11.0.3 (clang-1103.0.32.29) Target: x86_64-apple-darwin20.6.0 Thread model: posix InstalledDir: /Library/Developer/CommandLineTools/usr/bin (I also tried clang -x c++).
Like you have noticed, Xcode and system uses different instance of Command Line Tools. Xcode uses the one that is embedded in Xcode, and the system will use a copy located in Library/Developer/, which is not automatically upgraded along with Xcode. Support of c++20 flag is only added for later versions of Apple Clang, which seems like the clang embedded within your Xcode does support it, but the clang install in Library/Developer does not. To force them be the same version, you might need to download it yourself from https://developer.apple.com/download/all/?q=command%20line%20tools, and choose the version that matches your Xcode.
70,681,084
70,683,604
Consteval constructor and member function calls in constexpr functions
struct A { int i; consteval A() { i = 2; }; consteval void f() { i = 3; } }; constexpr bool g() { A a; a.f(); return true; } int main() { static_assert(g()); } https://godbolt.org/z/hafcab7Ga The program is rejected by all of GCC, Clang, MSVC and ICC and replacing constexpr on g by consteval results in all four accepting it. However, when removing the call a.f();, still with constexpr on g, only ICC still rejects the code. The other three now accept it. I don't understand why this is the case. My understanding is that without consteval on g, the expression a.f() is not in an immediate function context, which will cause the member function call itself to be evaluated as separate constant expression, which then cannot modify the i member because the member's lifetime didn't begin during evaluation of that constant expression. But why can the constructor perform the same operation on the same object, in the same context? Is a's lifetime considered to have begun during the evaluation of the consteval constructor? Also note that the presence of the static_assert doesn't affect these results. Removing in addition constexpr completely from g then also doesn't change anything about the compiler behavior. As noted by @Enlico, even replacing both A a; and a.f(); by A{}.f(); with constexpr on g results in all compilers except ICC accepting the code, although by my understanding, this expression should result in evaluation of two separate constant expressions for the immediate constructor invocation and for the immediate member function invocation. I think the latter call should behave exactly as a.f();, making this even more confusing. (After reading @Barry's answer, I realize now that the last sentence didn't make any sense. Correction: A{} would be one constant expression for the constructor immediate invocation and A{}.f() as a whole would be the second constant expression for the member function immediate invocation. This is clearly different from the expression a.f().)
The rule is, from [expr.const]/13: An expression or conversion is in an immediate function context if it is potentially evaluated and its innermost non-block scope is a function parameter scope of an immediate function. An expression or conversion is an immediate invocation if it is a potentially-evaluated explicit or implicit invocation of an immediate function and is not in an immediate function context. An immediate invocation shall be a constant expression. Where, an immediate function is simply the term for (from [dcl.constexpr]/2): A function or constructor declared with the consteval specifier is called an immediate function. From the example: struct A { int i; consteval A() { i = 2; }; consteval void f() { i = 3; } }; constexpr bool g() { A a; a.f(); return true; } The call a.f() is an immediate invocation (we're calling an immediate function and we're not in an immediate function context, g is constexpr not consteval), so it must be a constant expression. It, by itself, must be a constant expression. Not the whole invocation of g(), just a.f(). Is it? No. a.f() mutates a by writing into a.i, which violates [expr.const]/5.16. One of the restrictions on being a constant expression is that you cannot have: a modification of an object ([expr.ass], [expr.post.incr], [expr.pre.incr]) unless it is applied to a non-volatile lvalue of literal type that refers to a non-volatile object whose lifetime began within the evaluation of E; Our object, a.i, didn't begin its lifetime within the evaluation of this expression. Hence, a.f() isn't a constant expression so all the compilers are correct to reject. It was noted that A().f(); would be fine because now we hit the exception there - A() began its lifetime during the evaluation of this expression, so A().i did as well, hence assigning to it is fine. You can think of this as meaning that A() is "known" to the constant evaluator, which means that doing A().i = 3; is totally fine. Meanwhile, a was unknown - so we can't do a.i = 3; because we don't know what a is. If g() were a consteval function, the a.f() would no longer be an immediate invocation, and thus we would no longer require that it be a constant expression in of itself. The only requirement now is that g() is a constant expression. And, when evaluating g() as a constant expression, the declaration of A a; is now within the evaluation of the expression, so a.f() does not prevent g() from being a constant expression. The difference in rules arises because consteval functions need to be only invoked during compile time, and constexpr functions can still be invoked at runtime.
70,681,310
70,681,456
Error i get using get() and set() method in C++
I want to write a code that will accept input but store it as private in C++ but I keep getting a weird output after compiling it. Below is my code #include <iostream> #include <string> using namespace std; class MyClass{ private: int salary; public: string fname; string lname; int age; void sent(string fname1, string lname1, int age1){ cout<<"My name is "<<fname1<<" "<<lname1<<" and i am "<<age1<<" years old."; }; void setSalary(int s){ salary = s; } int getSalary(){ return salary; } }; int main(){ MyClass myObj; string fname2 = myObj.fname; string lname2 = myObj.lname; int age2 = myObj.age; int salaries; myObj.setSalary(salaries); cout<<"Enter first name: "; cin>>fname2; cout<<"Enter last name: "; cin>>lname2; cout<<"Enter age: "; cin>>age2; cout<<"Salary amount: "; cin>>salaries; myObj.sent(fname2, lname2, age2); cout<<"\n"; myObj.getSalary(); return 0; }
You should call cout<<"Salary amount: "; cin>>salaries; before myObj.setSalary(salaries); and also actually print the salary you get: cout << myObj.getSalary();
70,681,777
70,681,938
A code error about template and iterator of C++ made by a C++ new learner
As a C++ new learner, when I tried to learn about the template and iterator of C++, I wrote a function to check whether a number is amoung an array by using template and iterator of C++. The code is below: template<typename T> bool find(vector<T>::iterator &begin, vector<T>::iterator &end, T target){ for(;begin != end; begin++){ if(*begin == target){ return true; } } return false; } int main(void){ vector<int> array{1,2,3,4,6,7}; if(find(array.begin(),array.end(), 7)){ cout << "find!"; } else{ cout << "not found!"; } } When I run the code above, I'll encouter the error, like this: template<typename T> bool find(vector<T>::iterator &begin, vector<T>::iterator &end, T target){ ^~~~~~ test.cpp:2631:94: error: expression list treated as compound expression in initializer [-fpermissive] template<typename T> bool find(vector<T>::iterator &begin, vector<T>::iterator &end, T target){ ^ test.cpp:2631:95: error: expected ';' before '{' token template<typename T> bool find(vector<T>::iterator &begin, vector<T>::iterator &end, T target){ ^ ; test.cpp: In function 'int main()': test.cpp:2643:8: error: reference to 'find' is ambiguous if(find(array.begin(),array.end(), 7)){ ^~~~ In file included from C:/LLVM/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/algorithm:62, from test.cpp:3: C:/LLVM/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:3897:5: note: candidates are: 'template<class _IIter, class _Tp> _IIter std::find(_IIter, _IIter, const _Tp&)' find(_InputIterator __first, _InputIterator __last, ^~~~ In file included from C:/LLVM/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/locale_facets.h:48, from C:/LLVM/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/basic_ios.h:37, from C:/LLVM/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/ios:44, from C:/LLVM/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/ostream:38, from C:/LLVM/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/iostream:39, from test.cpp:1: C:/LLVM/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/streambuf_iterator.h:368:5: note: 'template<class _CharT2> typename __gnu_cxx::__enable_if<std::__is_char<_CharT2>::__value, std::istreambuf_iterator<_CharT> >::__type std::find(std::istreambuf_iterator<_CharT>, std::istreambuf_iterator<_CharT>, const _CharT2&)' find(istreambuf_iterator<_CharT> __first, ^~~~ test.cpp:2631:43: note: 'template<class T> bool find<T>' template<typename T> bool find(vector<T>::iterator &begin, vector<T>::iterator &end, T target){ ^~~~~~~~ I just don't know what is wrong with the function and sincerely hope somebody can help!
You should add typename before iterator type in function arguments. Also if you use the name find for your function and include std namespace in your code, there will be a clash. So you should use another name for the function or use scope resolution operator for std functions. Here I fixed it for you: template<typename T> bool findElement(typename std::vector<T>::iterator &begin, typename std::vector<T>::iterator &end, T target){ for(;begin != end; begin++){ if(*begin == target){ return true; } } return false; } int main(void){ std::vector<int> array{1,2,3,4,6,7}; auto it1 = array.begin(); auto it2 = array.end(); if(findElement(it1, it2, 7)){ std::cout << "find!"; } else{ std::cout << "not found!"; } }
70,682,096
70,682,383
Is it safe to call std::visit on classes with virtual functions?
I'd like to create a hierarchy of visitors to handle instances of std::variant. I'd like to override some of the methods in subclasses for more specialized behavior. My code looks like this: #include <variant> #include <cstdint> #include <iostream> struct Event1 {}; struct Event2 {}; using Event = std::variant<Event1, Event2>; class Visitor { public: virtual ~Visitor() = default; virtual void operator()(const Event1&) { std::cout << "Visitor: Event1\n"; } virtual void operator()(const Event2&) { std::cout << "Visitor: Event2\n"; } }; class SubVisitor: public Visitor { public: using Visitor::operator(); virtual void operator()(const Event1&) { std::cout << "SubVisitor: Event1\n"; } }; int main() { SubVisitor sv; Event e; e = Event1{}; std::visit(sv, e); e = Event2{}; std::visit(sv, e); } This compiles and seems to work fine: $ g++ test.cpp -o test $ ./test SubVisitor: Event1 Visitor: Event2 Is such code well defined and carry no risk of an undefined behavior? All examples of std::variant I've seen use either simple classes with no inheritance or lambdas.
Yes, such code is required to do what you expect. When you pass a Visitor & to std::visit, it won't copy (and thus slice) it. All examples of std::variant I've seen use either simple classes with no inheritance or lambdas. That's because examples tend to be as simple as possible.
70,682,335
70,682,418
query the spdlog logger name
say we build our spdlog object as the following? logger = std::make_shared<spdlog::logger>("some name", sink_list.begin(), sink_list.end()); Is there a method such as logger->get_name() or anything else that would return "some name"
Is there a method such as logger->get_name() or anything else that would return "some name" There is. logger->name() (source)
70,682,756
70,684,047
schedule() affecting private thread variables in OpenMP #pragma omp parallel for
I've been following and modifying a tutorial for OpenMP in C/C++ to demonstrate/ understand how schedule() works in #pragma omp parallel for. This is my code: #include <unistd.h> #include <stdlib.h> #include <omp.h> #include <stdio.h> #define THREADS 4 #define N 100 int main ( ) { int i; int perThread=0; printf("Running %d iterations on %d threads.\n", N, THREADS); #pragma omp parallel for num_threads(THREADS) private(perThread) //schedule(static) for (i = 0; i < N; i++) { perThread++; printf("Thread: %d\t loops: %d\n", omp_get_thread_num(), perThread); usleep(10000); // to slow the process down a bit //Uncomment below to simulate one thread taking longer on each loop // if(omp_get_thread_num()==1) // sleep(1); } // all threads done printf("All done!\n"); return 0; } I saved it as "schedule_example.cpp" and compiled it with: g++ schedule_example.cpp -fopenmp -o SheduleEx I then compared it with line 13 schedule(static) uncommented and again with various options for schedule(), i.e. schedule(static,25) schedule(static,5) schedule(dynamic) schedule(dynamic,5) schedule(runtime) The scheduler works and the code demonstrates the difference (particularly when lines 20 and 21 are uncommented.) The problem is that for some but not all options of schedule() the starting value of perThread is changed for some but not all threads, which can be seen in the printed output. I've run the code on a few different machines and they've all shown similar results. I used WSL on my Windows 10 laptop, g++ --version returns: g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0. Using the final 8 lines as an example. If schedule() is commented out or using schedule(static) the output is correct: Thread: 2 loops: 24 Thread: 0 loops: 24 Thread: 1 loops: 24 Thread: 3 loops: 24 Thread: 2 loops: 25 Thread: 1 loops: 25 Thread: 0 loops: 25 Thread: 3 loops: 25 All done! But if I use anything else for shedule() even schedule(static,25) which should give the same result, it compiles and runs but the last few lines of output are: Thread: 1 loops: 24 Thread: 3 loops: 24 Thread: 0 loops: 22010 Thread: 2 loops: 24 Thread: 1 loops: 25 Thread: 3 loops: 25 Thread: 0 loops: 22011 Thread: 2 loops: 25 All done! The problem is the starting value of perThread has been set to 1986 but only for thread 0. If I rerun it, without recompiling, I have similar results, always thread 0 that's wrong and by about 22000 but not the same amount each time. If I recompile before reruning it gives the same results. I then ran the same code on Raspberry Pi and got similar but slightly different results. g++ --version returns: g++ (Raspbian 10.2.1-6+rpi1) 10.2.1 20210110 The Raspberry Pi only prints out the correct value for loops on all threads if schedule(dynamic) or schedule(dynamic, X) is used - I tried 1, 5, and 25 as values for X. If (static) or (static, X) is used then all the threads except thread 0 have a starting value of around 67321, this number is always the same for thread 1, 2, and 3, and is often but not always the same between successive runs of the code. (auto) behaves the same as (static). However, (runtime) is opposite to (static), only thread 0 that is wrong, but is also about 67481 off - however when when running it a few times in a row it was the same amount wrong each time. I ran the same code again on a different PC with Arch Linux and got similar results to the Windows 10 laptop. In terms of an actual question, is there something I'm doing wrong with how I've written the code? Is there a way to ensure the thread's variables aren't changed? Sorry it's such a long post but I think the core of the issue is that schedule() is somehow affecting the variable in private() for some of the threads at the beginning of the parallel for loop, some of the time. Thank you
You should use firstprivate(perThread) instead of private(perThread). Using private clause your private variable is declared, but not initialized, so its value is undefined. In OpenMP specification you can read that the firstprivate clause declares one or more list items to be private to a task, and initializes each of them with the value that the corresponding original item has when the construct is encountered. so you have to use this clause.
70,683,050
70,683,168
How am I able to use a class as a function parameter in itself?
This is not allowed as test will be infinitely big (it contains itself recursively). struct test{ test t; }; However the following compiles fine: struct test{ int get(test t1);// or `int get(test t1){}` static test t2; }; How does it know how much space to allocate for t1 on the stack, at that point test isn't complete yet. Same question goes for t2 and it's location on static memory.
Case 1 Here we consider the statement static test t2; From static documentation: The declaration inside the class body is not a definition and may declare the member to be of incomplete type (other than void), including the type in which the member is declared: struct S { static S s; // declaration, incomplete type (inside its own definition) }; For the exact same reason your statement static test t2; is allowed/valid. Case 2 Here we consider int get(test t1); The above statement is a member function declaration and not a definition so this is also valid. That is, since it is a function declaraion you can use the incomplete type as parameter. Case 3 Here we are considering: int get(test t1){} This works because: The type of a parameter or the return type for a function definition shall not be an incomplete class type (possibly cv-qualified) unless the function definition is nested within the member-specification for that class (including definitions in nested classes defined within the class).
70,683,307
70,683,476
Pass function template as argument to normal function to be specialised differently within the normal function
I would like to do something to the following effect: template <class A> A doThings(A input) { /* do something */ } void doTwoThings(ClassB inputB, ClassC inputC, template <class A> A(A) func) // This syntax is wrong but how to achieve this effect? { std::cout << func<ClassB>(inputB); std::cout << func<ClassC>(inputC); } doTwoThings(5, "testStr", doThings); Basically, I am trying to pass a function template as an argument to a normal function, and within that function, specialise the function template into two or more overloads and use them. Is there a way to do that in C++?
Not sure if it match your need, but you might do template <typename F> void doTwoThings(ClassB inputB, ClassC inputC, F func) { std::cout << func(inputB); std::cout << func(inputC); } doTwoThings(5, "testStr", [](const auto& input){ doThings(input); });
70,683,447
70,699,796
mlpack include file errors
Recently I am about to learn mlpack. Today I have successfully built the solution from mlpack source code, but when I newly create a project I get the following error in the header file. I would like to know what is wrong and how to fix it. errors In the screenshot, the algorithm.hpp is under the build folder and its absolute path is D:\MLPack\mlpack\build\include\mlpack\core\std_backport\algorithm.hpp. The source code in the new project is just a copy from https://www.mlpack.org/. The screenshot below shows some of the files generated after building solution of mlpack.sln. generated libs The versions of other libraries to help build the mlpack are : Armadillo 10.8.0 (at least 9.800) Boost (math_c99, spirit) 1.78.0 (at least 1.58.0, and I have added this version string in CMakeLists.txt before building mlpack) CMake 3.20 (at least 3.6) ensmallen 2.18.1 (at least 2.10.0) cereal 1.3.0 (at least 1.1.2) openBLAS 0.24.1 The configurations of my new project are shown below. additional include directories additional dependencies post-build event And I have also disabled "Conformance Mode". disabled conformance mode The entire building and using process refer to https://www.mlpack.org/doc/stable/doxygen/build_windows.html and https://www.mlpack.org/doc/mlpack-3.4.2/doxygen/sample_ml_app.html.
I finally found out that this problem seems to be related to the version of the source code. I should not use the latest version of the source code from https://github.com/mlpack/mlpack, but the source code corresponding to the latest stable version. After I replaced the include directory with the include directory corresponding to the officially released windows installation package, no error was reported during the building of the solution in my new project, so I got the expected result. the result This incident taught me a lesson that I should use the stable rather than the latest version of the source code when doing CMake in the future.
70,684,028
70,684,245
How am I able to use an incomplete class as an argument in itself?
struct test{ void call(test t1){ // } }; I have asked a similar question and found a few other links such as: How am I able to use a class as a function parameter in itself? Incomplete types in member function definitions But none of them answer this question: The compiler needs to emit code to allocated space on the stack for t1, but at that point test is incomplete so how would it know how much space it needs?
The class struct test is not an incomplete type. From cppreference.com: Incomplete type the type void (possibly cv-qualified); incompletely-defined object types class type that has been declared (e.g. by forward declaration) but not defined; array of unknown bound; array of elements of incomplete type; enumeration type from the point of declaration until its underlying type is determined. All other types are complete. Test it out yourself, put a test into your call function, like: void call(test t1) { std::cout << sizeof t1 << std::endl; }
70,684,671
70,684,766
How do i read/write JSON with c++?
I would like to know how to read/write a JSON file using C++. I will be using this file to store player info & setting for a simple game I'm making. It's nothing fancy, just a console number guessing game, but I just use it to learn stuff. I have to know how to read & write specific parts of a JSON.
Using a library, it can be done quite easily: #include <nlohmann/json.hpp> #include <iostream> int main() { // read file auto json = nlohmann::json::parse("{\"value1\": \"string\"}"); // mutate the json json["value1"] = "new string"; // write to a stream, or the same file std::cout << json; // print the json } C++ don't have the built-ins for dealing with json. You can implement your own json data structure, or use one available like nlohmann/json or simdjson You could create your own parser using pure C++ with the standard library only, but I would advise against.
70,684,743
70,686,290
gdb printing <incomplete type> with incomplete enum class declaration
I've been dipping my toes in C++, and found a surprising behavior of gdb. I'm wondering if it is the expected behavior, or if I messed something up. enum class Foo; struct Bar { Foo a; int b; }; enum class Foo { A, B, C }; int main() { auto a = Foo::A; auto b = Bar{ Foo::A, 1 }; } built with gcc 7.5.0 (with the -g option) and ran with gdb 8.1.1 When trying to print the value of a, or b.a, the result is <incomplete type>. This doesn't happen if the struct declaration is not between the two enumeration declaration, or if the enumeration is fully declared once. For the practical reason why I tried this, I had a header file containing a relatively big class declaration with some of its member being enumeration types. I felt have the full declaration of the enumerations after the class declaration was cleaner, and decided to partially declare them. Is there something I can do to access the variable information in gdb while still doing these partial declarations, or is fully declaring my enumerations the only way. Theses similar questions gdb class is incomplete type until I set breakpoint in class constructor? How to print <incomplete type> variable in gdb GDB incomplete type when having C++ virtual function do not concern my situation, since I have no trouble accessing the type information if the enumeration is only fully declared.
Using g++ (Debian 11.2.0-10) 11.2.0 and GDB-10.0: 7 auto b = Bar{ Foo::A, 1 }; (gdb) p a $1 = Foo::A (gdb) n 8 } (gdb) p b $2 = {a = Foo::A, b = 1} built with gcc 7.5.0 (with the -g option) and ran with gdb 8.1.1 These are pretty ancient. Is there something I can do I suggest trying latest released GDB (easy to build from source), and if that doesn't help, latest GCC.
70,684,828
70,685,367
Return an array which is iniated in a one liner
I want to return an array of my custom structure object timeInDay with as few lines as possible, in order to return a day in my time schedule. struct timeInDay[] getRingTimesForWeekDay(int day) { switch (day) { case MONDAY: return { {7, 50} }; case TUESDAY: return { {7, 50} }; case WEDNESDAY: return { {7, 20} }; case THURSDAY: return { {7, 50} }; case FRIDAY: return { {7, 50} }; case SATURDAY: return { {7, 50} }; case SUNDAY: return { {7, 50} }; } } struct timeInDay { unsigned short hour; unsigned short minute; }; Right now it produces an error with the return value of the method: error: decomposition declaration cannot be declared with type 'timeInDay' struct timeInDay[] getRingTimesForWeekDay(int day) { Would be deeply appreciated if anybody could write down their way of doing it with as few lines as possible.
No line is required to return a c-array from a function, because you cannot return a c-array from a function. You could dynamically allocate it and return a pointer to first element and size, but you better stay away from that in favor of std::array: #include <array> struct timeInDay { unsigned short hour; unsigned short minute; }; std::array<timeInDay,1> getRingTimesForWeekDay(int day) { switch (day) { case 1: return { {7, 50} }; default: return { {7, 50} }; } } However, as others have mentioned already, the function does only return a single element, so it isnt clear why you want an array in the first place. PS: If the size of the array is dynamic, use std::vector
70,685,138
70,696,741
Conan package manager - how to remove folders during conan install?
I have a local conanfile.py to consume a package, the package is already located on the local cache (~/.conan/). In the conanfile.py there is the imports() function in which I copy some files from the package into my build folder. I have two files with the same name in different directories and I copy them to the same directory and rename one of them. After I do that, I am left with an empty directory I want to remove, but can't find a way to do so from conanfile.py, every attempt seems to remove the folder before the files gets run. My imports looks as follows: class SomeConanPkg(ConanFile): name = "SomeName" description = "SomeDesc" requires = ( "SomePkg/1.0.0.0@SomeRepo/stable") def imports(self): # copy of 1st file self.copy("somefile.dll", src=os.path.join("src"), dst=os.path.join(build_dest)) # copy of 2nd file to nested directory self.copy("somefile.dll", src=os.path.join("src", "folder"), dst=os.path.join(build_dst, "folder")) # move and rename the file to parent directory shutil.copy2(os.path.join(build_dst, "folder", "somefile.dll"), os.path.join(build_dst, "renamed_file.dll")) # now build_dst/folder is an empty directory I have tried to use conan tools.rmmdir() or just calling shutil.rmmtree() but all of them seems to run before the files gets copied. I also tried to add a package() or deploy() member functions and execute the remove inside but these methods don't seem to run at all (verified with a debug print). Any ideas?
I ended us solving it in the package creation side. Renamed the files as I wanted and then just consumed them
70,685,472
70,685,528
Problem with function which create and return pointer to dynamic vector
I have to crate a function which gets a reference to int array as one of arguments. This function should creates a dynamic vector and returns its pointer. When I compile this code I got err: "No matching function for call to 'func'". I have no idea what's wrong. Immediately, I would like to ask if I removed the dynamic vector from the memory correctly or should I write it differently? #include <iostream> #include <vector> using namespace std; vector<int> *func(int &, int); int main() { const int arrSize = 5; int arr[arrSize] = {1, 3, 5, 7, 9}; vector<int> *ptr_vec = func(arr, arrSize); delete ptr_vec; } vector<int> *func(int &arr, int size){ auto *newVec = new vector<int>; for(int i = 0; i < size; i++) newVec[i].push_back(arr+i); return newVec; } Thanks in advance
The first parameter of the function is a reference to a scalar object of the type int vector<int> *func(int &, int); You need to write vector<int> *func( const int *, int); Also in the for loop you have to write for(int i = 0; i < size; i++) newVec->push_back(arr[i]); In fact the for loop is redundant. Your function could look simpler as for example vector<int> * func( const int *arr, int size ) { return new std::vector<int> { arr, arr + size }; } Pay attention to that there is no great sense to define the vector dynamically. The function can be declared and defined the following way vector<int> func( const int *arr, int size ) { return { arr, arr + size }; }
70,685,625
70,686,664
How to pass a function signature as input in order to initialize another function in C++?
my question is the following: supposing I have a program, written in C++, which takes a function and gives its integral. In this program I write the function manually, in the source code, and I change its signature every time I want to integrate another function. If now I want to initialize this function in input (for example giving a string), in order to directly initialize it at compiling time, how could I do? I would be interested in having something like this: $ ./program $ Give me the function name: x+3y+4 and now the function is initialized with: int func() { return x+3y+4; }
You need this: https://github.com/ArashPartow/exprtk It is only slightly slower than compiling the expression in native code. There are also others, you can see most of them here: https://github.com/ArashPartow/math-parser-benchmark-project (Disclaimer: I am the author of the Node.js bindings: https://github.com/mmomtchev/exprtk.js)
70,685,777
70,710,121
How to get data out of readyReadSlot?
I am trying to get data out of slot with a signal readyRead(). But my method doesn't seem to work. I googled a lot but still I can't solve the problem. Here what I have: In my main function I call the method sendPOST() to get cookies. I got cookies from this method using inside of it SIGNAL finished(QNetworkReply *) and SLOT replyFinishedSlot_(QNetworkReply *) : connect(manager_, SIGNAL(finished(QNetworkReply *)), this, SLOT(replyFinishedSlot_(QNetworkReply *))); I made a public static bool variable isFinished = false by default to write if slot is finished it's job. replyFinishedSlot_(QNetworkReply ): if(reply->error()) qDebug() << "Error: " << reply->errorString(); else { cookie = reply->manager()->cookieJar()->cookiesForUrl(webReportsUrl); QString cookieString = cookie[0].name() + "=" + cookie[0].value() + "; domain=" + cookie[0].domain() + "; path=" + cookie[0].path() + ";"; if(reply->isFinished()) isFinished = true; //isFinished is static public variable } reply->deleteLater(); And then I check in my main function if isFinished is true, and if it is I connect to another slot: manager_ = new QNetworkAccessManager(this); sendPOST("http://url"); if(isFinished) { QNetworkAccessManager *man = new QNetworkAccessManager(); QNetworkRequest request(webReportsUrl); request.setHeader(QNetworkRequest::CookieHeader, QVariant::fromValue(cookie)); getReply = man->get(request); connect(getReply, SIGNAL(readyRead()), this, SLOT(readyReadSlot_())); if(isRead) qDebug() << "reading"; else qDebug() << "not reading"; } and isFinished in here works very well (but I am not sure if this is the right way to check finished or not like this). I get isFinished == true, and I can get cookies from replyFinishedSlot_. But the problem is to get data from readyReadSlot_(). I tried different ways to receive the data from this slot, but there's no successful result. I tried even something like this: QEventLoop loop; connect(getReply, SIGNAL(readyRead()), &loop, SLOT(readyReadSlot_())); loop.exec(); But I got the error: QObject::connect: No such slot QEventLoop::readyReadSlot_() in ... Inside readyReadSlot_() I have to receive all the data from the page: if(getReply->isReadable()) { if(getReply->error() != QNetworkReply::NoError) { qDebug() << "Error: " << getReply->errorString(); } else { isRead = true; response = getReply->readAll(); //here the data I need outside of this slot qDebug() << "response: " << response; } } getReply->deleteLater(); And I get it successfully inside, but I need to get response outside of this slot, in my main function, for example. I know here's something with a threads, and I just don't wait till the data recieved, but I don't know how can I fix it.
I found a problem solvation for me. void DataMartsModel::replyFinishedSlot_(QNetworkReply *reply) { static bool isRead = false; if(reply->error()) qDebug() << "Error: " << reply->errorString(); else { cookie = reply->manager()->cookieJar()->cookiesForUrl(webReportsUrl); QString cookieString = cookie[0].name() + "=" + cookie[0].value() + "; domain=" + cookie[0].domain() + "; path=" + cookie[0].path() + ";"; QNetworkAccessManager *man = new QNetworkAccessManager(); QNetworkRequest request(webReportsUrl); request.setHeader(QNetworkRequest::CookieHeader, QVariant::fromValue(cookie)); getReply = man->get(request); connect(getReply, &QNetworkReply::readyRead, [=](){ if(getReply->isReadable()) { if(getReply->error() != QNetworkReply::NoError) qDebug() << "Error: " << getReply->errorString(); else { isRead = true; } } }); if(reply->isFinished() && getReply->isReadable()) isFinished = true; //here is the problem solvation I wanted } reply->deleteLater(); } main function manager_ = new QNetworkAccessManager(this); sendPOST("http://url"); if(isFinished) { QByteArray array = getReply->readAll(); //here I got the data I needed to get from readyReady qDebug() << array; //here I display it and I can use them in the future } If you know better way to solve the problem, I would like to check it, too.
70,686,008
70,718,544
Shared library with statically linked dependencies
I just wanted to understand how shared libraries with statically linked libraries are expected to perform. I am writing a shared library (lshared.so) that is statically linked to another library (lstatic). Now, I have another executable helloworld which loads a dynamic version of library lstatic (lstatic.so) and lshared.so as well. Will the static version of library (lstatic) loaded by lshared.so and the dynamic version (lstatic.so) conflict? Will they share any global state? Tried to show it better below. helloworld --> lshared.so (statically linked to lstatic at compile time) --> lstatic.so (hello world loads this at runtime) To throw some context, I've to use a shared library for logging. It is possible that lshared.so is statically linked to a different version that the one available to helloworld at runtime.
Will the static version of library (lstatic) loaded by lshared.so and the dynamic version (lstatic.so) conflict. Possibly. Will they share any global state. Possibly. The answers depend on how exactly lshared.so is built (which symbols it exports), and how the main helloworld binary is linked. The answers also tend to be somewhat complicated, and may depend on inlining and other optimizations, and possibly on compiler versions. It is best to avoid doing that by using shared version of lstatic.so, where all the answers become simple.
70,686,429
70,686,520
Initializing a member of uncopyable and unmovable type
Given an uncopy/movable struct U, membes of that struct can not be assigned in the constructor (see C). They can only be initialized via a member initializer list (see S). struct U { U(int x); U(U &other) = delete; U(U &&other) = delete; }; struct S { S(int x) : u(x) {} U u; }; struct C { C(int x) { u = U(x); } // compiler complains: cannot assign U u; }; Error: <source>:13:5: error: constructor for 'C' must explicitly initialize the member 'u' which does not have a default constructor C(int x) { u = U(x); } ^ <source>:14:7: note: member is declared here U u; ^ <source>:1:8: note: 'U' declared here struct U { ^ <source>:13:18: error: object of type 'U' cannot be assigned because its copy assignment operator is implicitly deleted C(int x) { u = U(x); } ^ <source>:4:5: note: copy assignment operator is implicitly deleted because 'U' has a user-declared move constructor U(U &&other) = delete; ^ Code is here: https://godbolt.org/z/11nvh1ze4 The compiler of course rightfully complains. If x would be calculated in the constructor body, the initializer list could not be used. Is there any syntax that would allow to do so?
You cannot initialize it in the constructors body. Members are initialized before the body of the constructor is executed. If x is computed when the constructor is called then you can still use the member initializer list. For example when you have a void f(int&) that needs to be called to retrive the parameter for u: struct C { C(int x) : u(compute_x(x)) { } U u; private: static int compute_x(int x) { f(x); return x; } }; There was another now deleted answers that raised a good point about the mental model of a constructor. The point to take away here is that the constructor body is not for initialization of members. This happens before the body runs. Once you got the hang of it you will find yourself writing many constructors whose body is nothing more than {}, because its actually not that common that a constructor does more than setting up the class members.
70,686,708
70,687,209
String to Hex without changing number, C++
While working on a project, I found myself wondering how to convert from string to hex. Not just converting from, let's say, the string "42" to hex 0x3432. I'm curious how you would go about converting the string "0x42" to hex 0x42. As in, assume the string given is a valid hex number (I know that's a big assumption, but go with it...). I want to use that as a hex number, not as a string anymore. How would I go about doing that conversion? This isn't something I'd do... I'm just more curious if and how it would be done, as I've never run into this type of problem until now. *Using C and C++
As this is just a matter of different representations of the same value, its IO streams that offer such "conversion": #include <sstream> #include <iostream> int main() { std::stringstream ss{"0x42"}; int x = 0; ss >> std::hex >> x; std::cout << x << "\n"; std::cout << std::hex << x; } Output: 66 42
70,686,762
70,687,060
How to understand the usage of #define directive in this code example?
I am looking into the #define directive recently. And I am confused by the #define usage in the following code example. Anyone could explain how it works? template <> __inline__ __device__ void warpReduce<ReduceType::kSum, 2>(float* val_list) { float val0_tmp, val1_tmp; #define WarpReduceSumOneStep(a, b) \ val0_tmp = __shfl_xor_sync(FINAL_MASK, *(val_list + 0), a, b); \ val1_tmp = __shfl_xor_sync(FINAL_MASK, *(val_list + 1), a, b); \ *(val_list + 0) += val0_tmp; \ *(val_list + 1) += val1_tmp WarpReduceSumOneStep(16, 32); WarpReduceSumOneStep(8, 32); WarpReduceSumOneStep(4, 32); WarpReduceSumOneStep(2, 32); WarpReduceSumOneStep(1, 32); #undef WarpReduceSumOneStep } from my understanding, when WarpReduceSumOneStep(16, 32); occurs, the compiler substitute it with the blocks between #define and #undef, right?
Every preprocessor directive takes up exactly one line. That \ at the ends of some of the lines say "pretend that this isn't really the end of a line". So the definition of the macro WarpReduceSumOneStep includes the next four source lines. They're highlighted in blue on my system. The macro definition ends at the end of that last line, because it doesn't have a \; the end of the line really is the end of the line. After the end of the macro definition, any use of the macro WarpReduceSumOneStep gets replaced by the text in the macro's definition. In the code in the question, that macro is used five times: WarpReduceSumOneStep(16, 32); WarpReduceSumOneStep(8, 32); WarpReduceSumOneStep(4, 32); WarpReduceSumOneStep(2, 32); WarpReduceSumOneStep(1, 32); Each of those is replaced by the text of the macro, with arguments replaced appropriately. I'm not going to go through all five; they're pretty much the same. The first one, WarpReduceSumOneStep(16, 32), becomes val0_tmp = __shfl_xor_sync(FINAL_MASK, *(val_list + 0), 16, 32); val1_tmp = __shfl_xor_sync(FINAL_MASK, *(val_list + 1), 16, 32); *(val_list + 0) += val0_tmp; *(val_list + 1) += val1_tmp and because there's a semicolon after the inovocation of the macro, the full text becomes val0_tmp = __shfl_xor_sync(FINAL_MASK, *(val_list + 0), 16, 32); val1_tmp = __shfl_xor_sync(FINAL_MASK, *(val_list + 1), 16, 32); *(val_list + 0) += val0_tmp; *(val_list + 1) += val1_tmp; After those five uses of the macro, the #undef removes its definition. After that, any use of the name WarpReduceSumOneStep is just a use of that name; the preprocessor won't do anything special with it.
70,687,712
70,689,395
How to expand a non value paramter pack
I've been trying to expand a non value parameter pack recently in C++. Is this possible? And if it's not, why? I mean, as you can see, in the line with the comment //, given a parameter pack for the TypeMap class, how can I call addType<T>() with each type of the parameter pack? Thanks in advance! template <typename... T> class TypeMap { using vari_cmps = std::variant<T*...>; private: template<typename Type> void addType() { typemap[typeid(Type).name()] = std::make_unique<Type>(0).get(); } public: std::map<const char*, vari_cmps> typemap{}; TypeMap() { (addType<T,...>()); // Idk how to use this in order to make it work } ~TypeMap() { typemap.clear(); } };
As @HolyBlackCat has already answered in the comments, you can expand it like this: TypeMap() { (addType<T>(), ...); } If T is std::string, int, float this would expand to: TypeMap() { (addType<std::string>(), addType<int>(), addType<float>()); } There are however a few more issues in this code-snippet: 1. addType() addType() will not work as you'd expect, due to the unique_ptr deleteing your object after you put it into the map. .get() only retrieves the pointer that the unique_ptr manages but does not transfer ownership, so the unique_ptr will still delete the pointed-to object once it gets out of scope, leaving a dangling pointer in your map. so your addType() is roughly equivalent to: template<typename Type> void addType() { Type* tptr = new Type(0); // unique pointer constructs object typemap[typeid(Type).name()] = tptr; // insert pointer value of unique pointer delete tptr; // unique pointer destructs } You could fix this by releasing the unique_ptr after inserting its value into the map & then cleaning it up in the destructor: template<typename Type> void addType() { auto ptr = std::make_unique<Type>(0); typemap[typeid(Type).name()] = ptr.get(); ptr.release(); // now unique_ptr won't delete the object } ~TypeMap() { // cleanup all pointers for(auto& [name, ptrVariant] : typemap) std::visit([](auto ptr) { delete ptr; }, ptrVariant); } 2. Consider using std::type_index instead of const char* as map key std::type_info::name() returns an implementation-defined name for the given type, so you have no guarantee that you will get an unique name for a given type. Returns an implementation defined null-terminated character string containing the name of the type. No guarantees are given; in particular, the returned string can be identical for several types and change between invocations of the same program. std::type_index on the other hand is build specifically for this purpose - using types as keys - and comes with all comparison operators & a std::hash specialization, so you can use it with std::map & std::unordered_map out of the box. e.g.: template <class... T> class TypeMap { using vari_cmps = std::variant<T*...>; private: template<typename Type> void addType() { typemap[std::type_index(typeid(Type))] = /* something */; } public: std::map<std::type_index, vari_cmps> typemap{}; TypeMap() { /* ... */ } ~TypeMap() { /* ... */ } template<class U> U* get() { auto it = typemap.find(std::type_index(typeid(U))); return std::get<U*>(it->second); } }; Consider using std::tuple std::tuple is basically built for this task, storing a list of arbitrary types: e.g.: template <class... T> class TypeMap { private: std::tuple<std::unique_ptr<T>...> values; public: TypeMap() : values(std::make_unique<T>(0)...) { } template<class U> requires (std::is_same_v<U, T> || ...) U& get() { return *std::get<std::unique_ptr<U>>(values); } template<class U> requires (std::is_same_v<U, T> || ...) U const& get() const { return *std::get<std::unique_ptr<U>>(values); } }; usage: TypeMap<int, double, float> tm; tm.get<int>() = 12; If you want you can also store T's directly in the tuple, avoiding the additional allocations.
70,689,073
71,063,033
QT on Raspberry Pi 4
I have a Raspberry Pi 4 Model B Rev 1.4 and I am using Ubuntu 20.04 running in VirtualBox on a Windows 10 machine. I have been following the steps presented in this video https://www.youtube.com/watch?v=TmtN3Rmx9Rk&list=PLXAxzIhirYJGp1dMN0SxMRNCumubmpzWj&index=2&t=1686s. The goal is to run QT C++ applications on the Raspberry Pi @24.20, the presenter issues the command: rsync -avz --rsync-path="sudo rsync" pi@192.168.1.237:/lib sysroot His host machine receives a number of files. On the video I can see the contents of lib/firmware, lib/modules.bak, lib/modules, lib/udev However, when I issue the same command, I only receive a symbolic link receiving incremental file list lib -> usr/lib BTW, a symbolic link is also what I see on the RPi lrwxrwxrwx 1 root root 7 May 7 2021 bin -> usr/bin I tried adding the option --copy-links. It allows me to copy the files, but the usr/bin directory is about 3GB and it seems to have a many more folders (for instance chromium-browser) when compared to what I saw in the video Why the discrepancy? Did I miss an initial setup step, maybe? Any advice?
Had the same problem. the /lib you want to copy is a link, not a folder. It's linked to /usr/lib. So try it with rsync -avz --rsync-path="sudo rsync" pi@192.168.1.237:/usr/lib sysroot
70,689,563
70,690,538
Google test using C++11/14, how to fix the invalid POSIX Extended error
I am using gtest to do unit test and trying to use the function MatchesRegexto match the pattern a string contains multiple substrings using look around. e.g Verifying the statement The team members are Tom, Jerry and a Terminator contains all three keywords Tom, Jerry and Term std::string target = "The team members are Tom, Jerry and a Terminator"; EXPECT_THAT(target, MatchesRegex("(?=.*(Tom))(?=.*(Jerry))(?=.*(Term))")); But I am getting an error Regular expression "((?=.*(Tom))(?=.*(Jerry))(?=.*(Term)))" is not a valid POSIX Extended regular expression. Any suggestion to fix the regexp? The test code can be found here
POSIX regular expressions in C++ are very limited. Fortunately, you may combine expectations logically. #include <iostream> #include <string> #include <gmock/gmock.h> using testing::AllOf; using testing::MatchesRegex; TEST(RegexTest, Simple_Regex_Matcher) { std::string target = "The team members are Tom, Jerry and a Terminator"; EXPECT_THAT(target, AllOf(MatchesRegex(".*Tom.*"), MatchesRegex(".*Jerry.*"), MatchesRegex(".*Term.*"))); } int main(int argc, char*argv[]) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } Output: [==========] Running 1 test from 1 test suite. [----------] Global test environment set-up. [----------] 1 test from RegexTest [ RUN ] RegexTest.Simple_Regex_Matcher [ OK ] RegexTest.Simple_Regex_Matcher (0 ms) [----------] 1 test from RegexTest (0 ms total) [----------] Global test environment tear-down [==========] 1 test from 1 test suite ran. (0 ms total) [ PASSED ] 1 test.
70,689,568
70,689,828
Is overloading int function with the same long long function has any point?
Here is a simple example: int function (int n) { //code } long long function (long long n) { //absolutely the same code but intended to work with bigger values } I was thinking about saving extra memory (if you use it with variables of small types) AND making it more universal (if you use it with variables of big types) I hope you get my idea here - dont use long long if you put something like 15 in there, instead use overload for smaller types (like int). I think I'm missing something here. Should i even make this overload? Can I make most universal AND most optimal function without overloading it for each existing integer type (short, int, long, long long...)?
If you're writing code for reasonably-recent personal computers or web servers, having a separate int version is probably a premature optimization, given that most of these machines have 64-bit processors anyway, so calculations with 64-bit long long should be fast. OTOH, if you're writing for an 8/16/32-bit embedded system on which 64-bit arithmetic is dramatically slow, it might be a worthwhile speed optimization. But it's still unlikely to be helpful in terms of memory usage due to the fact that having duplicate implementations of a function will increase the size of your compiled code, thus cancelling the benefit of using less memory for your variables. Unless that function takes an array of possibly millions of integers instead of just one, in which case the data size is more of a concern than the code size. If you do insist on having overloaded functions for different integer sizes, I recommend using Ranoiaetep's suggestion of making it a template function, so as to avoid duplication in the source code.
70,689,663
70,693,776
How to link multiple .cpp files in Code::Blocks for a single project?
While following the book C++ For Dummies, I have three files in my CodeBlocks project, main.cpp, Pen.h, and Pen.cpp. They look like this: main.cpp: #include <iostream> #include "Pen.h" //#include "Pen.cpp" using namespace std; int main() { Pen MyPen = Pen(); MyPen.test(); } Pen.h: #ifndef PEN_H_INCLUDED #define PEN_H_INCLUDED //#include "Pen.cpp" // Uncommenting this gives a different error using namespace std; class Pen { public: // attributes omitted // PROTOTYPES: // other functions omitted void test(); }; #endif // PEN_H_INCLUDED Pen.cpp: #include <iostream> #include "Pen.h" using namespace std; //other function definitions omitted void Pen::test() { cout << "Test successful." << endl; } When I run the code as listed above, I get an "undefined reference to `Pen::test()'" error. To fix this, I changed the #include statements at the top of main.cpp to: #include <iostream> //#include "Pen.h" #include "Pen.cpp" This works as intended and correctly prints out "Test successful." My question is this: what in the world is the point of putting a function prototype in a header file if I have to import the .cpp file later on anyways? EDIT: It turns out this was a problem with not knowing how to use Code::Blocks rather than with the C++ language.
In the main.cpp include the header file: #include "Pen.h" The Pen.h file it's ok. You need to add the Pen.cpp file to the project tree. Go to Project -> Add files... and add Pen.cpp
70,689,687
70,689,712
Why do operation on <bit> return signed numbers?
Operations like template< class T > constexpr int popcount( T x ) noexcept; return a signed integer, but the number of set bits can never be negative? What was the motivation for choosing a signed rather than unsigned type?
From the paper: The counting operations return "int" quantities, consistent with the rule "use an int unless you need something else". This choice does not reflect, in the type, the fact that counts are always non-negative. gcc's intrinsic here (__builtin_popcount) also returns int.
70,689,689
70,690,647
Update Template Parameter/Recast Template With New Parameter
I'm creating a tree of templated typenames. I am using tuples for the trees structure. Every Node in the tree that is not a leaf will contain a tuple of typenames containing other Nodes and Leaves. The leaves will contain a size and an offset representing their position within the tuple (relative to root node and based on the size of the leaf nodes before it). Essentially all values will be known at compile time, I would like to use the tuple as a map of sorts. The end result will look something like so: Simple enough, I create a variadic template note and unpack the result into a tuple for the nodes template<typename... Elements> struct Node { std::tuple<Elements...> elements; }; But the catch is that I would like both the Nodes and the leaves to contain a template argument for their offset position within the tuple, that way I can access "Leaf 4" for example from Node 1 by using std::get<0>(std::get<1>(Node0)), and from within "Node 2" I could access its elements each of which would still know their offset within the "grander tuple". Programmatically this would look something like so (albeit below does not account for the offset part): template<uint16_t offset, uint16_t size> struct Leaf { constexpr uint16_t GetOffset() {return offset; } constexpr uint16_t GetSize() {return size; } }; template<uint16_t offset, typename... Elements> struct Node { std::tuple<Elements...> elements; //Does not setup proper offsets constexpr uint16_t GetOffset() { return offset; } }; As you can see I have a tuple of elements but I would need to "Recast" them into new templates using a new offset based on the size of the leaves prior. So, along the lines of "Recasting" my next idea was this: template<uint16_t offset, uint16_t size> struct Leaf { static constexpr uint16_t GetOffset() {return offset; } static constexpr uint16_t GetSize() {return size; } //New ability to Recast template<uint16_t newOffset> struct Recast { typedef Leaf<newOffset, size> type; }; }; template<uint16_t offset, typename... Elements> struct Node { static constexpr uint16_t GetSize() { return (Elements::GetSize() + ...); } static constexpr auto GetElements() { uint16_t size = 0; //Using the comma operator to increment size before recasting using it return std::tuple<(Elements::template Recast<(size+= Elements::GetSize(), size)>::type)...> } static constexpr auto elements = GetElements(); static constexpr uint16_t GetOffset() { return offset; } //New ability to Recast template<uint16_t newOffset> struct Recast { typedef Node<newOffset, Elements...> type; }; }; But now I'm running into issues where size can't be used as a constant expression and even if it was the increment would come before it was used as an offset by the recast due to the order of operations using the comma operator. Long story short, how can I make this vision a reality, is their a tweak I can make to the existing setup or is there a different tool that I should be using that would help simplify this whole thing? To potentially clear things up I am using template arguments to store the offset because that way I can ensure that it can be evaluated at compile time and so that the data memory storage of such values is unnecessary. Basically I want to make sure that if these values are going to be inlined anyways that they aren't also taking up space on the stack or heap. If there is another way to accomplish something similar that would be perfect as well.
Sorry if I don't quite get the exact logic how the code work, but you might try this: struct Node { ⋮ ⋮ template<uint16_t ... I, uint16_t ... J> static constexpr auto GetElements_helper(std::integer_sequence<uint16_t, I...>, std::integer_sequence<uint16_t, J...>) { constexpr std::array arr{I...}; return std::tuple<typename Recast<std::accumulate(arr.begin(), arr.begin() + J + 1, uint16_t {})>::type...>{}; } static constexpr auto GetElements() { return GetElements_helper(std::integer_sequence<uint16_t, Elements::GetSize()...>{}, std::make_integer_sequence<uint16_t, sizeof...(Elements)>{}); } ⋮ ⋮ }
70,690,329
70,690,358
Declare static arrays in a struct right in C++
I tried to declare static array: #include <iostream> #include <string.h> using namespace std; struct tagData{ static string tags[]; }; int main(){ tagData::tags[3]; tagData::tags[0] = "default"; tagData::tags[1] = "player"; tagData::tags[2] = "enemy"; return 0; } But as the result an error occurred: *Path*\cczPqyfY.o:main.cpp:(.text+0x1e): undefined reference to `tagData::tags[abi:cxx11]' *Path*\cczPqyfY.o:main.cpp:(.text+0x32): undefined reference to `tagData::tags[abi:cxx11]' *Path*\cczPqyfY.o:main.cpp:(.text+0x46): undefined reference to `tagData::tags[abi:cxx11]' collect2.exe: error: ld returned 1 exit status I was looking for some info about how to declare static arrays in structs, but couldn't. Can anybody show me an example or help me in another way? P.S. I tried to compile this code with GCC version 8.1.0;
struct tagData{ static string tags[]; }; This static class member must be defined in global scope, and not as a local variable in a function like main: string tagData::tags[3]; And now, once the formalities are taken care of, you can manually access its class members, in main or any other function: int main(){ tagData::tags[0] = "default"; tagData::tags[1] = "player"; tagData::tags[2] = "enemy"; return 0; } However, if the goal is to initialize the array there's an even better way. Just initialize it as part of its definition: string tagData::tags[3]={"default", "player", "enemy"}; Note: when defining static class member, you should always keep in mind the static initialization order fiasco.
70,690,458
70,690,588
Is a pointer pointing to another array and deallocating memory at the end considered as memory leak in c++?
#include <iostream> using namespace std; int main() { int* pointer = new int[5]; pointer = new int [10]; delete[] pointer; return 0; } After allocating new memory for the pointer, what happens to the old memory with the length of 5? If it is a memory leak, should I use realloc() instead?
I want you to picture yourself in the following scenario You are standing next to an abyss with one arm tied behind your back. Thus, you have one hand available. That hand is your pointer var. At some point you request of me to throw you a ball. That ball is the memory being allocated via new. I toss you the ball, which you catch with your one free hand. You don't "own" the ball per se, but it is entirely on loan to you, and is your exclusive responsibility. I'm trusting you to toss it back if/when you don't need it anymore. Now, you request I throw you a different ball, a new new, if you will. I do so, and you catch the new ball, but to do so you first drop the old ball (pun intended; yes, you "dropped the ball"). It falls into the abyss. Where it ultimately ends up nobody knows. But now you are holding the second ball. Now the time comes to return the balls I've handed out to you. You toss me the one you still have, good. But the first one is gone forever. It is in no one's hand, and no one knows where it is. That is a memory leak. It can be circumvented a number of ways. You could toss the ball back to me before you request the new one. You could break the shackles that bind your other arm, and catch it there. Now you have two balls in two hands (e.g. two allocations held in two pointers), both of which you will (hopefully) someday toss back to me once finished with them. You could use a hyped up prototype ball that has auto-magic super-homing-beacon logic, so if ever tossed to the side it does not fall into the abyss. Instead, it knows how to find its way back to me all on its own. (smart pointer). You could use a special ball that knows how to instinctively ask me for more size when needed (to a point). (a std::vector for example) etc. Yes, you have a memory leak. A blatant one. You can solve it by returning the memory via delete[] before asking for more. You can solve it by using more than one pointer and managing them both. You can solve it using intelligent constructs like smart pointers to assist in lifetime management. Or you can do what modern C++ programmers do: use RAII tactics to let the code, and intelligent containers, manage things mostly for you. Regarding realloc... just don't. realloc is a C mechanic for resizing buffers (and even allocating them if need be). But it does not know one iota about the characteristics of complex entities being stored within. Failure to properly construct and destruct objects with such complexity spells disaster whence later referenced. In the long run, embrace the concept of programming in a different language, with different patterns and methodologies. C doesn't have all these whiz-bang containers like std::vector; you do. C doesn't have smart pointers; you do. Etc. Embrace that early and often. It will pay for itself many times over down the road.
70,690,649
70,690,855
Bezier curve... adding normals (in 3D)
I have a bezier curve class. Each point on the curve is defined thus: struct bpoint { vector3D position; vector3D controlpoint_in; vector3d controlpoint_out; }; To retrieve a point on the curve's spline (the curve can have infinite points), I use this function: vector3d GetSplinePoint(float thePos) { float aPos=thePos-floorf(thePos); int aIPos=(int)floorf(thePos); bpoint& aP1=pointList[aIPos]; bpoint& aP2=pointList[min(aIPos+1,pointList.size())]; vector3D aResult; vector3D aAB, aBC, aCD, aABBC, aBCCD; Lerp(aAB,aP1.mPos,aP1.mOut,aPos); Lerp(aBC,aP1.mOut,aP2.mIn,aPos); Lerp(aCD,aP2.mIn,aP2.mPos,aPos); Lerp(aABBC,aAB,aBC,aPos); Lerp(aBCCD,aBC,aCD,aPos); Lerp(aResult,aABBC,aBCCD,aPos); return aResult; } Works great, but now I'm in a situation where I want to add normals to each point, so that I can do some fancier stuff (rotations, etc). Like so: struct bpoint { vector3D position; vector3D controlpoint_in; vector3d controlpoint_out; vector3d normal; }; I've been utterly unsuccessful in trying to write a GetSplineNormal(float thePos) function. I'm not even sure where to begin-- I thought I could just interpolate between the points, but I don't know how to factor in the control points. How could I accomplish this?
Ok, so, there are a few things to consider, mathematically speaking. First, your curve has a certain shape, so at each point of the curve there is one and only one plane perpendicular to the current direction of the curve. The normal has to be a part of this plane. So your curve is parametrized by thePos, which, to simplyfy my mathemathical notation, I will write as t: x(t), y(t), z(t). The perpendicular plane at pos t is given by the equation: d_t x(t) * (x - x(t)) + d_t y(t) * (y - y(t)) + d_t z(t) * (z - z(t)) = 0, where d_t x(t) is the derivative with respect to t of x(t), d_t y(t) for y(t) and d_t z(t) for z(t). For the orientation of the normal vector (i.e. in which direction the normal is facing in this perpendicular plane), you can interpolate between the two control points. Just pay attention, interpolating angles can be tricky, as you have to account for the direction. Linear interpolation of the angle coordinate is an option, but you can also interpolate the normal vectors directly and then reproject on the perpendicular plane using least squares. It really depends what you want to use the normal for. Finally, remember that this perpendicular plane also exists at the control points, so you might have to constrain the normal given by the user (by reprojecting it using least squares).
70,690,749
70,690,771
Why can't compare int and size_t in c++
The thing is that if I compare int and size_t in for loop it works fine. vector<int> v; for (int i = 0; i < v.size(); ++i) However, it doesn't work if I do this: vector<int> v; int max_num = max(3, v.size()); Line 13: Char 24: error: no matching function for call to 'max' /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/algorithmfwd.h:370:5: note: candidate template ignored: deduced conflicting types for parameter '_Tp' ('int' vs. 'unsigned long') max(const _Tp&, const _Tp&); ^ /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_algo.h:3462:5: note: candidate template ignored: could not match 'initializer_list<type-parameter-0-0>' against 'int' max(initializer_list<_Tp> __l, _Compare __comp) ^ /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_algo.h:3456:5: note: candidate function template not viable: requires single argument '__l', but 2 arguments were provided max(initializer_list<_Tp> __l) ^ /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/algorithmfwd.h:375:5: note: candidate function template not viable: requires 3 arguments, but 2 were provided max(const _Tp&, const _Tp&, _Compare); ^ 1 error generated. In the bottom case, I have to cast size_t into int to make it works. Why in the for loop I don't need to do that? Just curiouos.
In C++ when the types of a binary operator are different, there are various (complicated) rules that govern what actual type the binary operator uses: i < v.size() One of these is an int. The other one is a size_t. This is ok, there are rules that figure out which actual type is used for the comparison (the int value gets type-converted to size_t, then the < operator does the comparison. max(3, v.size()); The definition of std::max functionally requires both of its parameters to be the same type. They're not. Hence the compilation error. Now that you understand the reason, try to reread the following error message, and see if you now understand the compiler telling you exactly that: deduced conflicting types for parameter '_Tp' ('int' vs. 'unsigned long') max(const _Tp&, const _Tp&); As you can see here, the compiler is trying very hard to digest a function with two parameters, both of which are the same type: const _Tp &. That's how max()'s definition reads: both of its parameters are the same type. Well, the poor compiler sees that one of these parameters is an int, the other one is size_t (a.k.a. "unsigned long") and gives up.
70,690,912
70,690,989
binary comparison not defined when using map<any,any>
I was looking for a way to have a string[] as a map value, and I found this Stack Overflow question. I attempted to use the std::any type to solve my problem, and I got the error binary '<': 'const _Ty' does not define this operator or a conversion to a type acceptable to the predefined operator Here is my code: #include <iostream> #include <map> #include <any> using namespace std; map<any,any> dat; int main() { any s[] = {"a","b"}; dat["text"] = s; return 0; }
std::map by default requires that the key type be comparable with <. std::any does not define any operator< and can therefore not be used as key in the map by default. If you really want to use it in the map as a key, you need to implement your own comparator, see this question. However, the comparator needs to define a weak strict order. It is probably not going to be easy to define that for std::any. It is unlikely that map<any,any> is the correct approach to whatever problem you are trying to solve. If you want a std::string array as key or value type, then use std::array<std::string, N> or std::vector<std::string> instead of a plain std::string[N]. The std::map will work with these types out-of-the-box. std::any has only very few use cases. If you don't have a very specific reason to use it, you probably shouldn't try to use it.
70,691,206
70,691,233
Access to field results in dereference of a null pointer in C
This question is related to C Programming Language: I get error: Access to field 'x' results in a dereference of null pointer #include <stdlib.h> #include <stdio.h> typedef struct A { int *x; int *y; } A; void allocateStruct(int sizeN, A *aType); void printInfo(A *aType); int main() { A *genericA; allocateStruct(5, genericA); int x[5] = {2, 3, 4, 5, 6}; int y[5] = {12, 36, 40, 52, 23}; genericA->x = x; genericA->y = y; printInfo(genericA); } void allocateStruct(int sizeN, A* aType) { aType->x = (int*)malloc(sizeN * sizeof(int)); aType->y = (int*)malloc(sizeN * sizeof(int)); } void printInfo(A *aType) { printf("%i %i\n", aType->x[0], aType->y[0] ); }
You haven't allocated a memory to the structure and yet you are accessing it's member in void allocateStruct(int sizeN, A* aType) { aType->x = (int*)malloc(sizeN * sizeof(int)); aType->y = (int*)malloc(sizeN * sizeof(int)); } allocate memory to the structure itself first atype = malloc(sizeof(A)) You need to return the address of atype to your main function as you are passing the pointer by value else your changes in allocateStruct wont be accessible in main and also cause a memory leak. You don't need to pass atype as a parameter in case you are returning the address. A* allocateStruct(int sizeN){ A* atype; atype = malloc(sizeof(A)); aType->x = malloc(sizeN * sizeof(int)); aType->y = malloc(sizeN * sizeof(int)); return atype; } and in main atype = allocateStruct(5); Also you dont need to typecast explicitly in C, the malloc returns a void pointer and it can be assigned to any type. And also for completeness so that you dont cause memory leaks at the end of main just free all your memory that you have malloced. free(atype->x); free(atype->y); free(atype);
70,691,337
70,691,427
Create a class run at main() get undefined reference to... error
arrayADT.h #include <iostream> using namespace std; template <class T> class arrayADT { private: T *A; static int size; static int length; public: arrayADT(){ size=10; A= new T[size]; length=0; } void increaseSize(){ T *p; size=size*2; p= new T[size]; delete[] A; A=p; p=NULL; } int getSize(){ return size; } ~arrayADT();}; example.cpp #include<iostream> #include<stdio.h> #include"arrayADT.h" using namespace std; int main(int argc, char const *argv[]) { arrayADT<int> s; s.increaseSize(); s.getSize(); return 0; } Get error: undefined reference to `arrayADT::~arrayADT()' undefined reference to `arrayADT::~arrayADT()' undefined reference to `arrayADT::length' undefined reference to `arrayADT::size' Can anyone help me? Thanks very much!
I found two different problems: The destructor method must have a scope with {} even if it is empty. I removed the static keyword as each object will have size and length property. #include <iostream> #include <stdio.h> #include <string> using namespace std; template<class T> class arrayADT { private: T *A; int size; /* Removed the static keyword used in data members. */ int length; /* Removed the static keyword used in data members. */ public: arrayADT() { size = 10; A = new T[size]; length = 0; } ~arrayADT(){} /* The destruction method has been edited. */ void increaseSize() { T *p; size = size * 2; p = new T[size]; delete[] A; A = p; p = NULL; } int getSize() { return size; } }; int main(int argc, char const *argv[]) { arrayADT<int> s; s.increaseSize(); cout << s.getSize() << endl; return 0; }
70,691,372
70,692,382
Using predicates in custom implemented data structures
I have a cusom implemented Heap for priority queue application class Heap { SomeCutsomClass elements[100]; .... .... }; Now I need to support two different comparison operation between the keys of the heap and I want to implement it using c++ predicates struct less1 { bool operator()(const SomeCutsomClass& c1, const SomeCutsomClass& c1) { //specific implementation } }; struct less2 { bool operator()(const SomeCutsomClass& c1, const SomeCutsomClass& c1) { //specific implementation } }; Ideally I should be able to pass the predicates somehow in the constructor of Heap I am not able to visualize how to achieve this. It is not that I want to use only predicates.Since I cant overload same operator twice in SomeCutsomClass , I am trying to use predicates. I tried looking up STL source code of some well known data structures like std::sort etc , but they look complicated to me.
Here is an example containing both an example of std::less use and custom predicates as functions (lambdas). #include <cassert> #include <array> #include <iostream> #include <functional> // Make heap a class template // this allows you to specialize easily for any class // I added the STL like third template parameter as example // type_t is the type to store in the heap // N is the size of the heap template<typename type_t, std::size_t N, class Compare = std::less<type_t>> class Heap { public: using pred_t = std::function<bool(const type_t&, const type_t&)>; Heap() : m_predicate{ Compare() } { } explicit Heap(pred_t predicate) : m_predicate{ predicate } { } bool compare(const int a, const int b) { return m_predicate(a, b); } private: std::array<type_t, N> m_elements; pred_t m_predicate; }; struct SomeCustomClass { // all you need to make SomeCustomClass usable in Heap // if it uses std::less as third template parameter // is to provide this compare overload bool operator<(const SomeCustomClass& other) const { return m_value < other.m_value; } int m_value{}; }; int main() { // this heap will use std::less Heap<int, 100> less_heap; assert(less_heap.compare(1, 2)); // create a lambda predicate auto pred = [](const int& lhs, const int& rhs) { return lhs > rhs; }; // this heap will use custom predciate Heap<int, 100> greater_heap(pred); assert(greater_heap.compare(2,1)); // Heap<SomeCustomClass, 10> custom_heap; return 0; }
70,691,413
70,694,322
C++ derived-class members after downcasting
I recently learned about upcasting and downcasting in C++. However I came up with a few questions during reading about downcasting. Say I have two classes class Base { public: virtual void foo() {} }; class Derived : public Base { public: Derived(int i) { mem = i; } int mem; }; My questions are the followings: If I create an object Derived d(1), upcast to Base class, and then downcast it back to Derived class, is 'mem==1' preserved? Do I still have access to it? Assume pointer or reference is used so object slicing doesn't happen and dynamic_cast is used for downcasting. When downcasting from Base class to Derived class, there will an additional member variable 'mem'. Is memory allocated for 'mem' during run-time (using dynamic_cast)? To what value will it be initialized to? After some simple experiments, 1 seems to be true. However for 2 it seems I can't start from a Base class pointer and dynamic_cast it into Derived class pointer as dynamic_cast returns null. I read from another post saying "But the basic point of dynamic_cast is that it first checks that the pointee object is really of the derived type, and then returns a pointer to it, or returns a null pointer if the pointee object isn't actually of (or derived from) the requested target type." Is this saying we can't actually start from the Base class and simply downcast it into Derived class, but rather the whole point of dynamic_cast is to "cast back" something that has been upcasted?
It depends; if you cast a Derived object to Base, the result is a new object created by omitting the fields that are not in the Base. However, if you cast a pointer to Derived (i.e. Derived*), the result is a pointer which points to the same object but whose type is Base*. It depends; if you cast a Base object, you get a compile error unless you overload the typecast operator for doing such an operation (you have correctly observed that the values of the fields would otherwise be undefined). However, if you cast a Base* (a pointer) to Derived* (using dynamic_cast<Derived*>(p)), the result depends on the object the pointer points to. If it points to an instance of the Derived class (or its subclass), the result is a Derived* pointer to that object; otherwise, you get a nullptr pointer of type Derived*.
70,691,644
70,691,679
How can I repeat a number cycle using mod operator?
I have to loop through 1 <= i <= 20 and every time I mod any i, I want to get a value between 1,2,3. Sorry I have not found any useful resources online. That's why I posted it here. Thanks in advance.
In C++ the % sign acts as the remainder operator. If you do i % 3; The possible values are 0, 1, and 2. Using that as a starting point, we can shift by 1: (i % 3) + 1; The possible values are now 1, 2, and 3.
70,691,678
70,692,354
Is it possible to define a group of template parameters and specialize it conditionally
struct TypeA { using data_t = int; enum { thread_create = pthread_create }; // ??? }; struct TypeB { using data_t = double; enum { thread_create = another_kind_of_thread_create }; // ??? }; template<typename T> class Test { public: void func() { T::thread_create(); // ??? } private: T::data_t a; }; Test<TypeA> t1; Test<TypeB> t2; What I'm trying to do is to specialize the template class Test with one single template parameter. As you see, data_t shouldn't be any problem but it doesn't seem that passing a function is easy. This piece of code will generate an error: error: enumerator value for 'thread_create' must have integral or unscoped enumeration type. Is it possible to pass a function like this?
I if understand you correctly, you want to switch thread creation function and data type depending on the specialization. If so, why not sth like this? #include <type_traits> void pthread_create(void*, void*); void another_kind_of_thread_create(void*, void*); //my fakes. use your includes here struct TypeA { using data_t = int; using thread_create_t = void (*)(void*, void*); static constexpr thread_create_t thread_create{pthread_create}; }; struct TypeB { using data_t = double; using thread_create_t = void (*)(void*, void*); static constexpr thread_create_t thread_create{another_kind_of_thread_create}; }; template<typename T> class Test : public T { public: void func() { T::thread_create(this, &a); //whatever, put here just to match the prototype... } private: typename T::data_t a; }; Test<TypeA> t1; Test<TypeB> t2; static_assert(std::is_same<decltype(t1)::data_t, int>::value, "t1 should be int"); static_assert(std::is_same<decltype(t2)::data_t, double>::value, "t2 should be double"); demo
70,692,034
70,733,052
'dllimport' attribute only applies to variables, functions and classes warning even though applied to class function
I'm in the middle of a port to the newest c++ Builder 11 (Clang) compiler and I ran into a warning that I don't understand The warning: 'dllimport' attribute only applies to variables, functions and classes The simplified code: class Test { public: Test() ; int __declspec(dllimport) (*DllFunction) (int a, int b) ; } ; And during construction (for instance) I load the dll and find a pointer for DllFunction This is a function, so .. why the warning ? What am I not getting ?
As the error message says, dllimport cannot be used to import individual class methods. Only standalone variables and functions, and whole classes. However, dllimport is meant for static linking only, but you are using dynamic loading instead, so there is no need to use dllimport in this code at all.
70,692,366
70,692,659
Difference in evaluation of expression when using long long int vs double in c++
I'll refer to the below code to explain my question. typedef long long int ll; void func(){ ll lli_a = 603828039791327040; ll lli_b = 121645100408832000; double d_b = (double)lli_b; cout << "a " << lli_b - d_b << endl; \\0 cout << "b " << (lli_a - 4*lli_b) - (lli_a - 4*d_b) << endl; \\64 cout << "c " << (lli_a - 4*lli_b) - (lli_a - (ll)4*d_b) << endl; \\64 cout << "d " << (lli_a - 4*lli_b) - (lli_a - 4*(ll)d_b) << endl; \\0 cout << "e " << 4*(ll)d_b - 4*d_b << endl; \\0 cout << "f " << 4*(ll)d_b - (ll)4*d_b << endl; \\0 } I'm unable to understand why statements b and c have evaluated to 64, while d has evaluated to 0, which happens to be the correct answer. Both e and f evaluate to 0, so the difference is coming because of subtraction from lli_a I assume. I don't think there is any overflow issue as individual values for each term are coming correctly.
Some code to walk you through it, bottom line don't mix doubles with ints implicitly #include <cassert> #include <iostream> #include <type_traits> // typedef long long int ll; NO , use using and never use aliasing to safe a bit of typing. Aliases are there to introduce meaning not shortcuts //using namespace std; // also NO int main() { long long int lli_a = 603828039791327040; long long int lli_b = 121645100408832000; //double d_b = (double)lli_b; // No this is C++ don't use 'C' style casts double d_b = static_cast<double>(lli_b); assert(static_cast<long long int>(d_b) == lli_b); // you are in luck the double can represent your value exectly, NOT guaranteed std::cout << "a " << lli_b - d_b << "\n"; // endl; \\0 don't use endl unless you have a good reason to flush long long int lli_b4 = 4 * lli_b; // use auto to show you this expression evaluates to a double! auto lli_d_b4 = (lli_a - static_cast<long long int>(4) * d_b); // d_b is double!!! what do you want to do here? Use it as a long long int then cast it first static_assert(std::is_same_v<double, decltype(lli_d_b4)>); auto result_c = lli_b4 - lli_d_b4; // result c is still a double! static_assert(std::is_same_v<double, decltype(result_c)>); std::cout << "c " << result_c << "\n"; // long story short don't mix types implicitly and use "C++" style cast explicitly to get the results you want /* cout << "b " << (lli_a - 4 * lli_b) - (lli_a - 4 * d_b) << endl; \\64 cout << "c " << (lli_a - 4 * lli_b) - (lli_a - (ll)4 * d_b) << endl; \\64 cout << "d " << (lli_a - 4 * lli_b) - (lli_a - 4 * (ll)d_b) << endl; \\0 cout << "e " << 4 * (ll)d_b - 4 * d_b << endl; \\0 cout << "f " << 4 * (ll)d_b - (ll)4 * d_b << endl; \\0 */ return 0; }
70,692,369
70,692,963
Pointers in recursion not working as expected
I'm trying to do BST insertion; struct Node { Node* left; Node* right; int data; Node(int d) :left(nullptr), right(nullptr), data(d) { } }; void Insertion(Node* head, int value) { if (!head) { head = new Node(value); return; } if (head->data > value) Insertion(head->left, value); else Insertion(head->right, value); } void printTree(Node* root) { if (!root) { return; } cout << root->data << " "; //20 15 10 18 30 35 34 38 printTree(root->left); printTree(root->right); } int main() { Node *root = new Node(20); Insertion(root, 15); Insertion(root, 30); Insertion(root, 10); Insertion(root, 18); Insertion(root, 35); Insertion(root, 34); Insertion(root, 38); printTree(root); } My Insertion method won't insert properly. But if I use it like the following it does; Node* Insertion(Node* head, int value) { if (!head) { return (new Node(value)); } if (head->data > value) head->left = Insertion(head->left, value); else head->right = Insertion(head->right, value); return head; } I'm not sure if Node* head is a copy of what I'm sending, if it is, is it possible to create the same function without using a Node return type but by passing head by reference?
You can use a reference to pointer like mentioned in the comment, or you can also use a pointer to pointer like the following: void Insertion(Node** head, int value) { if (!(*head)) { *head = new Node(value); return; } if ((*head)->data > value) Insertion(&(*head)->left, value); else Insertion(&(*head)->right, value); } And call the function like this: Node *root = new Node(20); Insertion(&root, 15); In your code, you are just copying the address to the function parameter (pointer variable). And inside the function, you are assigning another address to it. But that's not what you want in this case. You need to change the content of the address that you are passing.
70,692,502
70,693,027
Converting Apache Arrow Table to RecordBatch in c++
I would like to obtain a std::shared_ptr<arrow::RecordBatch> from an std::shared_ptr<arrow::Table> as std::shared_ptr<arrow:Table> table = ... auto rb = std::RecordBatch::Make(table->schema(), table->num_rows(), table->columns()).ValueorDie(); However the compiler complains that there's no known conversion from 'const vector<shared_ptr<arrow::ChunkedArray>>' to 'vector<shared_ptr<arrow::Array>>' since the table->columns() of course returns vector<shared_ptr<arrow::ChunkedArray>>. I can't seem to convert the arrow::ChunkedArray into arrow::Array. I've poured over the documentation but I can't, for the life of me figure out how to do this. How do I go about it, and alternatively, is there another way to convert a arrow::Table into an arrow::RecordBatch?
There is a helper method arrow::Table::CombineChunksToBatch which should become available in the 7.0.0 release. In the meantime you can do this: ARROW_ASSIGN_OR_RAISE(std::shared_ptr<Table> combined, table->CombineChunks(/*Can pass memory_pool here*/)); std::vector<std::shared_ptr<Array>> arrays; for (const auto& column : combined->columns()) { arrays.push_back(column->chunk(0)); } std::shared_ptr<RecordBatch> batch = RecordBatch::Make(table->schema(), table->num_rows(), std::move(arrays)); Keep in mind that this is not a zero-copy operation. Each column in a table is going to consist of multiple arrays. When you call arrow::Table::CombineChunks it will need to allocate a new array big enough for all the chunks and then it will have to copy data from each chunk to this new array. If at all possible it is generally more performant to either keep the table or operate on it in a streaming fashion (e.g. use a arrow::TableBatchReader and operate on one batch at a time).
70,692,739
70,793,464
Detect client context destruction from gRPC server
I have create an Async C++ gRPC server that offer several APIs similar with a signature similar to this: service Foo { rpc FunctionalityA(ARequest) returns (stream AResponse); rpc FunctionalityB(BRequest) returns (stream BResponse); } The client creates one channel to connect to this service, and uses calls the various RPCs from separate threads, something like this: class FooClient { // ... void FunctionalityA() { auto stub = example::Foo::NewStub(m_channel); grpc::ClientContext context; example::ARequest request; example::AResponse response; auto reader = stub->FunctionalityA(&context, request); for(int i = 0; i < 3; i++) { reader->Read(&response); } } void FunctionalityB() { auto stub = example::Foo::NewStub(m_channel); grpc::ClientContext context; example::BRequest request; example::BResponse response; auto reader = stub->FunctionalityB(&context, request); for(int i = 0; i < 3; i++) { reader->Read(&response); } } // ... }; int main() { // ... FooClient client(grpc::CreateChannel("127.0.0.1:12345", grpc::InsecureChannelCredentials())); auto ta = std::thread(&FooClient::FunctionalityA, &client); auto tb = std::thread(&FooClient::FunctionalityB, &client); // ... } I want to implement the server so that: when FunctionalityA is called, it start streaming objects of type AResponse when FunctionalityB is called, it start streaming objects of type BResponse when the context used to call FunctionalityA is cancelled, streaming of AResponse ends when the context used to call FunctionalityB is cancelled, streaming of BResponse ends The problem I face is that even when the ClientContext associated with one of the two Functionalities goes out of scope (after the 3 reads in the example) the server does not receive any information and keeps writing, and the "ok" status remains true. The "ok" status goes to false and allows me to stop Writing only when the client disconnects. Is this the intended behavior of gRPC? Does the client need to send a specific "kiss of death" message in order to inform the server to stop writing on the stream? Here is an example of the implementation of a Functionality server side, for completeness: void FunctionalityB::ProcessRequest(bool ok, RequestState state) { if(!ok) { if(state == RequestState::START) { // the server has been Shutdown before this particular call got matched to an incoming RPC delete this; } else if(state == RequestState::WRITE || state == RequestState::FINISH) { // not going to the wire because the call is already dead (i.e., canceled, deadline expired, other side dropped the channel, etc). delete this; } else { // unhandled state } } else { if(state == RequestState::START) { // the RPC has indeed been started m_writer.Write(m_response, CreateTag(RequestState::WRITE)); // the constructor of the functionality requests a new one to handle future new connections new FunctionalityB(m_completion_queue, m_service, m_worker); } else if(state == RequestState::WRITE) { // TODO do some real work std::this_thread::sleep_for(std::chrono::milliseconds(50)); m_writer.Write(m_response, CreateTag(RequestState::WRITE)); // this write will continue forever, even after client stops reading and TryCancel its context } else if(state == RequestState::FINISH) { delete this; } else { // unhandled state } } }
There are two ways to detect call cancellation on the server. The first one is to check ServerContext::IsCancelled(). That is something you can check right before you do a write, which in this case may be fine. In the general case, though, it may not be ideal, because your application might be waiting for some other event (other than the previous write completing) before it does another write, and you ideally want some async way of getting notified when the cancellation happens. Which brings me to the second approach, which is to request an event on the completion queue when the call is cancelled by calling ServerContext::AsyncNotifyWhenDone() before the RPC starts. This will give you async notification of the cancellation, but unfortunately, the API is very cumbersome and has a few sharp edges. (This is something that is handled much more cleanly in the new callback-based API, but that API isn't that performant in OSS until we finish the EventEngine effort.) I hope this info is helpful.
70,692,897
70,694,614
Last 52 lines are not written in csv file using qt
I have one csv file in which 3 column and 866300 lines. I have try to write this data into other csv file. when i try to write it has write 866248 lines in file after that remaining 52 lines are not write in file. what is the problem I do not understand it. I have try to debug this problem using print that data on console then it has print till last line on the console. only the problem in write the data in file. #include <QCoreApplication> #include <QFile> #include <QStringList> #include <QDebug> #include <QTextStream> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QFile file("C:/Users/hello/Downloads/hello.csv"); QFile write("new_data.csv"); if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug()<<file.errorString(); return 1; } if(!write.open(QIODevice::WriteOnly |QIODevice::Append)) { qDebug()<<file.errorString(); return 1; } QTextStream out(&write); QStringList data; while (!file.atEnd()) { QString line = file.readLine(); data = line.split(','); if (data[0]=="v1") { out<<line; continue; } else { int seq = (data[0].toInt())-1; QString str = QString::number(seq)+","+data[1]+","+data[2].trimmed(); qDebug()<<str; out<<str<<"\n"; } } return a.exec(); } please help.
Please close the file before the return a.exec(); this line and after the while loop. add this line below line. write.close();
70,693,002
70,693,600
AtCoder DP Contest Q -I Coins (getting wrong answer may be using double)
Link to Problem -> https://atcoder.jp/contests/dp/tasks/dp_i question Coins-I Code I wrote gave wrong answer to TEST CASE 3 5 0.42 0.01 0.42 0.99 0.42 Expected output 0.3821815872 MY code output 0.382182 As the error is greater than 1e-9 it got WA What I tried: I made double to long double but still it doesn't give accuracy is there any way to increase the accuracy when working with double in this question. #include<bits/stdc++.h> using namespace std; long double p[3000]; long double dp[3001][1501]; long double solve(int i,int tail_count){ if(dp[i][tail_count]!=2){ return dp[i][tail_count]; } long double ans=0; if(i==1 && tail_count==0)return p[1]; else if(i==1 && tail_count>0)return (long double)1; else if(tail_count==0)ans= p[i]*solve(i-1,tail_count); else ans= (p[i]*solve(i-1,tail_count)+(1-p[i])*solve(i-1,tail_count-1)); dp[i][tail_count]=ans; return ans; } int main(){ for(int i=0;i<3000;i++){ for(int j=0;j<1500;j++){ dp[i][j]=2; } } int n; cin>>n; for(int i=1;i<=n;i++){ cin>>p[i]; } cout<<solve(n,(n-1)/2); return 0; }
The number of digits to be printed via output streams is controlled by their precision parameter. The default is 6 digits, if you want more you need to adjust it accordingly by std::setprecision : std::cout << std::setprecision(num_digits) << solve(n,(n-1)/2); Most of your indexing is off by one. Valid indices of an array with N elements are 0 till (including) N-1. dp is 3001 x 1501 but you only use 3000 x 1500 and p leaves the first element unused. Perhaps the code is still correct, but at least your way of using indices is confusing. Also in case you know the size of the array only at runtime you could use a std::vector.
70,693,057
70,693,263
Partial Constructor arguments from tuple
In C++17 there's std::make_from_tuple; However that only applies to situations where the number of the elements stored in the tuple matches with that of the constructor. I was able to concatenate two tuples and use std::make_from_tuple. #include <iostream> #include <utility> #include <tuple> class ConstructMe{ public: ConstructMe(int a_, int b_, int c_) : a(a_), b(b_), c(c_) { } private: int a; int b, c; }; int main(){ int a = 1; std::tuple<int, int> part = std::make_tuple(2,3); ConstructMe please = std::make_from_tuple<ConstructMe>( std::tuple_cat(std::make_tuple(a), part) ); return 0; } And after some research ( this question I was able to make it work with references as well with std::tie as well. #include <iostream> #include <utility> #include <tuple> class ConstructMe{ public: ConstructMe(int& a_, int b_, int c_) : a(a_), b(b_), c(c_) { } private: int& a; int b, c; }; int main(){ int a = 1; std::tuple<int, int> part = std::make_tuple(2,3); ConstructMe please = std::make_from_tuple<ConstructMe>( std::tuple_cat(std::tie(a), part) ); return 0; } Is there a simpler way to do this ( e.g. with std::bind) which doesn't require c++17?
std::bind does something completely different. Quoting cppreference The function template bind generates a forwarding call wrapper for f. Calling this wrapper is equivalent to invoking f with some of its arguments bound to args. You can just use the cpp reference link to build your own implementation of the standardized function, e.g. in C++14 #include <iostream> #include <utility> #include <tuple> namespace detail { template <class T, class Tuple, std::size_t... I> constexpr T make_from_tuple_impl( Tuple&& t, std::index_sequence<I...> ) { static_assert(std::is_constructible<T, decltype(std::get<I>(std::declval<Tuple>()))...>::value); return T(std::get<I>(std::forward<Tuple>(t))...); } } // namespace detail template <class T, class Tuple> constexpr T make_from_tuple( Tuple&& t ) { return detail::make_from_tuple_impl<T>(std::forward<Tuple>(t), std::make_index_sequence<std::tuple_size<std::remove_reference_t<Tuple>>::value>{}); } class ConstructMe{ public: ConstructMe(int& a_, int b_, int c_) : a(a_), b(b_), c(c_) { } private: int& a; int b, c; }; int main(){ int a = 1; std::tuple<int, int> part = std::make_tuple(2,3); ConstructMe please = make_from_tuple<ConstructMe>( std::tuple_cat(std::tie(a), part) ); } If you want to go back more language versions, you have to do more by hand. It will be harder and harder, especially if you want to go before C++11...
70,693,121
70,693,396
Why vector's insert() creates a copy of inserted element and assigns to the copy, not the inserted element?
Consider an insert(iterator position, const value_type &x) call: if no reallocation is happening (capacity != size), then in many implementations of the vector I saw this behavior: ... template<typename _Tp, typename _Alloc> void vector<_Tp, _Alloc>:: _M_insert_aux(iterator __position, const _Tp& __x) #endif { ... if (this->_M_impl._M_finish != this->_M_impl._M_end_of_storage) { this->_M_impl.construct(this->_M_impl._M_finish, _GLIBCXX_MOVE(*(this->_M_impl._M_finish - 1))); ++this->_M_impl._M_finish; #ifndef __GXX_EXPERIMENTAL_CXX0X__ _Tp __x_copy = __x; #endif _GLIBCXX_MOVE_BACKWARD3(__position.base(), this->_M_impl._M_finish - 2, this->_M_impl._M_finish - 1); #ifndef __GXX_EXPERIMENTAL_CXX0X__ *__position = __x_copy; ... Why not assign *__position to __x? Doesn't creating a copy result in additional waste of space? Couldn't one get away with avoiding creating the copy?
The __x_copy is only used if the __GXX_EXPERIMENTAL_CXX0X__ macro isn't set. This means it is only used in C++98 and C++03 mode. Nowadays you probably shouldn't be using these old modes without a reason. The macro name also indicates that you have an old copy of libstc++. It was replaced in 2012: https://gcc.gnu.org/git/?p=gcc.git;a=commit;h=734f50238f863ae90d2e8caa2323aaa02380ff48 Before moving elements of the container to free up the location at which the new element is supposed to be inserted, a copy of __x is made because it is possible that __x refers to an element of the container which may be relocated in this operation, invalidating the reference. At least that is what it looks like to me. If I remember correctly, it was, and still is, allowed to pass references to elements of the same container to its member functions if there are no specific preconditions stating otherwise, as long as these are lvalue references, not rvalue references.
70,693,786
70,693,801
Why is Universal reference being treated as R-Value reference?
#include <iostream> class A { public: A() {}; }; template <class T> class Test { public: void func1(T&& t) { } }; int main() { A a; Test<A> o1; o1.func1(a); return 0; } Following errors are seen on compilation error C2664: 'void Test<A>::func1(T &&)': cannot convert argument 1 from 'A' to 'T &&' note: You cannot bind an lvalue to an rvalue reference o1 is obtained by instantiating template class Test with "A". So the call o1.func1(a) should know that void func1(T&& t) should resolve to void func1(A&& t) I thought T&& in void func1(T&& t) should be deduced as a universal reference or a forwarding reference because its from a template type parameter. Then why in the error above it says "You cannot bind an lvalue to an rvalue reference"? Am i missing some template magic here?
I thought T&& in void func1(T&& t) should be deduced as a universal reference or a forwarding reference [...] No. t in your example is not a universal reference. To be a universal reference it must be deduced from the call, but in your example T is just A. This is a universal reference: template <class T> class Test { public: template <typename X> void func1(X&& t) { } }; The important detail is "deduced". In your example nothing is being deduced. Consider that Test<A> is equivalent to class TestA { public: void func1(A&& t) { } }; Once you instantiated the class template, its method func1 has argument of tpye A&&, not something else, ie there is nothing to be deduced anymore. Template argument deduction takes place when you do not explicitly state the template argument, as in template <typename T> void foo(T&& t) {}; foo(1);
70,693,916
70,694,339
Why is is showing error in rotating the strings of larger length?
my code #include<bits/stdc++.h> using namespace std; int main() { int n ; cin >> n; string s1 , s2 , s3; cin >> s1 >> s2; string s = s1 + s1; int count = 0; for (int i = 0 ; s3 != s2 ; i++) { // int a = s.find() s3 = s.substr( i , s1.length() ); count++; } cout << count - 1; return 0; } In this when I try to rotate the small sized string it is working fine but when I tried with some large length string it is showing error terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::substr: __pos (which is 227) > this->size() (which is 226) I'm not understanding what is happening as with the string length of 20 or 30 it is working fine but when then string length is over the 110 it is showing this type of error. Also this testcase is showing error 113 ndafmffmuuwjzqpquwjhuftohawpfegsjvnxwipwqlswvawogjuyiqtzsgpwgosegmuuhpzwchejuiitumyescxxyecnsatcbfpseqzowvdjyvchg zqpquwjhuftohawpfegsjvnxwipwqlswvawogjuyiqtzsgpwgosegmuuhpzwchejuiitumyescxxyecnsatcbfpseqzowvdjyvchgavqnonmkwgqp
This is quite simple your for loop has condition which is never false for this input. So you are increasing i beyond size of s (double of size of s1). Note common part of this two strings is: zqpquwjhuftohawpfegsjvnxwipwqlswvawogjuyiqtzsgpwgosegmuuhpzwchejuiitumyescxxyecnsatcbfpseqzowvdjyvchg. Difference is: s1 has in front: ndafmffmuuwj s2 has in backL: avqnonmkwgqp So s1 is not rotation of s2 that is why codition in for is never fasle. This is the reason std::basic_string::substr throws an exception. Live demo. Some fix. And here is better way to do it.
70,694,337
70,694,556
template function overloading ambiguity
A beginner's question here, so I have the following code foo.h enum class Fruit : uint16_t { Apple = 8019U, Orange = 8020U, Banana = 8021U, Cactus = 8022U }; class Foo { public: template<typename T> void SetValue(unsigned int location, const T& value); template<typename T> void SetValue(unsigned int location, const T* value_ptr); template<typename T> void SetValue(Fruit fruit, const T& value); template<typename T> void SetValue(Fruit fruit, const T* value_ptr); } foo.cpp template<typename T> void Foo::SetValue(unsigned int location, const T& value) { std::cout << value << std::endl; } template<typename T> void Foo::SetValue(unsigned int location, const T* value_ptr) { std::cout << (*value_ptr) << std::endl; } template<typename T> void Foo::SetValue(Fruit fruit, const T& value) { SetValue<T>(static_cast<unsigned int>(fruit), value); } template<typename T> void Foo::SetValue(Fruit fruit, const T* value_ptr) { SetValue<T>(static_cast<unsigned int>(fruit), value_ptr); } #define INSTANTIATE_TEMPLATE(T) \ template void Foo::SetValue<T>(unsigned int location, const T& value); \ template void Foo::SetValue<T>(unsigned int location, const T* value_ptr); \ template void Foo::SetValue<T>(Fruit fruit, const T& value); \ template void Foo::SetValue<T>(Fruit fruit, const T* value_ptr); INSTANTIATE_TEMPLATE(int) INSTANTIATE_TEMPLATE(uint) INSTANTIATE_TEMPLATE(bool) INSTANTIATE_TEMPLATE(float) INSTANTIATE_TEMPLATE(vec2) INSTANTIATE_TEMPLATE(vec3) INSTANTIATE_TEMPLATE(vec4) INSTANTIATE_TEMPLATE(mat2) INSTANTIATE_TEMPLATE(mat3) INSTANTIATE_TEMPLATE(mat4) ... #undef INSTANTIATE_TEMPLATE main.cpp int main() { Foo foo; float bar[7] { 0.0f, 0.15f, 0.3f, 0.45f, 0.6f, 0.75f, 0.9f }; float baz = 12.5f; foo.SetValue(Fruit::Orange, 1.05); // calling SetValue<double>(Fruit fruit, const double& value) foo.SetValue(Fruit::Apple, bar + 3); // calling SetValue<float*>(Fruit fruit, float *const& value) foo.SetValue(Fruit::Cactus, &baz); // calling SetValue<float*>(Fruit fruit, float *const& value) } In the last 2 calls, while I really intended to call SetValue<float>(Fruit fruit, const float* value_ptr) What actually gets called are SetValue<float*>(Fruit fruit, float *const& value) I'm aware that this is ambiguous because VS Intellisense was not able to color highlight SetValue<T> in the overridden function body, so I tried to write foo.SetValue<float>(Fruit::Cactus, &baz) instead, now the compiler interprets T as float rather than float*, but I wonder if this is a horrible design...... Is there a better approach that doesn't require me to explicitly specify the type of T? How can I eliminate the ambiguity completely?
I'm aware that this is ambiguous It is not. const T& value is a better match than const T* value for float*. The former is an exact match, whereas the later require a qualification conversion. You might drop the const for pointer: template<typename T> void SetValue(Fruit fruit, T* value_ptr); Demo
70,694,478
70,694,662
Same array giving garbage value at one place and an unrelated value at the other place
In the following code: #include<iostream> using namespace std; int main() { int A[5] = {10,20,30,40,50}; // Let us try to print A[5] which does NOT exist but still cout <<"First A[5] = "<< A[5] << endl<<endl; //Now let us print A[5] inside the for loop for(int i=0; i<=5; i++) { cout<<"Second A["<<i<<"]"<<" = "<<A[i]<<endl; } } Output: The first A[5] is giving different output (is it called garbage value?) and the second A[5] which is inside the for loop is giving different output (in this case, A[i] is giving the output as i). Can anyone explain me why? Also inside the for loop, if I declare a random variable like int sax = 100; then A[5] will take the value 100 and I don't have the slightest of clue why is this happening. I am on Windows, CodeBlocks, GNUGCC Compiler
Well you invoke Undefined Behaviour, so behaviour is err... undefined and anything can happen including what your show here. In common implementations, data past the end of array could be used by a different element, and only implementation details in the compiler could tell which one. Here your implementation has placed the next variable (i) just after the array, so A[5] is an (invalid) accessor for i. But please do not rely on that. Different compilers or different compilation options could give a different result. And as a compiler is free to assume that you code shall not invoke UB an optimizing compiler could just optimize out all of your code and only you would be to blame. TL/DR: Never, ever try to experiment UB: anything can happen from a consistent behaviour to an immediate crash passing by various inconsistent outputs. And what you see will not be reproduced in a different context (context here can even be just a different run of same code)
70,694,574
70,695,113
Checking reversed text on C++ (doesn't work with a -1 index?)
I was making a simple palindrome checker and can't understand why the iterator works with index 0, but won't work with index -1, you can see that both codes print the SAME text, but not the same boolean. Can anyone explain me what's the logic behind this? The only different part on both codes is this: for(int i=text.size();i>=-1;i--) Not Working for(int i=text.size()-1;i>=0;i--) Working WORKING: #include <iostream> // Define is_palindrome() here: std::string is_palindrome(std::string text){ std::string reverse= ""; for(int i=text.size()-1;i>=0;i--){ reverse += text[i]; } if(reverse == text){ return text + " IS palindrome (reverse text: " + reverse +")"; } else { return text + " NOT palindrome (reverse text: " + reverse + ")"; } } int main() { std::cout << is_palindrome("madam") << "\n"; std::cout << is_palindrome("ada") << "\n"; std::cout << is_palindrome("lovelace") << "\n"; } output madam IS palindrome (reverse text: madam) ada IS palindrome (reverse text: ada) lovelace NOT palindrome (reverse text: ecalevol) NOT WORKING #include <iostream> // Define is_palindrome() here: std::string is_palindrome(std::string text){ std::string reverse= ""; for(int i=text.size();i>=-1;i--){ reverse += text[i]; } if(reverse == text){ return text + " IS palindrome (reverse text: " + reverse +")"; } else { return text + " NOT palindrome (reverse text: " + reverse + ")"; } } int main() { std::cout << is_palindrome("madam") << "\n"; std::cout << is_palindrome("ada") << "\n"; std::cout << is_palindrome("lovelace") << "\n"; } output madam NOT palindrome (reverse text: madam) ada NOT palindrome (reverse text: ada) lovelace NOT palindrome (reverse text: ecalevol)
C++ uses 0-based indexing, ie valid indices of a N sized container are 0,1,2...N-1. If you try to use an index out of bounds your code invokes undefined behavior. Look at the output of this code: #include <iostream> #include <string> void foo(const std::string& text){ for(int i=text.size();i>=-1;i--){ std::cout << i << "\n"; } } int main() { foo("madam"); } It is 5 4 3 2 1 0 -1 Both -1 and 5 are not elements of the string, because it has only 5 characters. (For 5 I am allowing myself to simplify the matter a bit, because strings have some oddities for accessing the one past last character null terminator. As -1 definitely is out of bounds and with std::string you usually need not deal with the null terminator explicitly, this is ok for this answer). Now look at the output of this code: #include <iostream> #include <string> void foo(const std::string& text){ for(int i=text.size()-1;i>=0;i--){ std::cout << i << "\n"; } } int main() { foo("madam"); } It is 4 3 2 1 0 It iterates all characters of the input string. Thats why this is correct and the other is wrong. When your code has undefined behavior anything can happen. The results may appear to be correct or partially correct. Wrong code does not necessarily produce obviously wrong output. Note that for(int i=text.size()-1;i>=0;i--) is a problem when the size of the string is 0, because size() returns an unsigned which wraps around to result in a large positive number. You can avoid that by using iterators instead. There are reverse iterators that make a reverse loop look the same as a forward loop: #include <iostream> #include <string> int main() { std::string text("123"); for (auto i = text.rbegin(); i != text.rend(); ++i) std::cout << *i; } Output 321
70,694,600
70,705,984
How can I read lines from a text file into a variable
I know that there's many questions here about reading lines from a text file and storing it in a c++ struct. However, those questions all contain text files that have precisely the information they needed, such as a text file with : Tom 123 Jim 234 However, what if my text file had something like // The range of 'horizontal' indices, inclusive // E.g. if the range is 0-4, then the indices are 0, 1, 2, 3, 4 GridX_IdxRange=0-8 // The range of 'vertical' indices, inclusive // E.g. if the range is 0-3, then the indices are 0, 1, 2, 3 GridY_IdxRange=0-9 How would I be able to get just the numbers 0-8 and 0-9 besides the equal sign in gridX and gridY to be stored in my struct? What I tried: struct config { int gridRange[2]; int gridX; int gridY; int cityId; int cloudCover; int pressure; std::string cityName; }; config openFile(std::string filename, config &con) { std::fstream inputFile(filename.c_str(), std::fstream::in); if (inputFile.is_open()) { std::string line; for (int i = 0; i < 2; i++) { while (std::getline(inputFile, line)) { inputFile >> con.gridRange[i]; std::cout << con.gridRange[i]; //to show what is stored in the array } } //std::cout << range << std::endl; std::cout << std::endl; return con; } else { std::cout << "Unable to open file" << std::endl; } } Ignore the other variables in the struct as I still do not need them yet. The output I got was // The range of 'horizontal' indices, inclusive 0
I managed to solve this by adding in if (line[0] != '/' && !line.empty()) { inside the while loop and creating a new string variable called lineArray[5]. The function now looks like this config openFile(std::string filename, config &con) { std::fstream inputFile(filename.c_str(), std::fstream::in); if (inputFile.is_open()) { std::string line; std::string lineArray[5]; int count = 0; while (std::getline(inputFile, line)) { if (line[0] != '/' && !line.empty()) { lineArray[count] = line; count++; } } std::cout << "Printing out " << lineArray[0] << std::endl; std::cout << std::endl; return con; } else { std::cout << "Unable to open file" << std::endl; } } And the output I'll get is Printing out GridX_IdxRange=0-8.
70,694,660
70,694,762
How to obtain nanosecond file creation time in C++
In the process of software development, I encountered a requirement to obtain the time stamps of file creation time, modification time and access time. It is easy to obtain this information by calling struct stat related interfaces, but the requirement is to obtain nanosecond timestamps. So I don't know what to do, is there someone give me a solution? By the way, I use C++ programming under Linux.
Not all file systems support this (ext4 does): struct stat result; if (stat(filename, &result) == 0) { printf("Last access of %s: %sns: %ld\n", filename, ctime(&result.st_ctim.tv_sec), result.st_ctim.tv_nsec ); } else { fprintf(stderr, "%s: %s.\n", argv[0], strerror(errno)); }
70,694,672
70,694,754
C++ How to make a non void function return nothing for if else statements?
So my problem goes like this: string something (string something){ string letter; cout << "press a"; cin >> letter; if (letter==a){ return a; } else cout << "wrong letter"; //what should I put here if I don't want it to return any value? } Any alternatives would also be welcome
One way to handle this would be a std::optional<std::string> #include <optional> std::optional<std::string> dingas(std::string something) { string letter; cout << "press a"; cin >> letter; if (letter==something){ return "a"; } else { std::cout << "wrong letter"; return std::nullopt; } } [1] https://en.cppreference.com/w/cpp/utility/optional
70,695,086
70,697,779
How Do I Set Include Path Library Directory And Linker For VSCODE When I Have Visual C++ Build Tools To Work With (not g++)
I have set up VS code as my development environment and used MSVC build tools (cl.exe compiler) instead of g++. I tried to set up SFML for my environment. I want to know how do I set the SFML include path and library path. And also, How do I perform static Linking with cl.exe. Note: I am using only VS code and NOT Visual Studio for programming. Below are some files I've used. Tasks.json,Launch.json, C_cpp_properties.json. Tasks.json: { "tasks": [ { "type": "cppbuild", "label": "C/C++: cl.exe build active file", "command": "cl.exe", "args": [ "/Zi", "/EHsc", "/nologo", "/Fe:", "${workspaceFolder}\\bin\\${fileBasenameNoExtension}.exe", "${workspaceFolder}\\*.cpp" ], "options": { "cwd": "${workspaceFolder}" }, "problemMatcher": [ "$msCompile" ], "group": { "kind": "build", "isDefault": true }, "detail": "Task generated by Debugger." } ], "version": "2.0.0" } Launch.json: { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "cl.exe - Build and debug active file", "type": "cppvsdbg", "request": "launch", "program": "${workspaceFolder}\\bin\\${fileBasenameNoExtension}.exe", "args": [], "stopAtEntry": false, "cwd": "${workspaceFolder}", "environment": [], "console": "externalTerminal", "preLaunchTask": "C/C++: cl.exe build active file" } ] } c_cpp_properties.json { "configurations": [ { "name": "Win32", "includePath": [ "${default}" ], "defines": [ "_DEBUG", "UNICODE", "_UNICODE" ], "windowsSdkVersion": "10.0.19041.0", "compilerPath": "C:/Program Files (x86)/Microsoft Visual Studio/2022/BuildTools/VC/Tools/MSVC/14.30.30705/bin/Hostx64/x64/cl.exe", "cStandard": "c17", "cppStandard": "c++17", "intelliSenseMode": "windows-msvc-x64" } ], "version": 4 }
As mentioned in the comments, you need to use a C++ build system to manage dependencies and build your project. VSCode does not come with any built-in build systems like Visual Studio does. VSCode tasks allow you to specify a command line, which can then be invoked easily in the IDE. The task shown is just a "build active file" task, which is only really useful for trivial programs with no dependencies. It invokes cl.exe on the current source file (and passes a few other arguments). You can specify include directories and pass arguments to the linker by adding to the "args" array in the task, e.g.: "/I", "D:\\Code Libraries\\boost_1_77_0", "/link", "/LIBPATH:\"D:\\Code Libraries\\boost_1_77_0\\stage\\lib\"", which assumes that the boost headers and (statically built) libraries are at the specified locations. You could probably work out how to build an entire project by adding command lines with VSCode tasks, but it's probably easier to use a build system (even if that system is CMake).
70,695,121
70,695,181
how does getline() read a multiple-line file in loops?
I have some confusion about the use of std::getline function. see the following code: #include <sstream> #include <string> std::ifstream ifs(filename); std::string line; while (std::getline(ifs, line)) { //...// } for ( std::string s; getline(ifs, s)){ //...// } For both of the while loop and the for loop, it seems like each time in a new iteration, the "geline" is reading a new line, e.g. if we have a file storing: 1 2 3 4 5 6 then in the first iteration, getline reads 1 2 , then 3 4 in the next iteration... so, how does it know from which line it should start reading when an iteration starts?
A file stream is a source of bytes (“characters”). Each time you read a character from the file the file get pointer is advanced to the next character to read. That is, each time you read, you get the next unread character. std::getline() simply reads characters until it gets the delimiter value (which is '\n' by default). Hence each call to getline() gets the next line in the file.
70,695,178
70,695,590
Why do we need to downcast a variable even if the function will upcast it again right before returning?
While reading a book about modern C++, I have seen a code snippet that confused me. The code has been written to set up PWM (16 bit Timer) for 8 bit AVR microcontroller. The code is like that: class pwm_base : private util::noncopyable { public: typedef std::uint_fast16_t duty_type; pwm_base(const duty_type resol, const duty_type duty = 0U) : resolution(resol), counter (0U), duty_cycle(duty), shadow (duty) { } duty_type get_resolution() const { return resolution; } void set_duty(const duty_type duty) { // Set a new duty cycle in the shadow register. mcal::irq::disable_all(); shadow = static_cast<std::uint_fast8_t>((std::min)(duty, get_resolution())); // ???? (1) mcal::irq::enable_all(); } duty_type get_duty() const { // Retrieve the duty cycle. mcal::irq::disable_all(); const volatile std::uint_fast8_t the_duty = duty_cycle; // ???? (2) mcal::irq::enable_all(); return the_duty; } virtual void service() = 0; protected: const duty_type resolution; duty_type counter; duty_type duty_cycle; duty_type shadow; }; I have problems with lines indicated by ????. It is clearly seen that both, shadow and duty_cycle have been defined as uint_fast16_t. So, it means that they have to be at least 16 bits. If it is the case, why does the author downcast the result of min method to uint_fast8_t instead of casting to uint_fast16_t at line ???? (1) ? And also, why does at line ???? (2) he downcast again the variable to uint_fast8_t even if the function return type is uint_fast16_t? Are these downcastings required? What are their purposes?
This code seems severely over-engineered, which is always the biggest danger whenever you allow C++. The language tends to encourage making things needlessly complicated just for the heck of it, instead of utilizing the KISS principle. The hard requirements are: on the given hardware, the CPU works fastest with 8 bit types but the PWM register is 16 bits. Period. Therefore any variable describing period or duty cycle needs to be exactly 16 bits. It doesn't make sense to declare it as uint_fast16_t because the corresponding hardware registers will always be exactly 16 bits, no more, no less. In general the uint_fast types are only helpful if planning to port this to a 32 bit system somehow, but it is very unlikely that there will exist a 32 bit MCU with an identical PWM peripheral. Thus in this case uint_fast is just useless noise, because the code will never get ported. The cast to uint8_t supposedly truncates the 16 bit value to the 8 least significant bits. If so, the cast is incorrect, it should never be static_cast<std::uint_fast8_t> but static_cast<std::uint8_t>. I'm otherwise not quite following what the code is supposed to do, update the duty cycle somewhere, I would assume. Furthermore, disabling the interrupt mask as a re-entrancy protection feature probably doesn't make sense, as this can cause unexpected timing problems. If this class is to be used from inside an ISR then another protection mechanism might be more suitable, such as a semaphore or atomic access/inline asm. PWM in particular is picky with when/how you change the duty cycle, or you might get glitches. Overall, I would strongly recommend not to use C++ on an ancient, severely resource-confined 8 bit microcontroller. Or to use ancient 8 bit microcontrollers instead of ARM when learning embedded systems, 8-bitters are much harder to program in C (or C++) than 32-bitters.
70,695,190
70,695,250
If code changed to std::move(vector) will that save a copy operation in this function
The function is to extract the file contents into a vector as below: std::vector<uint8_t> GetFileContents(const std::string& filename) { std::ifstream file(filename, std::ios::binary); if (!file.good()) { return {}; } file.seekg(0, std::ios::end); std::streampos fileSize = file.tellg(); file.seekg(0, std::ios::beg); std::vector<uint8_t> fileData(fileSize); file.read((char*) &fileData[0], fileSize); return fileData; } On the lines: std::vector<uint8_t> fileData(fileSize); file.read((char*) &fileData[0], fileSize); return fileData; The fileData vector is copied into a temporary vector to be returned here? Do I need to change to: std::vector<uint8_t> fileData(fileSize); file.read((char*) &fileData[0], fileSize); return std::move(fileData); to do a move and save a vector copy operation? Any other changes required in the function to support move? Is there any value in std::move({}) for the empty case?
No, you shouldn't use std::move there. That avoids possible NRVO, and there is an implicit move anyway. See Automatic_move_from_local_variables_and_parameters for further detail.
70,695,389
70,695,489
Returning anonymous struct from template function (for structured binding)
I wanted to use new C++17 features and wanted to use a structured binding to return multiple values from a (template) function. I can get it to work, but I want it to work better. A simplified version of the code is (the real code is larger and have better variable names): template <class O> struct { int a; double b; } F(int i,O o) { return {i, o(i)}; } void foo(int i) { auto [a,b]=F(i, [=](int k)->double {return 1.0/k; /*...*/}); // ... }; The combination of anonymous struct and template function didn't work in VS 2019, so I had to write: struct Dummy { int a; double b; }; template <class O> Dummy F(int i,O o) { return {i, o(i)}; } void foo(int i) { auto [a,b]=F(i, [=](int k)->double {return 1.0/k; /*...*/}); // ... }; or: template <class O> std::tuple<int,double> F(int i,O o) { return {i, o(i)}; } void foo(int i) { auto [a,b]=F(i, [=](int k)->double {return 1.0/k; /*...*/}); // ... }; Preference: I don't need the return-type struct, and thus I prefer the anonymous variant, and I know that it works for non-template functions. I want the member-names in the struct for documentation purposes, and thus I find the tuple-variant less clear. (This an especially an issue with more members of the same type.) So, what is the best way to handle this also for template functions? The error messages were: error C2143: syntax error: missing ';' before 'identifier' error C2332: 'struct': missing tag name error C3306: '': > unnamed class template is not allowed
How about local struct: template <class O> auto F(int i, O o) { struct { int a; double b; } res {i, o(i)}; return res; } void foo(int i) { auto [a,b] = F(i, [=](int k)->double {return 1.0/k; /*...*/}); // ... }; Demo
70,695,554
70,695,589
Difference between -= and =- in C++ and C?
I often confuse both "-=" and "=-", like what is the exact difference between them? int main() { int x=10, a=-3; x=-a; printf("%d",x); return 0; } Output 3
-= is a compound assignment operator. =- is two operators applied seperately. While a =- 3; is the same as a = (-3); This x -= a; is more or less equivalent to x = x - a; "More or less" because operators can be overloaded (in C++) and typically the compound operator avoids the temporary right hand side. Btw you are using =- twice in your code while the questions asks for += vs =+. += is a compound operator as well.
70,695,969
70,696,112
Why is pair not working with unordered_map?
The following code doesn't compile. The line with pair is giving the error. Is there some other way to access the data or is this way correct?? unordered_map<int,int> hm; unordered_map<int,int>::iterator it; it=find(hm.begin(),hm.end(),x+c); if (it!=hm.end()) { bNotFound = false; pair<int,int> p = *it; ind = p.second; }
Sometimes the compiler does a lousy job with the error messages. Your problem is the find algorithm. unordered_map & map have their own find, which take the key as argument and returns an iterator. The algorithm is looking for the key: auto it = hm.find(key); if (it != hm.end()) { // ... } The global find algorithm takes a search interval and a value as input. But it works with any container that meets some iterators constrains. In the case of a map the value is not the key, as in the unordered_map::find but the (key, value) pair. The algorithm is looking for the (key, value) pair. You can declare your target value and use it like this: unordered_map<int, int>::value_type target{ key, value }; auto it = find(hm.begin(), hm.end(), target); if (it != hm.end()) { // ... }
70,696,083
70,696,399
For reversing a number in C++ which ends with zeros
I want to write a program for reversing a number. For reversing a number like 2300 to 32 so that the ending zeros are not printed, I found this method: #include<iostream> using namespace std; int main() { int l; cin>>l; bool leading = true; while (l>0) { if ((l%10==0)&& (leading==true)) { l /= 10; leading = false; // prints 032 as output continue; } // leading = false; this prints correct 32 cout<<l%10; l /= 10; } return 0; } The instruction of assigning boolean leading false inside the if statement is not giving a valid answer, but I suppose assigning it false should give 32 as output whether we give it outside or inside if statement as its purpose is just to make it false once you get the last digit to be a non zero. Please tell the reason of difference in outputs.
The reason for the difference in output is because when you make leading = false inside the if statement, you are making it false right after encountering the first zero. When you encounter the remaining zeroes, leading will be false and you will be printing it. When you make leading = false outside the if statement, you are basically waiting till you encounter all zeroes before making it false. If you are looking to reverse a number, this is the well known logic to do so: int reverse(int n) { int r; //remainder int rev = 0; //reversed number while(n != 0) { r = n%10; rev = rev*10 + r; n /= 10; } return rev; } EDIT: The above code snippet is fine if you just want to understand the logic to reverse a number. But if you want to implement the logic anywhere you have to make sure you handle integer overflow problems (the reversed number could be too big to be stored in an integer!!). The following code will take care of integer overflow: int reverse(int n) { int r; //remainder int rev = 0; //reversed number while(n != 0) { r = n%10; if(INT_MAX/10 < rev) { cout << "Reversed number too big for an int."; break; } else if(INT_MAX-r < rev*10) { cout << "Reversed number too big for an int."; break; } rev = rev*10 + r; n /= 10; } if(n != 0) { //could not reverse number //take appropriate action } return rev; }
70,696,092
70,728,366
C++ Store an expression template inside a class whose objects will be part of a vector
[Extensively edited for clarity and typos, and now with attempted solution, old version at the end] New version of the question I have a class which needs to store a functor. The problem is that the functor is an expression template (meaning that each functor is of different type). On top of that I need to collect all the objects of that class in a vector. Below my attempts: I do not write the code for the functors as expression templates as it is too long. I will therefore test the code by trying to store two functors of two different classes struct FunctorTypeA { double a; FunctorTypeA(const double ap): a(ap) {} double operator()(const double x){ return a;} }; struct FunctorTypeB { double a, b; FunctorTypeB(const double ap, const double bp): a(ap), b(bp) {} double operator()(const double x){ return a+b*x;} }; I think, correct me if I am wrong, that if the code below works for the two functors above, it should work for any functor constructed with expression templates. The first idea would be template <typename functorType> struct myClass { functorType functor; myClass(functorType funct): functor(funct){} }; I can store a functor inside an object of that class with: FunctorTypeA functor1(1.2); FunctorTypeB functor2(1.5, 5.0); myClass myObj1(functor1); myClass myObj2(functor2); cout << myObj1.functor(0.2) << " " << myObj1.functor(0.2) << "\n\n"; However I cannot store those objects in an std::vector as they have different types. Therefore I tried: struct myClass2Base { virtual ~TrialClassBase() = default; virtual double functor(const double x) = 0; }; template <typename functorType> struct myClass2 : public myClass2Base { functorType functorStored; myClass2(functorType funct): functorStored(funct){} double functor(const double x){return functorStored(x);} }; and I can construct a vector of those objects as std::vector<myClass2Base*> vecOfObj; vecOfObj.push_back(new myClass2(functor1)); cout << vecOfObj[0]->functor(0.3) << "\n\n"; This one works. Is there a better solution? Thanks! Old version of the question I have a class which needs to store a functor which is an expression template (meaning that each function is of different type). I also need to put the objects of that class in an std::vector. My Attempt is struct TrialClassBase{ virtual double get_functor(double) = 0; }; template <typename derived> struct TrialClass : public TrialClassBase { derived functor; TrialClass(derived fun): functor(fun){} double get_functor(double x) {return functor(x);} }; std::vector<shared_ptr<TrialClassBase>> vecOfObjs; Then I try to add an object to the vector. As an example I use an std::function, only as an example: the functor in my case will be an expression template. std::function<double(double)> funcccc = [](double x){return x*x;}; vecc.emplace_back(TrialClass(funcccc)); cout << vecc[0]->get_functor(0.3) <<"\n\n"; This fails to compile. What mistake am I making? How can I do what I want to do? Thanks!
I see you have improved your question. Yes there are debatably better solutions. One nice solution the std lib offers you, is to use type-erasure using std:function. #include <vector> #include <functional> #include <iostream> #include <cmath> struct FunctorTypeA { double a; FunctorTypeA(const double ap): a(ap) {} auto operator()([[maybe_unused]]const double x) const { return a;} }; int main(){ auto funcVec{std::vector<std::function<double(double)>>{}}; funcVec.push_back(FunctorTypeA{3.14}); // functor allowed funcVec.push_back([](double x){return x;}); // lambda allowed funcVec.push_back(sqrt); // function pointer allowed, e.g. C math function for(auto&& f:funcVec){ std::cout << f(2.0) << '\n'; } } This way you don't complicate things with inheritance and pointer casting. Easy to make mistakes there. std::vector and std::function will do all the cleaning up. (That was something you can easily miss in your vector-of-pointers solution) Note: std::function may perform a dynamic allocation. But so does std::vector and inheritance has vtable overhead.
70,696,149
70,696,541
Comparator for matching point in a range
I need to create a std::set of ranges for finding matching points in these ranges. Each range is defined as follows: struct Range { uint32_t start; uint32_t end; uint32_t pr; }; In this structure start/end pair identify each range. pr identifies the priority of that range. It means if a single point falls into 2 different ranges, I like to return range with smaller pr. I like to create a std::set with a transparent comparator to match points like this: struct RangeComparator { bool operator()(const Range& l, const Range& r) const { if (l.end < r.start) return true; if (l.end < r.end && l.pr >= r.pr) return true; return false; } bool operator()(const Range& l, uint32_t p) const { if (p < l.start) return true; return false; } bool operator()(uint32_t p, const Range& r) const { if (p < r.start) return true; return false; } using is_transparent = int; }; std::set<Range, RangeComparator> ranges; ranges.emplace(100,250,1); ranges.emplace(200,350,2); auto v1 = ranges.find(110); // <-- return range 1 auto v2 = ranges.find(210); // <-- return range 1 because pr range 1 is less auto v3 = ranges.find(260); // <-- return range 2 I know my comparators are wrong. I wonder how I can write these 3 comparators to answer these queries correctly? Is it possible at all?
find returns an element that compares equivalent to the argument. Equivalent means that it compares neither larger nor smaller in the strict weak ordering provided to the std::set. Therefore, to make your use case work, you want all points in a range to compare equivalent to the range. If two ranges overlap, then the points shared by the two ranges need to compare equivalent to both ranges. The priority doesn't matter for this, since the equivalence should presumably hold if only one of the ranges is present. However, one of the defining properties of a strict weak ordering is that the property of comparing equivalent is transitive. Therefore in this ordering the two ranges must then also compare equal in order to satisfy the requirements of std::set. Therefore, as long as the possible ranges are not completely separated, the only valid strict weak ordering is the one that compares all ranges and points equivalent. This is however not an order that would give you what you want. This analysis holds for all standard library associative containers, since they have the same requirements on the ordering.
70,696,610
70,696,844
Is there an easier way to get the current time in hh:mm:ss format?
I tried to print the current time in the usual format of hh:mm:ss however I get the full date format instead. I need the answer to be in string or int, so it is easier to deal with. I was thinking of adding it to a log file so that I can make it easier to track my program. #include <iostream> #include <chrono> #include <ctime> int main() { auto curr_time = std::chrono::system_clock::now(); std::time_t pcurr_time = std::chrono::system_clock::to_time_t(curr_time); std::cout << "current time" << std::ctime(&pcurr_time)<<"\n"; } I do want a little tip to help me do so.
The following example displays the time in the "HH:MM:SS" format (requires at least c++11 - tested with clang): #include <iostream> #include <iomanip> #include <chrono> #include <ctime> int main() { std::time_t t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); std::tm ltime; localtime_r(&t, &ltime); std::cout << std::put_time(&ltime, "%H:%M:%S") << std::endl; } Compiling and running: $ clang++ -std=c++11 so.cpp $ ./a.out 13:44:23 $
70,696,879
70,697,114
Visual Studio 2019/C++ bug?
I'm using native C++ with Visual Studio 2019 16.11.8. I don't understand this: whis can the false keyword be used as NULL (or nullptr)? Below the test code: bool test(bool* pb) { if (NULL != pb) return *pb; else return false; } void main() { test(false); // compiles (not what I was expecting) test(true); // won't compile: error C2664: 'test' : cannot convert parameter 1 from 'bool' to 'bool *' } I have tried online compilers tool, and they do not accept the test(false); line, which sounds to me what the normal behavior should be. In addition, this behavior can cause issues with overloaded methods. i.e., you have a test(bool* pb) method and an overloaded version with a pointer: test(int* pv) bool test(bool* pb) { if (NULL != pb) return *pb; else return false; } bool test(int* pb) { if (NULL != pb) return true; else return false; } void main() { test(false); // won't compile anymore: error C2668: 'test' : ambiguous call to overloaded function test(true); // won't compile: error C2664: 'test' : cannot convert parameter 1 from 'bool' to 'bool *' } BTW I'm also using VS2012, which has the same behavior with the same test codes.
MSVC treats the expression false as a null pointer constant. A null pointer constant can be implicitly converted to any pointer type, resulting in a null pointer value. The correct behavior according to the standard is to treat only integer literals with value 0 as null pointer constants. Although it has value 0, false is not an integer literal. However this rule is only in place since resolution of CWG issue 903. Before that every integral constant expression with value 0 was a null pointer constant. MSVC is not implementing the defect report with default flags and still follows this old rule, according to which the expression false is a null pointer constant. If you give MSVC the flag /permissive- to make it behave more standard-conform and implement the new rule. With /std:c++20 or higher this is also set by default, if I am not mistaken. Note however, that you still have this problem if you use a literal 0 in your code and yes, it can affect overload resolution. Values other than 0, even if an integer literal, are never null pointer constants and therefore cannot be converted to pointers implicitly. This also applies to true which has value 1. Therefore overload resolution may be affected by the specific value passed as argument. Null pointer constants are what makes NULL work to initialize and compare null pointers, by having NULL expand either to an integer literal with value 0 or to nullptr. The latter is, since C++11, an alternative null pointer constant.
70,697,017
70,697,142
Is there a way to declare a class and then define it later in c++?
So i want to declare a function func(temp t1, temp t2) and use it in class temp. But i do not want to define it as a member function of the class temp mainly because i want other functions to be able to access func without using any object of temp. I know it is possible by declaring func() as a friend to temp but is there a way to declare a sort of prototype for temp so that I can use it as arguments for a non member function temp and then define it later? template<typename Type> class record { public: Type data; /*....some other memebers...*/ friend int rec_comp(const record& r1, const record& r2) { } bool operator==(const record& r1, const record& r2) { if(rec_comp(r1, r2)==0) return true; else return false; } /*...similar implementation for other relational operators ...*/ }; i want to declare the function rec_comp outside the class.
Yes it is possible. One example is given below: func.h #pragma once //declaration for class temp class Temp; //declaration for function func void func(Temp t1, Temp t2); func.cpp #include "func.h" #include "temp.h" #include<iostream> //implementation for function func void func(Temp t1, Temp t2) { std::cout<<"func called"<<std::endl; //do something with t2 and t2 } temp.h #pragma once //class definition class Temp { int i = 0; public: //default constructor Temp();//this is a declaration }; temp.cpp #include "temp.h" #include <iostream> //definition for default constructor Temp::Temp() { std::cout<<"default constructor called"<<std::endl; } main.cpp #include <iostream> #include "func.h" #include "temp.h" int main() { Temp t1, t2; //call func func(t1,t2); return 0; } The output of the above program can be seen here. Edit Since you have edited your question, below is the answer to your edited question. template<typename Type> class record { public: Type data; //NOTE: rec_comp is NOT A MEMBER FUNCTION template<typename U, typename V> friend int rec_comp(const record<U>& r1, const record<V>& r2); //THIS IS A DECLARATION }; //THIS IS A DEFINITION template<typename U, typename V> int rec_comp(const record<U>& r1, const record<V>& r2) { return 5; }
70,697,368
70,722,337
How to let a thread wait itself out without using Sleep()?
I want the while loop in the thread to run , wait a second, then run again, so on and so on., but this don't seem to work, how would I fix it? main(){ bool flag = true; pthread = CreateThread(NULL, 0, ThreadFun, this, 0, &ThreadIP); } ThreadFun(){ while(flag == true) WaitForSingleObject(pthread,1000); }
While the other answer is a possible way to do it, my answer will mostly answer from a different angle trying to see what could be wrong with your code... Well, if you don't care to wait up to one second when flag is set to false and you want a delay of at least 1000 ms, then a loop with Sleep could work but you need an atomic variable (for ex. std::atomic) or function (for ex. InterlockedCompareExchange) or a MemoryBarrier or some other mean of synchronisation to check the flag. Without proper synchronisation, there is no guarantee that the compiler would read the value from memory and not the cache or a register. Also using Sleep or similar function from a UI thread would also be suspicious. For a console application, you could wait some time in the main thread if the purpose of you application is really to works for a given duration. But usually, you probably want to wait until processing is completed. In most cases, you should usually wait that threads you have started have completed. Another problem with Sleep function is that the thread always has to wake up every few seconds even if there is nothing to do. This can be bad if you want to optimize battery usage. However, on the other hand having a relatively long timeout on function that wait on some signal (handle) might make your code a bit more robust against missed wakeup if your code has some bugs in it. You also need a delay in some cases where you don't really have anything to wait on but you need to pull some data at regular interval. A large timeout could also be useful as a kind of watch dog timer. For example, if you expect to have something to do and receive nothing for an extended period, you could somehow report a warning so that user could check if something is not working properly. I highly recommand you to read a book on multithreading like Concurrency in Action before writing multithread code code. Without proper understanding of multithreading, it is almost 100% certain that anyone code is bugged. You need to properly understand the C++ memory model (https://en.cppreference.com/w/cpp/language/memory_model) to write correct code. A thread waiting on itself make no sense. When you wait a thread, you are waiting that it has terminated and obviously if it has terminated, then it cannot be executing your code. You main thread should wait for the background thread to terminate. I also usually recommand to use C++ threading function over the API as they: Make your code portable to other system. Are usually higher level construct (std::async, std::future, std::condition_variable...) than corresponding Win32 API code.
70,697,517
70,697,728
c++ libcurl get request is returning 0 but still printing in the console
I've installed libcurl on ubuntu 20.4 and I've been playing around with it. I decidedly wanted to create a program that would write a file from the internet. So I wrote this. #include <iostream> #include <string> #include <curl/curl.h> #include <fstream> #include <unistd.h> int main() { std::ofstream htmlFile("index.html"); auto curl = curl_easy_init(); if(curl) { curl_easy_setopt(curl, CURLOPT_URL, "http://localhost/"); curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L); htmlFile <<curl_easy_perform(curl); htmlFile.close(); } return 0; } When I run this file I'm given my apache webserver html code through the console. But when looking at the file I want to write to there's just a zero. I'm stumped, I've seen so many different ways to do this. I find it strange that the html is logged to the console, but all it does is return 0.
curl_easy_perform returns a CURLcode. where "CURLE_OK (0) means everything was ok". That's what is written to your file. If you want to capture the text inside the program, you need to set a callback function with CURLOPT_WRITEFUNCTION and also provide somewhere to store the data via CURLOPT_WRITEDATA Example: #include <curl/curl.h> #include <fstream> #include <string> size_t write_callback(char* ptr, size_t size, size_t nmemb, void* userdata) { std::string& data = *static_cast<std::string*>(userdata); size_t len = size * nmemb; // append to the string: data.append(ptr, len); return len; } int main() { auto curl = curl_easy_init(); if(curl) { std::string data; // we'll store the data in a string curl_easy_setopt(curl, CURLOPT_URL, "http://localhost/"); curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L); // provide a pointer to where you'd like to store the data: curl_easy_setopt(curl, CURLOPT_WRITEDATA, &data); // provide a callback function: curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback); if(curl_easy_perform(curl) == CURLE_OK) { std::ofstream htmlFile("index.html"); if(htmlFile) htmlFile << data; // all's well, store the data in the file. } curl_easy_cleanup(curl); } }
70,698,268
70,730,409
constexpr position in variable declaration
Usually I like to put "const" behind the type, as int const foo1 = 123; Now, if i want to declare a second variable (which should even be constexpr) I would like to use the same style: int constexpr foo2 = 123; However, this led to a warning upon running a code analysis tool (however, all compilers I tried accept it). Does the C++ standard mandate that constexpr can only be used before the actual type?
constexpr is a decl-specifier, as are int and const. Other decl-specifiers are for example thread_local, mutable, extern, virtual, extern, friend, typedef, consteval, constinit and inline, as well as other type-specifiers such as volatile, long, double, auto, signed, decltype(...), names of types, types introduced by class, enum, union, struct, etc. A sequence of decl-specifiers makes up the decl-specifier-seq of a declaration. Following the decl-specifier-seq is typically a list of declarators, separated by commas, which declare the entities with the given decl-specifiers. (But for example the * in int* s; is part of the declarator, not the specifier sequence.) I don't think there is any instance in the standard where the order of the decl-specifier-seq has any relevance. For example the following compiles without issue and should have the same meaning as in the conventional order of specifiers: struct { double volatile mutable long x = 1; } typedef const S; inline S thread_local constexpr *s = {}; See the post-C++20 draft of the C++ standard, section [dcl.spec]. It specifies the grammar of the decl-specifier-seq and the individual specifiers. In the rest of the section certain combinations of specifiers are forbidden, but their order is not mentioned. So int constexpr x; and constexpr int x; are equivalent. But what is not possible is e.g. int* constexpr x; The constexpr would here be part of the declarator. It could be written as int constexpr* x; though. I suppose that makes putting constexpr as a rule after the type specifier confusing. It is the same rule as for const, but constexpr should only ever apply to the whole declaration, not to the type or a subtype. I think it is likely that the code analysis tool is simply complaining about the style rather than the functionality of the syntax. It is unusual to place constexpr behind the type specifiers, as it is unusual to put e.g. const between the two long in long long, and if the specifiers are in uncommon order it may become hard to read the code.
70,698,367
70,701,420
Is it possible to expand GCC/Clang compile and link options that start with "-f"?
I write C/C++ with GCC/Clang, but know little about compiler options that starts with "-f". For example, to turn on Address Sanitizer, I pass "-fno-omit-frame-pointer -fsanitize=address" to the compiler. This should both affect compile and link stages. Another example, to turn on OpenMP, I pass "-fopenmp" to the compiler, which gives support of compile and link to shared openmp library. If I use static openmp library, I should pass "-fopenmp" to the compiler, and pass "-fopenmp -static" to the linker. And this StackOverFlow answer says it means "-lgomp -lrt". My question: is there any method to expand the "-f" started compile/options, thus I can know what exactly libraries this "-f" flag links to?
Let's check the docs of clang at https://clang.llvm.org/docs/ClangCommandLineReference.html --verbose or -v looks very promising. A quick check at compiler-explorer.com gives promising results. GCC has a similar page with all options: https://gcc.gnu.org/onlinedocs/gcc/Option-Summary.html Here we have -v as well, though as it prints stuff to stderr, I can't verify the output at compiler-explorer.
70,698,391
70,700,081
How to correctly loading shp file by code
I am trying to load a .shp file by OGRFeatureSource class, and it is not showing in the scene, but when I load .earth file, using osgearth_viewer by arguments, the shape file works. Any errors are printing on terminal. I based my code on tutorials that i found on web, but i think these are for an old version (some classes of these tutorials no longer work.) The program is not crashing. Here is my code: osg::Node* node = osgEarth::Contrib::MapNodeHelper().load(arguments, &viewer); if (node) { osgEarth::Contrib::MapNode* mapNode = osgEarth::Contrib::MapNode::findMapNode(node); std::string shpFile = "/usr/local/muse/airtraficcontrol/ATC/airtrafficcontrol/data/osg_earth/world.shp"; osgEarth::OGRFeatureSource* featureSrc = new osgEarth::OGRFeatureSource(); featureSrc->setName("teste"); featureSrc->setURL( shpFile ); osgEarth::Contrib::Style earthStyle; osgEarth::LineSymbol* ls = earthStyle.getOrCreateSymbol<osgEarth::LineSymbol>(); ls->stroke()->color() = {1, 1, 0.3, 1}; ls->stroke()->width() = 1; ls->tessellationSize()->set(100, osgEarth::Contrib::Units::KILOMETERS); ls->stroke()->widthUnits() = osgEarth::Units::METERS; ls->stroke()->smooth() = true; earthStyle.getOrCreateSymbol<osgEarth::RenderSymbol>()->depthOffset()->enabled() = true; osgEarth::AltitudeSymbol* alt = earthStyle.getOrCreate<osgEarth::AltitudeSymbol>(); alt->technique() = alt->TECHNIQUE_DRAPE; osgEarth::FeatureDisplayLayout layout; layout.tileSize() = 650; osgEarth::FeatureModelLayer* fml = new osgEarth::FeatureModelLayer(); fml->setName( "layerName" ); fml->setFeatureSource( featureSrc ); fml->options().layout() = layout; fml->setStyleSheet( new osgEarth::StyleSheet() ); fml->getStyleSheet()->addStyle( earthStyle ); mapNode->getMap()->addLayer( fml ); viewer.setSceneData(node); } earth file: <!-- flat --> <options> <profile>plate-carre</profile> </options> <!-- <image driver="gdal"> <url>./world.tif</url> </image>--> <!-- <GDALImage name="world"> <url>./world.tif</url> </GDALImage>--> <!-- <FeatureModel name="world_boundaries" features="world-data"> <styles> <style type="text/css"> world { stroke: #ffffed; stroke-width: 4px; altitude-clamping: terrain-drape; } </style> </styles> </FeatureModel> --> <terrainshader> <code> <![CDATA[ #version 330 #pragma vp_entryPoint colorize void colorize(inout vec4 color) { color.rgb = vec3(0.192156, 0.20392, 0.22352); } ]]> </code> </terrainshader> <Viewpoints home="0" time="0"> <viewpoint> <!-- <heading>15.2667</heading> --> <pitch>-90</pitch> <range>5583.51m</range> <lat>45.504275</lat> <long>12.339304</long> <height>34720.802966509946</height> <srs>+proj=longlat +datum=WGS84 +no_defs </srs> </viewpoint> </Viewpoints> <!-- <DebugImage/> --> <!-- <OGRFeatures name="world-data"> <url>./world.shp</url> <url>/usr/local/muse/airtraficcontrol/ATC/airtrafficcontrol/data/osg_earth/world.shp</url> </OGRFeatures>--> </map>
Your AltitudeSymbol also needs to specify the clamping: alt->clamping() = alt->CLAMP_TO_TERRAIN;
70,698,635
71,745,745
QRect of full Virtual Desktop on Qt6
How to get QRect of a full Virtual Desktop? For example, for putting a window on a whole Virtual Desktop (multimonitor system). The obsolete Qt5 function is: QApplication::desktop()->geometry()
Something like this: QRect desktopRect() { QRegion virtualGeometry; for (auto screen : QGuiApplication::screens()) { virtualGeometry += screen->geometry(); } return virtualGeometry.boundingRect(); }
70,698,656
70,698,708
In struct nested union/array member default initialization compiles, but is not happening correctly?
I am trying to initialize array members at struct declaration in the following struct with nested union & array: struct Nested { union { short sArray[5] = {42}; float fVal; // Must NOT be initialized - obviously, only 1 member of a union can be }; double dArray[5] = {77.7}; }; While the code compiles just fine, only first elements of both arrays are initialized, when running/debugging the code.. sArray[0] is set to 42, remaining elements are all set to 0 dArray[0] is set to 77.69999, remaining are all set to 0 All other answers I found, mention initialization at instance declaration, but not default init in struct/class declaration. I have not seen/found whether this syntax is enabled (for array members too) by gnu c++17. However, since it compiles WO warning one would assume it should correct. Am I doing something wrong ? Edit: Or how do I simply initialize my arrays ?
What you are doing is aggregate initialization, which means the elements in sArray and dArray are value initialized when not specified. Because short and double are scalar types, this means zero initialization Since you don't specify anything but the first element, all remaining elements will be initialized to 0 As requested in the comments, a way to initialize the arrays would be std::fill or std::fill_n: #include <algorithm> struct Nested { explicit Nested() { std::fill_n(sArray, 5, 0); std::fill_n(dArray, 5, 0.0); } union { short sArray[5]; float fVal; // Must NOT be initialized - obviously, only 1 member of a // union can be }; double dArray[5]; }; In general, I would recommend to instead use std::array and its fill function: #include <array> struct Nested { explicit Nested() { sArray.fill(0); dArray.fill(0.0); } union { std::array<short, 5> sArray; float fVal; // Must NOT be initialized - obviously, only 1 member of a // union can be }; std::array<double, 5> dArray; };
70,698,805
70,698,847
Why is this code running without vector header file?
I couldn't find out why is the code below working fine on my local system without including the vector header file but not on online judges or online compilers. #include<iostream> #include<algorithm> using namespace std; int main(){ vector<int> v(10); for(int i = 0; i<10; i++) v[i] = i; sort(v.begin(),v.end()); for(int i = 0; i<10; i++) cout<<v[i]<<" "; return 0; } I am compiling the code by enabling the warning flags as g++ -Wall -Wextra ./ex.cpp but g++ doesn't give me any warnings at all. Removing the #include<algorithm> does give me the error I wanted, identifier "vector" is undefined, but I don't know what's the relationship between them.
Your algorithm header itself includes the vector header (either directly or indirectly). Because of this, the code after the preprocessor looks the same as if you had included the vector header yourself. You should not rely on this behavior though, as it depends on the standard library implementation you are using and can change at any time.
70,698,842
70,699,109
concept to check existence of function in class (problem in GCC?)
I would like to detect if a function (operator() in my case) is present in a class, regardless of its signature or whether it would be possible to get a pointer to it (may be impossible without additional info because it is templated or overloaded). The following code using a concept compiles on MSVC and clang, but not GCC (see godbolt link below for error messages). Is this supposed to work and is GCC not conformant, or is this not supposed to work and are MSVC and clang too lenient? It is interesting to note GCC fails not only for the overloaded and templated operator()s, but also for the simple functor. Note also that while the example code uses variations on unary functions taking an int, I'd like the concept to work regardless of function signature (and its does for MSVC and clang). Try here for GCC, clang and MSVC. Context is making this work, it does now on MSVC and clang, but not GCC. template <typename C> concept HasCallOperator = requires(C t) { t.operator(); }; struct functor { int operator()(int in_) { return 1; } }; struct functorOverloaded { int operator()(const int& in_) { return 1; } int operator()(int&& in_) { return 1; } }; struct functorTemplated { template <typename... T> int operator()(const T&... in_) { return 1; } }; template<HasCallOperator T> struct B {}; int main() { B<functor> a; B<functorOverloaded> b; B<functorTemplated> c; }
First, the way to check a concept is just to static_assert (not to try to instantiate a constrained class template). static_assert(HasCallOperator<functor>); static_assert(HasCallOperator<functorOverloaded>); static_assert(HasCallOperator<functorTemplated>); Second, you can't write t.operator() for the same reason that you can't write f.fun for any other non-static member function: if you do class member access, it must end with invocation. So this is simply a clang/msvc bug that it allows any of this. And then &C::operator() will not work if the call operator is overloaded or a function template (or both). Which really calls into question the whole point of this, since without reflection we're highly limited in the kinds of answers we can give to these questions. You can really only address the simple case of non-overloaded, non-template call operator. Nevertheless, there is an approach that works here. The trick is the same problem we have in our present case: &C::operator() doesn't work if operator() is overloaded. So what we do instead is construct a case where &C::operator() would be overloaded if there were one, and invert the check. That is: #include <type_traits> struct Fake { void operator()(); }; template <typename T> struct Tester : T, Fake { }; template <typename C> concept HasCallOperator = std::is_class_v<C> and not requires(Tester<C> t) { &Tester<C>::operator(); }; HasCallOperator<C> doesn't check C, it checks a type that inherits from both C and a type that has a non-overloaded non-template call operator. If &Tester<C>::operator() is a valid expression, that means it refer to &Fake::operator(), which means that C did not have one. If C had a call operator (whether it's overloaded or a template or both or neither), then &Tester<C>::operator() would be ambiguous. The is_class_v check is there to ensure that stuff like HasCallOperator<int> is false rather than ill-formed. Note that this won't work on final classes.
70,698,852
70,963,934
Unable to delete file with _wremove API (permission issue)
I'm unable to delete a temporary file from my C++ application, it's failing with "permission denied" error. Here's the code snippet, void DeleteTempFile(const std::wstring& path) { wchar_t* wc = const_cast<wchar_t*>( path.c_str() ); if( _wremove( wc ) != 0 ) Log(fatal, std::string("Error: ") + std::strerror(errno) + std::string(" while deleting file: ") + std::string(path.begin(),path.end())); else Log(fatal, std::string("Successfully deleted file: ") + std::string(path.begin(),path.end())); } And this is the log I'm getting when I execute this code, Error: Permission denied while deleting file: C:/Windows/SERVIC~1/LOCALS~1/AppData/Local/Temp/abcD12E.pdf Can somebody please help me in resolving this permission issue?
From Microsoft docs: remove, _wremove [...] Return Value Each of these functions returns 0 if the file is successfully deleted. Otherwise, it returns -1 and sets errno either to EACCES to indicate that the path specifies a read-only file, specifies a directory, or the file is open, or to ENOENT to indicate that the filename or path was not found. The call to _wremove is returning EACCES since Permission denied is printed (check errno constants). So there are 3 options: Your file is open (You need to close the file in the first place before calling _wremove). Your path is a directory name. The file is read-only (You need to change file permissions). It cannot be 2 (I'd bet abcD12E.pdf is a file). Check whether is 1 or 3 and take the action in brackets.
70,698,983
70,699,009
Const after operator function c++
I'm learning C++ i saw a const after an operator function. It doesn't make sense because the function returns the same value regardless of the const. What's the purpose of using it? using namespace std; class Person { public: int age; Person(int age) : age(age) {} int operator *(int &b) const { return b; } }; int main() { Person *p = new Person(11); int a = 19; cout << *p * a; // prints 19 delete p; }
A const operator behind a member function applies to the this pointer, i.e. it guarantees that the object you call this function on may not be changed by it. It's called a const-qualified member function If you tried, in this example, to change the persons age in the openrator*(), you would get a compile error.
70,699,450
70,699,709
How do I use catch2 just by cloning its repository and copying its src to my project?
I am trying to get catch2 running for a barebone project just to get familiar with it but so far I failed installing it in whatever sense possible. the catch2-git repository either points you to installing it together with cmake (via vcpkg (I cannot use MSVC and don't want to at this point) or points to some Ubuntu solution.) I figured I should just download the catch2 files directly and put it somewhere locally, run my code then and include the .hpp directly: #include "../../Catch2/src/catch2/catch_all.hpp" Now the compiler (I use gcc and the code blocks ide) will find catch_all.hpp but tells me that it cannot include the headerfiles that are linked in catch_all.hpp (first include tries to include catch_benchmark_all.hpp): ...\Catch2\src\catch2\catch_all.hpp|25|fatal error: catch2/benchmark/catch_benchmark_all.hpp: No such file or directory| The #include statement in catch_all.hpp looks like this: #include <catch2/benchmark/catch_benchmark_all.hpp> Now I would assume that one answer to my problem would be to make all the include paths inside the catch2 to be relative but is that really what they want me to do here? There must be a better way, no?
The GitHub page says: Catch2 v3 is being developed! You are on the devel branch, where the next major version, v3, of Catch2 is being developed. As it is a significant rework, you will find that parts of this documentation are likely still stuck on v2. For stable (and documentation-matching) version of Catch2, go to the v2.x branch. On the v2.x page there's a link to a standalone header file: The latest version of the single header can be downloaded directly using this link
70,699,498
70,738,590
Retrieve always latest messages from Kafka on reconnection
I'm writing a piece of code that needs to read hundreds of messages from Kafka each few milliseconds. I'm using C++ and librdkafka. When my program stops and then restarts it does not need to recover all lost messages since it was stopped, but instead it needs to always read from latest messages sent. As far as I know I can manage consumer offsets by playing with enable.auto.commit and auto.offset.reset. But, the latter one is only useful when there are no committed offsets while the former one instead let me manage myself the offsets to store. Playing with these two values I found that if I set enable.auto.commit to false, without committing any offset, and auto.offset.reset to latest it seems to retrieve always the latest messages; but how clean is this solution? My fear is that if between two consumer polls there are 2 messages sent than my consumer only takes the latest, or if no messages where sent it continually reads the same. Both are unwanted behaviour. Another idea was to clear consumer group offsets or seeking forward, but the seek method in librdkafka seems to not work as needed and I cannot find methods to manage consumer groups.. How can I always read latest messages from Kafka using librdkafka?
Finally I solved by managing myself the callback on rebalance. This callback will be always executed when a new consumer join or leave the group. The rebalance callback is responsible for updating librdkafka's assignment set based on the two events: RdKafka::ERR__ASSIGN_PARTITIONS and RdKafka::ERR__REVOKE_PARTITIONS. So within the rebalance callback I iterate over the TopicPartitions in order to assign them to the consumer, using the latest offsets. The snippet of code is this: class SeekEndRebalanceCb : public RdKafka::RebalanceCb { public: void rebalance_cb (RdKafka::KafkaConsumer *consumer, RdKafka::ErrorCode err, std::vector<RdKafka::TopicPartition*> &partitions) { if (err == RdKafka::ERR__ASSIGN_PARTITIONS) { for (auto partition = partitions.begin(); partition != partitions.end(); partition++) { (*partition)->set_offset(RdKafka::Topic::OFFSET_END); } consumer->assign(partitions); } else if (err == RdKafka::ERR__REVOKE_PARTITIONS) { consumer->unassign(); } else { std::cerr << "Rebalancing error: " << RdKafka::err2str(err) << std::endl; } } }; In order to use that callback I will set it to the consumer. SeekEndRebalanceCb ex_rb_cb; if (consumer->set("rebalance_cb", &ex_rb_cb, errstr) != RdKafka::Conf::CONF_OK) { std::cerr << errstr << std::endl; return false; }
70,699,881
70,699,942
C++ : Is there a good way to choose between 2 implementations?
Is there a good way for my header class to choose which .cpp file he can call at runtime? For example : a.h #pragma once #include <iostream> class a { public: a() {}; void printA(); }; a.cpp : #include "a.h" void a::printA() { std::cout << "first"; } a_mockup.cpp : #include "a.h" void a::printA() { std::cout << "second"; } Then in main I want to choose which one I want to call: main.cpp: #include "a.h" #include <string.h> using namespace std; int main() { a test; test.printA(); }
You cannot have two implementations of one function. That would violate the One Definition Rule. You cannot link both translation units into one program. You can choose between two implementations at link time. If you link the main.cpp translation unit with a.cpp, then you call that implementation, and if you link with a_mockup.cpp, then you call that other implementation. In order to choose between two functions at runtime, there must be two functions; each with their own name. A minimal example: void f1(); void f2(); bool condition(); int main() { if (condition()) f1(); else f2(); } In order to choose between two functions through one interface (i.e. abstraction), you need polymorphism. There are many forms of polymorphism in C++ ranging from function pointers to templates (not runtime) and to virtual functions.
70,700,179
70,700,671
Why is a lambda considered an expression (Or: What constitutes an expression in C++)?
Lambdas are considered expressions. According to cppreference an expression is "a sequence of operators and their operands, that specifies a computation." An expression also has a value category and a type: "The lambda expression is a prvalue expression of unique unnamed non-union non-aggregate class type [...]" The unique class type is clear to me and I presume it is an prvalue whose evaluation "initializes an object" rather than "computes the value of an operand of a built-in operator" (Value Categories). The article Expression (Computer Science) on wikipedia says: "[...] an expression is a syntactic entity in a programming language that may be evaluated to determine its value." I'm still puzzled about what the result of an evaluation of a lambda expression (i.e. its value) is. For example, consider the following simple unary predicate lambda: [](auto val) { return val % 2 == 0; } What's the value of this expression? Is it an object of the unique class type? Where is the computation that is mentioned in the cppreference definition?
What's the value of this expression? Is it an object of the unique class type? Yes, exactly that. Where is the computation that is mentioned in the cppreference definition? In the same way that 1 or std::vector<int>{} can be said to compute values, so do lambda expressions. On their own, those all do nothing. The vast majority of expressions will either be operands to other expressions (including being arguments to a function call expression), be initialisers for a variable, or have some side-effect when evaluated.
70,700,370
70,752,733
How do I compile and deliver my application without requiring installation of shared libraries on other machines
On my Ubuntu machine I installed libGLEW. However, I did not install it on my other Ubuntu machine. It works on my compiling machine, but now I received the following error after copying my executable to my other machine. I want to find a solution where I don't have to require my other machine to install the library. Maybe I can simply share the file along with the executable, like I would do in Windows with DLL files? Would that be possible? And if so, how do I do that? error while loading shared libraries: libGLEW.so.2.1: cannot open shared object file: No such file or directory In CMake, I used the following relevant pieces of code: set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14 -g" ) set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -m64 -g" ) include_directories( ... "/usr/include/GL" # Also includes glew.h ) add_executable( ${PROJECT_NAME} ${PROJECT_SRC} ) target_link_libraries( ${PROJECT_NAME} ... "GLEW" )
To solve the issue for my situation, I added glew.c to my source files which solves the issue.
70,700,386
70,700,618
Do the order of edges matter in union find?
I am learning union-find and to understand it better, I have written a small program: #include <iostream> #include <vector> #include <numeric> using namespace std; vector<int> parent, sz; int find(int i) { if(parent[i]==i) return i; return parent[i]=find(parent[i]); } void merge(int i, int j) { int p1=find(i); int p2=find(j); if(p1==p2) return; if(sz[p1]<sz[p2]) { parent[p1]=p2; sz[p2]+=sz[p1]; } else { parent[p2]=p1; sz[p1]+=sz[p2]; } } int main() { vector<vector<int>> allowedSwaps={{0,4},{4,2},{1,3},{1,4}}; int n=5; //hard-code for now sz.resize(n,1); parent.resize(n); iota(begin(parent),end(parent),0); cout<<"Parents before: \n"; for(auto& e: parent) cout<<e<<" "; cout<<"\n"; for(vector<int>& currswap: allowedSwaps) { merge(currswap[0],currswap[1]); } cout<<"Parents after: \n"; for(auto& e: parent) cout<<e<<" "; cout<<"\n"; return 0; } allowedSwaps essentially denotes all the components that are connected to each other. For the code above, all of them are connected. However, if you notice the output: Parents before: 0 1 2 3 4 Parents after: 0 0 0 1 0 It shows that one of them (3, 0-indexed) is not connected. I think that is because when we process the edge {1,3}, both the vertices 1 and 3 have not been connected to the larger component yet (they are later, by {1,4}) and so Union Find determines that it is a different component. Does this mean that the order of edges matter for Union find? Or, am I missing something?
The output you got does not signify that one node is disconnected. The parent data structure represents links from one node to another (or itself, when it is a root). At the start you have this: And at the end we have this: The important thing here is that there is one tree. It is not required that all nodes are linked directly to the root, just that they have a path to the root, which is also true for the node with index 3. NB: if you would call find(3), then also index 3 would receive value 0. It is just something that gets optimised by calling find, but it doesn't change the meaning of result.
70,700,592
70,701,809
What is a correct way to setup protobuf and grpc for cpp project?
I have a cpp project, and I want to build everything from source, to get latest things likned in. So under my project root I've created a 3rd_party folder and assemble following script: sudo apt-get install autoconf automake libtool curl make g++ unzip -y git clone https://github.com/google/protobuf.git cd protobuf git submodule update --init --recursive ./autogen.sh ./configure make make check sudo make install sudo ldconfig cd .. echo installing grpc git clone --recurse-submodules -b v1.43.0 https://github.com/grpc/grpc export MY_INSTALL_DIR=$HOME/.local be sure that its exists cd grpc mkdir -p cmake/build pushd cmake/build cmake -DgRPC_INSTALL=ON -DgRPC_BUILD_TESTS=OFF -DCMAKE_INSTALL_PREFIX=$MY_INSTALL_DIR ../.. make -j make install popd i've encountered following flaws: grpc v1.43.0 clones 3rd party submodule protoc v3.18, which after build has problems - protoc binary says "cpp plugin not found", when trying to generate To overcome that I've copied sources obtained in the first part of script, to 3rd party subfolder of second part, to gurantee it to be 3.19 - then after compilation protoc working great, plugins are in place, and grpc is linked against latest version. Very weird issue, needs understanding why it clones outdated version, and why 3.18 has no plugins under same build parameters as 3.19 in cmakelists find_package(Protobuf REQUIRED) fails at all find_package( gRPC REQUIRED ) is not operating properly: Found package configuration file: [cmake] [cmake] /home/a/.local/lib/cmake/grpc/gRPCConfig.cmake [cmake] [cmake] but it set gRPC_FOUND to FALSE so package "gRPC" is considered to be NOT [cmake] FOUND. Reason given by package: [cmake] [cmake] The following imported targets are referenced, but are missing: [cmake] protobuf::libprotobuf protobuf::libprotoc Question How can I write script, that in an empty folder will get me everything, related to grpc 3rd party libs and tools, that I need for project?
Here are the steps I took: $ mkdir .local $ export INSTALL_PREFIX="$PWD/.local" $ export CMAKE_GENERATOR=Ninja # optional, but recommended $ git clone --recurse-submodules -b v3.19.3 --depth 1 https://github.com/google/protobuf.git $ pushd protobuf $ ./autogen.sh $ ./configure --prefix=$INSTALL_PREFIX $ make -j$(nproc) $ make install $ popd $ git clone --recurse-submodules -b v1.43.0 --depth 1 https://github.com/grpc/grpc.git $ cmake -S grpc -B .build/grpc \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_INSTALL_PREFIX=$INSTALL_PREFIX \ -DCMAKE_PREFIX_PATH=$INSTALL_PREFIX \ -DgRPC_INSTALL=ON \ -DgRPC_BUILD_TESTS=OFF \ -DgRPC_PROTOBUF_PROVIDER=package \ -DABSL_PROPAGATE_CXX_STD=ON $ cmake --build .build/grpc --target install ... $ mkdir example $ echo "int main () { return 0; }" > example/main.cpp $ vim example/CMakeLists.txt $ cat example/CMakeLists.txt cmake_minimum_required(VERSION 3.22) project(example) find_package(gRPC REQUIRED) add_executable(main main.cpp) target_link_libraries(main PRIVATE gRPC::grpc++) $ cmake -S example -B .build/example \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_PREFIX_PATH=$INSTALL_PREFIX $ cmake --build .build/example ... I build protobuf separately because gRPC doesn't set up its dependencies in CMake correctly when using its internal protobuf build (I tried both ways). This involves passing --prefix to protobuf's ./configure script and passing -DgRPC_PROTOBUF_PROVIDER=package to gRPC's CMake build. The latter is a gRPC-specific variable that tells it not to build protobuf, but to search for it instead. I tell gRPC where to find protobuf by setting CMAKE_PREFIX_PATH, which is a standard variable.
70,700,659
70,710,235
c++ boost locale - generator throws runtime_error with "Invalid file format" message
I try to reproduce the example of boost locale documentation with this piece of code : #include <boost/locale.hpp> #include <iostream> #include <stdexcept> using namespace boost::locale; using namespace std; int main() { generator gen; // Specify location of dictionaries gen.add_messages_path("./languages"); gen.add_messages_domain("hello"); // Generate locales and imbue them to iostream locale::global(gen("es_ES")); cout.imbue(locale()); // Display a message using current system locale cout << translate("Hello World") << endl; return 0; } I have generated this hello.mo file with xgettext and put it in a folder ./languages/es_ES/LC_MESSAGES : # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2022-01-13 17:30+0100\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n" "Language-Team: LANGUAGE <LL@li.org>\n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=CHARSET\n" "Content-Transfer-Encoding: 8bit\n" #: test.cpp:95 msgid "Hello World" msgstr "Hola a todos" When I run the code, the line locale::global(gen("es_ES")); throws a std::runtime_error with this message : "Invalid file format". Does it mean that there is an error in the .mo file ?
I forgot to compile the .po file... xgettext generates a .po text file which needs to be compiled into a .mo file. This can be done with msgfmt : msgfmt hello.po -o hello.mo
70,701,701
70,707,906
Dynamic Programming Using STL Vectors Makes Program Freeze Beyond Certain Values
I wrote the following program, trying to optimize a recursive algorithm using Dynamic Programming. #include <bits/stdc++.h> using namespace std; int mini(int n, vector<int> &memory){ if(n<memory.size()){ return memory[n]; } else{ int m = (n+1)+mini(((n-1)/2), memory)+mini(((n-1)-((n-1)/2)), memory); memory[n]=m; return m; } } int main(){ vector<int> memory={0, 2, 5}; int t; cin >> t; while(t--){ int n; cin >> n; cout << mini(n, memory) << "\n"; } } The base conditions for the recursive function are already specified inside the vector, and the function does work for the base conditions. It works correctly for mini(1), mini(2), ..., mini(5). Whenever I am trying anything from mini(6) or beyond, the program just freezes. After a bit of debugging, the problem does seem to be that the function is unable to read any of the values that we are subsequently adding into the memory vector. Which is why the following works: mini(5) = 6 + mini(2) + mini(2) //mini(2) is pre-specified in memory vector. mini(4) = 5 + mini(1) + mini(2) //mini(1) and mini(2) are pre-specified. However, mini(6) = 7 + mini(2) + mini(3) //mini(3) is not pre-specified into vector memory. Here, mini(3) should have been added into the vector and used, but the function somehow doesn't seem to be able to do that. It seems that the function is unable to perform recursions beyond a single level. I have no idea why, and would very much prefer some reason why this is happening.
Following insights from the comments, the problem has been solved. There were two issues with the initial program: Trying to insert elements beyond the current size of the vector: To fix this issue, use an if statement before inserting elements to the vector to ensure that it has the correct capacity. if(memory.capacity()<(n+1)){ memory.resize(n+1); } memory[n]=m; Using items from memory that we did not previously insert: When we are resizing memory from the previous point, we are also creating empty values at spots that we did not insert into before. For example, mini(7) would insert the values of mini(3) and mini(7) into memory. The values of mini(4), mini(5) and mini(6) would remain 0. Later when we use the function, the values of mini(4), mini(5) and mini(6) would be found in the memory to be 0, and be used as such, leading to incorrect answers. Fixing both errors, the revised function looks like this: int mini(int n, vector<int> &memory){ if(n<memory.size() && memory[n]!=0){ return memory[n]; } else{ int m = (n+1)+mini(((n-1)/2), memory)+mini(((n-1)-((n-1)/2)), memory); if(memory.capacity()<(n+1)){ memory.resize(n+1); } memory[n]=m; return m; } }
70,702,030
70,702,125
How to use three-way comparison (spaceship op) to implement operator== between different types?
Simple Task: I have these two types struct type_a{ int member; }; struct type_b{ int member; }; I want to use this new C++20 spaceship op that everyone says is so cool to be able to write type_a{} == type_b{}. I didn't manage to do that. Even if I write operator<=> between them, I only ever can call type_a{} <=> type_b{}, but never a simple comparison. That confuses me as with a single class, the three-way comparison also defines all the others. Alternative formulation? How to make it so that std::three_way_comparable_with<type_a, type_b> is true?
The premise of the question is wrong. You don't use the three-way comparison operator (<=>) to implement ==: you use == to implement ==: bool operator==(type_a a, type_b b) { return a.member == b.member; } The source of confusion is that there is one exception to this rule: if a type declares a defaulted <=> then it also declares a defaulted ==: struct type_c { int member; auto operator<=>(type_c const&) const = default; }; That declaration is equivalent to having written: struct type_c { int member; bool operator==(type_c const&) const = default; auto operator<=>(type_c const&) const = default; }; But it's not the <=> that gives you ==: it's still the ==, and only ==, that gives you ==.