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
65,540,841
65,541,272
C++ minor problem: no suitable constructor exists to convert from "void"
I'm new to C++ and run into the following problem when trying to implement a simple recursive algorithm. The problem is highlighting the sorted_lst.push_back(last[0]) in the base case return and says: no suitable constructor exists to convert from "void" to "std::__1::vector<int, std::__1::allocator<int>>"C/C++(415) . ...
As Tumblweed53 pointed out, you are returning the void which was returned by push_back. You can do the following instead: vector<int> merge_sorting(vector<int> lst, vector<int> sorted_lst = vector<int>()) { if (lst.size() == 1){ sorted_lst.push_back(lst[0]); return sorted_lst; }; vector <in...
65,541,016
65,541,091
matrix using pointers c++ without dynamic allocation
So i have an assigment that would read a matrix using pointers and show it using pointers also i wanna know why it always add a row where is exactly the mistake and it doesnt show the matrix also thnks #include <iostream> using namespace std; int main () { int Mat[50][50],N,M; int (*ptr)[50][50]; cout<<"n...
Your mistake is here cin>>*ptr[i][j]; that should be cin>>(*ptr)[i][j]; and the same error here cout<<*ptr[i][j]; that should be cout<<(*ptr)[i][j]; But why are you using ptr why not just use Mat instead? cin>>Mat[i][j]; cout<<Mat[i][j]; What do you think is the benefit of using a pointer to your matrix, why not j...
65,541,368
65,541,509
how compiler compile template and type checking?? (c++)
My Question is how compiler compile template and how compiler do type checking. i wanna know about how compiler compile template code. first of all, i just show you how i think how template works? first. compiler copy and paste template code replaced with template argument template <typename T> class vector { T* dat...
Templates are compiled in two phases: At definition time (no instantiation yet) the template code itself is checked for correctness (ignoring template parameters) for example: syntax errors, unknown names, etc. At instantiation time the template code is checked again, for ex. all parts that depend on template paramet...
65,541,406
65,541,498
Enabling UNICODE in gcc windows api string processing
I am trying scan thru windows wave devices, using following test snippet in test.cpp; using namespace std; #include <string> #include <vector> #include <Windows.h> int main () { int nDeviceCount = waveOutGetNumDevs(); vector<wstring> sDevices; WAVEOUTCAPS woc; for (int n = 0; n < nDeviceCount; n++) ...
By default, the UNICODE macro is undefined. This makes the pzPname field be CHAR pzPname[MAXPNAMELEN] in the definition. That’s why the error arises, as the std::wstring is trying to initialize with char data rather than wchar_t data. To resolve this, place a #define UNICODE statement before including the Windows.h fil...
65,541,499
65,541,625
C: Trouble with GMP pointers in a struct
I'm fairly new to c and I'm implementing a DHT. For that, I have to store node IDs in a list. Node IDs are < 2^160 whole numbers(thus resulting in me using GMP), but I'm setting 123 as an ID here to keep the example clean. I am able to set the Node's ID just fine, and I also verify it with mpz_out_str. When I iterate o...
With node->node_id = &id; your node_id points at a local variable. When add_node returns, id is destroyed and your pointer is dangling. Dereferencing it results in Undefined Behavior. A simple solution is to store the id in Node rather than storing a pointer to it. typedef struct { mpz_t node_id; } Node;
65,541,667
65,551,128
Is it possible to have a C code deployed that passes through and overwrites keystrokes from the keyboard?
I use some "user friendly" programs that demand me to type in long sequences of shortcuts and other characters at times. I found some tools like cnee but nothing that could help me to automate these sequences with no time and effort. I have simply added the source code into one of these programs (Qt), but another has m...
You do not need to write the whole driver. You need only C, uinput and some time to develop. What to do: 0. Finding your keyboard device node. you can use evtest or detect it dynamically. You can skip it if you know keyboard's event device node path (like /dev/input/event5). open keyboard by path. grab device to preve...
65,541,680
65,542,070
How do I perform an addition of a templated struct?
Currently I'm learning about structs and templated. I have a templated struct: template<int value> struct ConstInt { static int eval() { return value; }; }; I want to achieve the following: Create an Add struct template that take two structs as template parameters. An example of the usage is gi...
I would do something like this, template<int value> struct ConstInt { // Use constexpr as this method can be evaluated at compile time. static constexpr int eval() { return value; } // You dont need a semicolon here. }; template<class a, class b> struct Add { constexpr int operator()(...
65,542,159
65,542,564
Using operator += with multiple values
I wish to create a template of an operator +=, that would add values to the vector. I've been tinkering with the parameter packs, but it didnt work for me (i guess i did something wrong as a newbie to C++). Basically i want to achieve the effect of adding to the end of the vector with code like this: std::vector<int> v...
Overloading += is not sufficient to enable that syntax literally: std::vector<int> v; v += 1,2,3,4; You need a , too: #include <iostream> #include <vector> struct hacky_vector { std::vector<int>& v; hacky_vector& operator,(int x){ v.push_back(x); return *this; } hacky_vector& op...
65,542,214
65,542,510
Qt, communication between classes
I have two classes MainWindow and Worker. MainWindow is basically responsible for GUI and the worker is for connecting with the server. MainWindow has an instance of Worker. If Worker receives a message from the server it is supposed to change the GUI, but I can not find a way to communicate them. I thought about makin...
You mentioned signals/slots in your question, but you combined them with a singleton, which is not needed at all. You said MainWindow has an instance of Worker, so just connect to a signal from the Worker. Since you didn't provide any code, I'll make something up. void Worker::doSomething() { ... // When we ge...
65,542,286
65,542,315
Null type in standard C++ library
Is there some special null type and value in standard C++ library, e.g. defined as struct null_type_t {};? I want to use it in different places to signify that there is no value passed. E.g. to use in next template: template <typename T = std::null_type_t> struct S {}; Or in structure like next: template <typename T> ...
std::optional uses std::nullopt_t for this purpose: https://en.cppreference.com/w/cpp/utility/optional/nullopt_t So for your own optional type, you should probably implement your own nullopt_t.
65,542,341
65,542,372
Difference between x * 0.1 and x / 10?
I am a high school student and I saw a while ago that is better to multiply than to divide. Since then, without any proof found that it is true or not and without knowing how to do find it by myself at the moment, I tried to modify my codes for that slightly better time. Here is a problem where I wanted to find the big...
0.1 is a double type, 10 is an integer type. When dividing two integers e.g. n / 10 you will get integer division (e.g. 6/10 will equal 0). And your check will work differently when using 6 * 0.1 as that will equal 0.6.
65,542,765
65,545,220
Restricting template type to enum class
The function get_from_string below basically casts a string to a variable by creating a stringstream from the string and writing that to (a pointer of) the variable. Afterwards, it returns whether that was successful or not. If the variable is an enum class, it goes a little detour over the enum class' underlying_type ...
With C++17, you might do: template <typename T> bool get_from_string(T *target, const std::string &input) { if constexpr (std::is_enum_v<T>) { std::underlying_type_t<T> value{}; auto res = get_from_string(&value, input); *target = static_cast<T>(value); return res; } else { ...
65,543,144
65,543,689
Pointer stored in array changes value C++
First of all, I am noob at C++ so there is a huge chance I am making a stupid mistake. However I cannot figure out what the issue is. I have an object class called State and I have created a custom class called List to store, add and remove pointer references of instances of the State objects. Here is how the List clas...
Okay, you received some comments. I'm going to put them together into a full answer. This is your main problem: State* list[]; This is bad code, but it sounds like your compiler is letting you do it. This is suggesting you have an array of State-pointers. Great. How big is the array? Answer: unknown. We don't know...
65,543,145
65,543,509
Template candidate ignored despite a user provided deduction guide
I have a struct sequence similar to std::integer_sequence, but it can hold values of multiple types as non-type template parameters (sort of like a compile-time tuple). It is implicitly constructible from std::integer_sequence by using a constexpr constructor and a user-defined deduction guide. I also have a function a...
You could make an overload that forward to your first apply_constexpr function. Something like this. template<typename Fn, typename Is> constexpr auto apply_constexpr(Fn&& fn, Is s) noexcept(noexcept(apply_constexpr(fn, sequence{s}))) { return apply_constexpr(std::forward<Fn>(fn), sequence{s}); } The reason it doe...
65,543,450
65,543,551
Do I need a copy constructor if I'm using a vector to hold objects?
Here is an example: #ifndef CPP_PRACTICE_ACCOUNTS_H #define CPP_PRACTICE_ACCOUNTS_H #include <string> #include <utility> class Accounts { private: /* variables */ std::string email, password, displayName, dateOfBirth; /* invariant */ bool accountCreated;...
Until C++11 template parameter T in std::vector<T> had to meet CopyAssignable and CopyConstructible requirements. After C++11 this was relaxed, depending on what operations are used on the vector. For example in your case, if no operation on the vector is used where the copy is needed then no need for copy ctor. Exampl...
65,543,623
65,544,772
Converting IP address to binary
I'm currently working on converting each piece of an ip address to binary, and I would be glad if u can tell me why my code doesn't work. The main problem is with function ip_bin(); cause it's converting the first number correctly to binary but somehow later then it is adding the first number to the second one... same ...
Idk if u meant that but if its not what u wanted then comment i will delete , dont rep - #include <iostream> #include <string> using namespace std; string ip, mask; string ip_string[4]; int ip_int[4], length[4]; void dec(); void enter(); void get_ip(); void ip_bin(); int main(){ enter(); get_ip(); cout...
65,543,696
65,566,879
How to use Z3 Context in Python api?
In C++, z3::context context generate a new context.Through this Z3 expressions with new context can be created as context.bv_const(variable_name, 16). How can the same behaviour be done using z3 python api ?
In z3py, the general use model is via a Solver object, which is backed-up by one global context. This simplifies programming, as end users need not worry about the details of context creation. From the documents: Z3Py uses a default global context. For most applications this is sufficient. An application may use ...
65,543,700
65,545,076
How to use googletest with premake5 and VS2019
I have been trying to integrate googletest into my solution, but I get either nasty linker errors or can't add it at all. googletest was added as a submodule: git submodule add 'https://github.com/google/googletest.git' Have been trying configuring premake5 like so: ... project "libtest" location "libtest" kind...
Finally managed to fix it :) adding some extra file with: int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } fixed linking problem, and cleaning up: "libtest/vendor/googletest/googletest/include/gtest", "libtest/vendor/googletest/googletest/include", "libtest/ven...
65,543,782
65,546,053
How to get all the values bellow the variable that triggers it?
Hello everyone hope you had wonderful new years eve. I am searching for a command to use in my IF function that could read if the values are bellow for the variable that triggered it. Example of what I am trying to achieve: I have a signal coming trough mqtt back from nodered to my code which is a slider that choses th...
First, this will eventually break: if (millis() > millisNow + sendDelay). I think you want millis() - lastmillis >= sendDelay. (example page: https://www.norwegiancreations.com/2018/10/arduino-tutorial-avoiding-the-overflow-issue-when-using-millis-and-micros/) It looks to me that you do too much testing in your condit...
65,544,093
65,544,280
No compile_commands.json file using cmake with vs code on windows
I am trying to integrate the Clang-Tidy static analysis tool into my build system. I am getting a few issues with my setup. Step cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON .. is not generating compile_commands.json file. Hence, clang-tidy is giving below error. >cmake --build . result Could not auto-detect compilation da...
See https://cmake.org/cmake/help/latest/variable/CMAKE_EXPORT_COMPILE_COMMANDS.html Specifically this Note: Note This option is implemented only by Makefile Generators and the Ninja. It is ignored on other generators. Instead, you could write a python script which would generate that format for you, similar to this t...
65,544,630
65,545,420
Understanding std::apply inside std::visit
https://github.com/google/oboe/blob/e3e93e307456a388a84a6e0d96f9adb240f5918d/apps/fxlab/app/src/main/cpp/native-lib.cpp#L93 std::visit([id](auto &&stack) { std::function<void(decltype(stack.getType()), decltype(stack.getType()))> f; int i = 0; std::apply([id, &f, &i](auto &&... args) mutable { ((f =...
((f = (i++ == id) ? args.template buildDefaultEffect<defaultEffect<decltype(stack.getType())>() : f), ...); this is a comma-fold execute pack expansion. It is an awkard way to iterate over non-uniform typed elements in a tuple. If you could iterate over a pack of non-uniform elements: int i=0; for...(auto& ...
65,544,730
65,546,043
How to print out how many times does QuickSort does switches and checks?
I have this task where I have to do a research about quicksort algorithm and I have to measure how many time does this algorithm checks numbers (if statements) and switches them. Afterwards I need to print out 2 variables that show how many times were number checked and switched. I think I'm having issues because I'm u...
Make checks and switches global variables. while (arr[i] < pivot) i++; checks++; Shouldn't this be while (arr[i] < pivot) { i++; checks++; } checks++; Thank you @NateEldridge for pointing out the last check which terminated the loop must also be counted, hence the checks++ at the end. 3. if (i <= ...
65,545,042
65,545,065
Not using functions for speed? (C++)
I'm writing a program for a competition in my class. It already works great and now I'm trying to make it as fast as possible. My question is- would just pasting what a function returns, wherever I want to use it, speedup my program as compared to making a user defined function? I know that function calls causes a jump...
In general, none of that ought to matter. Optimizing compilers are really, really good at determining when to perform strength reduction (turning multiplication into adds or shifts) or inlining (eliminating the overhead of the function call). You should focus your time and effort, as a human, on writing concise, mainta...
65,545,218
65,557,530
performance of declaring objects
I was coding in some sort of university conquest and noticed something, when I declare a map in a loop such as down below: for (int i = 0; i < n; i++) { map<int, bool> hashMap; //... } it takes more time than: map<int, bool> hashMap; for (int i = 0; i < n; i++) { hashMap.clear(); //... } so I was wond...
In the first version of the code the constructor and destructor of the hashMap are called n times, while in the second version they are called just once. The natural question is why destructing and constructing a new map object would be noticeably different vs. clearing and reusing one and the same object. This can be ...
65,545,367
65,548,704
Cython modifiy pointer from c++
I need to modify my NumPy arrays which I am passing from cython to c++ function. Everything works fine but when I print out the value after calling the c++ modifier function, the value remains the same as it was before calling the function. I also tried the same with string but it does not work out as well. I used the ...
cdef float[:, :, ::1] d_view = d.astype(np.float32) Docs: By default, astype always returns a newly allocated array i.e. d_view is a view of a copy of d, not a view of d. We therefore do not expect changes made by d_view to reflect in d. int modify(S1* s1, char* str) { str = "newstr"; // string modify This is ...
65,545,506
65,545,555
Segfault when converting vector into vector<vector<complex>>
Good day. I was wondering if I could get some help on this. I've got the following: #include <vector> #include <complex> #include <iostream> using messageScalar = std::complex<double>; using messageVector = std::vector<messageScalar>; using messageMatrix = std::vector<messageVector>; class Tester { public: Tester(...
The problem The problem is in your constructors, see comments: messageMatrix container(1, t); // <--- container is a local variable messages = &container; // <--- you take the address of the local variable } // <--- you leave constructor: local is destroyed Or for the s...
65,545,712
65,545,735
Return type of closure in C++
I am trying to learn closures in C++. This example works: auto add_n(int n) { return [=](int x) -> int { return x + n; }; }; auto add_3 = add_n(3); add_3(5); //8 What type is add_n expecting out? I would expect to be able to use a function pointer that takes in an int and returns an int as the return t...
Each lambda has its own unnamed types, so you cannot replace auto by its real type. Lambda with capture cannot be converted to function pointer.
65,545,815
65,546,299
How to properly use new and delete (to avoid buffer overflow problems)
This is related to my previous question(now deleted) where I tried to implement a std::vector like data structure. The following is the code. #include <iostream> #define print(m) std::cout << m << std::endl template<typename T> class vector { private: unsigned int size = 0; unsigned int mem = 5; bool full...
It is not a problem with your code but a false positive from the analyser. If you open the + next to the message in the Error List (assuming you include Intellisense errors in it), the analyser will show the step it used to make the deduction. You could tell the analyser that mem is greater than size using _Analysis_as...
65,545,948
65,557,089
C++ Unit Test in Visual Studio 2019
I am having a problem with Visual Studio 2019 CPPUnitTestFramework. I follow the instructions, but every time I get an error. I have looked for tutorials, but anything I get is for Visual Studio 2017 and it does not solve my problem. I am writing a program that uses OOP in C++ and I want to make unit tests, since it is...
I suggest you to check if TestUnitForTestTestUnit has added Additional Dependencies. When I didn’t add it, the same problem as you occurred. After I added it, the program worked fine. Right click TestUnitForTestTestUnit->Properties->C/C++->Linker->Input->Additional Dependencies-> add ..\TestTestUnit\Debug\*.obj
65,546,392
65,546,591
Accessing the contents of a function from a struct defined inside that function
typedef void (*voidfunc)(); void somefunc(voidfunc function) { voidfunc func = function; struct wrapper { function(); //does not work func(); //does not work }; } Is there any way at all to access function from inside the struct wrapper? I am trying to see if it is possible to implemen...
Lambda Solution You can achieve this using C++ lambdas. Note my example requires C++14 (or greater) to compile. #include <iostream> typedef void (*voidfunc)(); void doNothing() {} auto foo(voidfunc function) { auto wrapper = [function]() { int x = 1; function(); int y = 1; std...
65,547,048
65,547,290
Is there anyway to access/modify an array using a string that contains the name of the array?
Let's say we have a couple arrays called "one", "two", and "three". Is there any way to access/modify the arrays using a string that contains the name of the array? For example, int one[n]; int two[n]; int three[n]; string str = "one"; // str can be "one", "two", or "three" // I wanna access/modify whatever array that ...
Yes it's possible. But also yes, you'll have to do write the code to map from the name as a string to the array you want that name to refer to. A simple version would be to use an std::unordered_map for the task: std::vector<int> one, two, three; std::unordered_map<std::string, std::vector<int> &> names { { "o...
65,547,104
65,589,240
How to turn Windows Proxy On/Off programmatically
I need a code to turn Windows Proxy on or off. I tried: WINHTTP_PROXY_INFO proxyInfo; proxyInfo.dwAccessType = WINHTTP_ACCESS_TYPE_NO_PROXY; proxyInfo.lpszProxy = new WCHAR[25] { 0 }; proxyInfo.lpszProxyBypass = new WCHAR[25] { 0 }; WinHttpSetDefaultProxyConfiguration(&proxyInfo) but it does not turn the proxy off e...
Turn Windows Proxy on, #include <Windows.h> #include <wininet.h> #pragma comment(lib,"Wininet.lib") void main() { INTERNET_PER_CONN_OPTION options[2]; INTERNET_PER_CONN_OPTION_LIST list{}; list.dwSize = sizeof(list); list.dwOptionCount = 1; list.pOptions = options; options[0].dwOption = INTERNE...
65,547,111
65,547,178
What does "char fun[](int x) const" do?: C++ Syntax Error
I am following along with a video emulating a cpu in C++. The programmer used the following and it is the first time I encounter it: This is the code from the video: struct Mem { Byte Data[MAX_MEM]; Byte operator[]( u32 Offset ) // <-- I don't understand this syntax { } } I wrote it in my own project ...
Your minimal example isn't quite right; the syntax they are using in the video is very particular and you've changed some crucial pieces - they are overloading the indexing operator as a member of a class. A silly minimal example of what's going on is as follows: struct X { char data[1024]; char& operator[](int i...
65,547,259
65,547,321
Why comment cannot execute and ignore by the compileres ,in which header file it's defination exit?
I am unable to understand the behavior of comments in C++. Why comment not executed by the compiler , what's the main reason, and in which header file the definition of comment can exit. Thanks
Comments (single line or multi lined) are not a part of the executable/ library. It is just in place, basically to document the code and make it easier to understand what's going on. Sometimes when the same source or header file is edited by multiple programmers, the other programmers might not know what a particular s...
65,547,843
66,967,699
how to write C++ DLL file for python correctly?
this is my test.cpp file.(I also used makefile to create dll file) //#include <iostream> int foo(int a) { if (a > 1) return a + 1; else return a + 2; } when I run following code in python import os import ctypes lib_bfs = ctypes.WinDLL("D:\\advanced_programming\\HW7\\cpp_part\\libtest.dll") ...
thanks to @DhirajWishal first I added the following line in my makefile. g++ -std=c++17 -O3 -I./h -g -fPIC -shared ./cpp/test.cpp -o ./libtest.dll -static-libgcc -static-libstdc++ then I placed libwindpthread-1.dll (which was in F:/strawberry/c/bin/ dir ) next to my makefile and the problem was solved.
65,547,900
65,548,343
Extracting and storing data to ostream
Is it possible to store data to an ostream like this void write(std::ostream& os){ int x,y = 0; bool b = true; os<<x<<" "<<y<<" "<<b<<std::endl; } and then extract data from it like this void read(std::istream& is){ unsigned int x,y,b; is>>x>>y>>b; // I want to take x,y,b and make store them in a object but it...
After closing and reopening the file my problem fixed. #include <iostream> #include <fstream> #include <string> int main(int argc, char const *argv[]) { std::ofstream file(argv[1]); if (!file.is_open()){ std::cerr<<"erreur"<<std::endl; return 1; } bool v = false; size_t x = 1; size_t y = 2; for(s...
65,547,908
65,548,043
Why is template<classTp> bool is_array<Tp[]> a partial specialization for template<class T> bool is_array<Tp>?
How to comprehend that template<typename Tp> bool is_array<Tp[]> = true is a partial specialization for template<typename T> bool is_array<Tp> = true? Here is the related code snippet: #include<iostream> template<typename T> bool is_array = false; template<typename Tp> bool is_array<Tp[]> = true; int main() { st...
For a template to be a specialization of a primary, it needs to be more specialized than the primary. This basically means that the specialization must match a strict subset of types that the primary can match. In your case, the specialization would match int[], char[], etc. The primary would also match these types, bu...
65,548,016
65,548,052
Why does printing reference of a char type variable returns the value in it?
Code Snippet : #include <iostream> int main() { char c = 50; int i = 50; std::cout<<&c<<"\n"; std::cout<<*(&c)<<"\n"; std::cout<<&i<<"\n"; return 0; } Expected output : <memory_address> 2 <memory_address> Original output : 2 2 0x7ffee0504ac4 Confusion : I thought & in this case should retu...
Its because of overload for operator<< (const char*) for ostream. &c is of type char* and the operator<< tries to print 0-terminated C-string. If you cast to void* as (void *)(&c) then you will get memory address as expected: #include <iostream> int main() { char c = 50; int i = 50; std::cout<<&c<<"\n"; ...
65,548,064
65,548,386
How to sychronize the output of NMEA gps sentences
I have two functions : string get_GPGGA() { // read_gga_sentence extract only gga return gps.read_gga_sentence(); } string get_GPGSA() { // read_gsa_sentence extract only gsa return gps.read_gsa_sentence(); } int main() { while(true) { cout << get_GPGGA(); cout << get_GPGSA(); } } The problem is, the...
You don't need multithreading, just buffering and a gps.Read() function. Which library do you use ? GPS messages are text/line based: $GPGGA,092750.000,5321.6802,N,00630.3372,W,1,8,1.03,61.7,M,55.2,M,,*76 $GPGSA,A,3,10,07,05,02,29,04,08,13,,,,,1.72,1.03,1.38*0A $GPGSV,3,1,11,10,63,137,17,07,61,098,15,05,59,290,20,08,54...
65,548,169
65,548,197
DLL not found despite static linking
I have bass.lib, bass_fx.lib and zlib.lib in my Library folders and Additional Dependencies in my project. But when I run my program, it complains it can't find bass.dll, bass_fx.dll and zlib.dll. How can this be fixed?
If you want to link statically, first you have to make sure that the *.lib's you have are really static and not dynamic libraries (which seems to be the case). You can use dumpbin from visual studio command line tools, to verify what's inside those .libs.
65,548,213
65,549,601
Unable to load html video tag in wxHtmlWindow?
I am trying to set html page in wxHtmlWindow. It is loading all the basic tags except html video tag. Note: My HTML file with the same video tag is working fine (Video is playing). html = new wxHtmlWindow(this); html -> SetRelatedFrame(this, _("wxHTML Demo: '%s'")); #if wxUSE_STATUSBAR html -> SetRelatedSta...
It supports only a limited set of tags, and was not even intended to cover them all. But, wxHtmlWindow supports tag handlers. This means that you can easily extend wxHtml library with new, unsupported tags.
65,548,323
65,548,358
Valgrind error dereferencing an address returned by std::vector
Why does valgrind returns an error for this piece of code? #include <iostream> #include <vector> int main() { std::vector<int> vec; int *ptr; for (int i = 0; i < 1000; i++) { vec.push_back(i); if (i == 100) { ptr = &vec[i]; } } std::cout << ptr << "\...
Valgrind says it's an "invalid read". During the push_back operation the std::vector will reallocate memory if required and copy all the data to anew location. If so, it is possible that your ptr is pointing to memory which is no longer allocated to the vector vec. So yes, it might be UB the way you are using it. It's ...
65,548,906
65,548,971
How does std::make_shared and std::make_unique work behind the scenes?
Edit: I am referring to std::make_shared and std::make_shared, not their actual constructors. I have edited the title but the text below still talks about constructors. Ignore that I use the word "constructor" I am trying to learn how smart pointers work behind the scenes but the source files seem to go beyond my under...
You can use variadic templates and forwarding to forward an arbitrary amount of arguments to another constructor or function. For example: #include <memory> // Include std::forward. template <typename T> class SmartPointer { public: template <typename ... Args> SmartPointer(Args&& ... args) : the_pointer{new...
65,548,944
65,716,517
CPLEX: freeing model (resources) takes immense time
I am solving a MIP and have built a corresponding CPLEX IloModel. My implementation follows the following pseudo-code: model = IloModel( env ); //Build optimization model //Configure CPLEX Solver //Solve model //Do some solution-statistics model.end(); Everything works fine, I get correct solutions, et cetera. No...
I'm guessing, but did you terminate the solver before terminating the model? The solver is using the model and so it is notified about its changes. It could be that model.end() is not optimized and as it is freeing constraints one by one, solver is notified about each particular change, it updates its own data structur...
65,549,035
65,556,466
C++ linker finds header but cannot find .cpp file (using cmake, gcc)
I am trying to include a project within a project. The relevant structure is as such: projectA /CMakeLists.txt (PA1) /src /main.cpp /req/projectB /CMakeLists.txt (PB1) /src /projb.hpp /projb.cpp ...
Turns out that another part of projectA which I thought was irrelevant was actually very relevant. Thus I just needed to add this line: # projAadep is included by main.cpp from projectA target_link_libraries(projAdep PRIVATE projectB) before this line: target_link_libraries(${PROJECT_NAME} PUBLIC projectB) My underst...
65,549,446
65,549,880
error in STL sort function with Compare function
i try to sort a vector which element-type is a class like following: void sort_test() { class A{ public: A(float x, float y, float z):score_(x),rerank_score_(y),ranking_score_(z) {}; float score_; float rerank_score_; float ranking_score_; }; using A_ptr = std::shared_ptr...
Testing your code in Visual Studio revelas that CompareA_ptr doesn't define a strict weak ordering as required for a comparator. This causes undefined behaviour. The culprit seems to be return x->ranking_score_ >= y->ranking_score_; where >= should be changed to > return x->ranking_score_ > y->ranking_score_;
65,549,666
65,549,963
C++ program not working for large input (logic_error, _M_construct null not valid)
I'm trying to implement the maximizing salary problem. Like if we are given two numbers 2 and 21 then the resultant number should be 221 not 212. I implemented the code and it works very well for small inputs. The code uses C++ std::sort with a simple comparator function. For big inputs like for 100 it fails and gives ...
Your comparator function does not meet the requirements. Namely, it does not define strict weak ordering. See the documentation for more details. For example, comp(s,s) must be false, while in your code, calling comp with the same argument always yields true. Basically, you may not use >= or <= when defining a comparat...
65,549,761
65,556,695
I called showMaximized() with QT4.7,A strange question came up
That's what I would like to achieve: But it turned out that way:
I found the cause of the problem because I called QWidget::setWindowFlags(Qt::FramelessWindowHint);This caused showMaximized() to show the wrong result.So I've reimplemented these two functions。 void MainWindowDef::showMax() { oldSize = this->size(); oldPoint = this->pos(); resize(QApplication::desktop()-...
65,549,769
65,562,681
Using GoogleMock to avoid dependencies when testing a Card and a CardCollection class
I'm learning about mocking and am reasonably new to the concepts. For the sake of learning, I'm implementing a Card class and a CardCollection class which depends on the Card. Therefore I've created a MockCard for testing the CardCollection. Here's the Card.h class ICard { protected: int rank_; ...
After you have acquired a pointer to new_card, you can use ON_CALL(*new_card, getRank()).WillByDefault(Return(6)); to make your mock method return 6
65,549,957
65,550,123
Correct way to start a function object thread in C++?
I have this code so far : #include <iostream> #include <string> #include <windows.h> #include <iomanip> #include <thread> #include <chrono> #include <atomic> class test { public: thread t1; test() : t1(&test::work, this) { } void work() { while (true) { cout << "in thread...
Is this how I'm supposed to create a thread in a class object for one function only after I initialize the object? It's one option. Another is t1([this]{ work(); }). Relevant question: Start thread with member function Be aware that, generally, the current instance (*this) may not be fully constructed when the thread...
65,550,280
65,551,672
delete causes core dumped, and why?
I encountered core dump when delete the array new without delete[] here is my code: Page *p; p = new Page[10]; delete p; but when I try to delete int[], there seems nothing here: int *p; p = new int[10]; delete p; I want to know why the first example causes the core dump but the second runs perfectly? This is my cals...
Using delete rather than delete[] on a pointer allocated with new[] exhibits undefined behavior. "Seems to work" is one possible manifestation of undefined behavior; "program crashed" is another. Practically speaking, the reason for the difference in behavior on a typical implementation is this. For an array of class t...
65,550,780
65,550,913
Use same name for class member and constructor parameter
Say I have a class with a constructor as follows. // C++ class Person { int age; Person(int a) { age = a; } }; Is there a way to use age instead of a in the constructor's attribute? It would make the code easier to read. In Python I can do it with: # Python class Person: def __init__(self, ...
In general you should use the member initializer list to initialize members. This list is a special case where there is no ambiguity between a member and a parameters name and there is no shadowing: class Person { int age; Person(int age) : age(age) {} // member(parameter) } Whether you rely...
65,551,389
65,551,425
Values mixing between parameters problem in C++ (Codeblocks)
enter code hereI'm trying to make something in c++ Codeblocks using GCC/G++/GFortran compiler and GDB debugger from MinGW-W64 project and something weird is happening. The values got mixed between parameters.(front1[0] takes the value of idk[0]).I tried to change the names of the parameter but same happens. What I shou...
you defined arrays of 0 elements, you need arrays of 1 element to be able to use the index 0 without undefined behavior. Do not confuse the size and the value of the higher index which is the size minus 1 So char idk[1], front1[1], ... to define arrays of 1 character, and for instance front1[0]='*'; to set the first ...
65,551,482
65,551,550
Couldn't find make, how can I solve this?
I have this output: make: The term 'make' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + make --directory=".output\" + ~~~~ + CategoryInfo ...
Supposing make is installed. You need to add to $path the location of make. You can to this in settings/system properties/environment variables; you can do it in system variables or user's. You can verify it is in your path with Get-command make. If you're using the included WSL make (gmake for GNU/linux, typically in...
65,551,590
65,551,824
std::tuple unpack over multiple arguments
I have a function taking pairs of (argument type, data ptr) as a variadic list (C function). I would like to unpack the tuple into that function as follows: foo(TypeIndex<std::tuple_element_t<I, Tuple>>(), &std::get<I>(tuple)); thus I wrote a following function: template<typename Tuple, size_t ...I> void doUnpack(Tuple...
The following does what you want: #include <tuple> #include <iostream> template<typename Tp> int type() { return 0; } template<typename Tuple, size_t... I> auto doUnpack(Tuple const &tp, std::index_sequence<I...>) { auto fun = [](auto &&...args) { (std::cout << ... << args) << std::endl; }; std::apply(fun...
65,551,760
65,553,324
How to create C++ API that can accept both Unix and Windows headers?
I'm building an API for serial port hardware, and I want this API to work on both Unix and Windows systems. In Windows I have used <window.h> and in Unix I have used <unistd.h>, <termios.h> and <fcnt1.h> Is there away to make the person who uses my API to decide which OS he's using and then use the API? or should I bui...
Typically you'd start with a single header that defines the user's interface to the common functionality. This is undoubtedly somewhat different from what you've designed, but something on this general order: class SerialPort { class Configuration { int bps; enum FlowControl { NONE, SOFTWARE, HAR...
65,551,801
65,551,944
C++ ifstream reads a non existing newline at the end
I made a basic C++ program to read a one line text file that does not include any newline character which looks like this: ifstream ifs; ifs.open(filename); char c; int cint; while (ifs >> noskipws >> c) { cint = c; cout << "'" << c << "' = " << cint << endl; } The thing is; while it reads everything that I wa...
you certainly have a newline at the end of your input file using : #include <iostream> #include <fstream> using namespace std; int main() { ifstream ifs; ifs.open("/tmp/i"); char c; int cint; while (ifs >> noskipws >> c) { cint = c; cout << "'" << c << "' = " << cint << endl; } return 0; } comp...
65,551,813
65,552,014
Determining if pointer-to-const points to const object?
Is there anyway to determine if a pointer-to-const points to a const object? bool is_const_object(const int* p) { return ???; } int main() { int x = 42; const int y = 43; assert(!is_const_object(&x)); assert(is_const_object(&y)); }
No, there isn't a way. C++ does not store runtime dynamic information about something being const. C++ does not know statically within the function if the data is really const or not. There are a few cases where it can be done with limitations. You could add your own dynamic runtime information to every const instan...
65,552,564
65,562,441
make action if up to date
I have a makefile used by GNU Make 3.81 running on windows and with each build I pass to the compiler a define giving a version number. The version number is obtained from a file and incremented at the start of the makefile using a perl script with the -get option. The resulting program can then display the build versi...
The current solution bumps the version number (stored in the file) at the start of the build, and rolling it back on failure. However, this may fail in variety of situation, when the scripts does not reach the link time. As an alternative, consider a different solution: New version number will be calculated at the sta...
65,552,593
65,552,866
Parallelizing for-loop and merging the thread private variables
I am a bit confused on how I can use OpenMP multithreading to parallelize this for-loop im working with. In this program section of the program I try to receive data from the arrays x and y; defined as: x = (float*)aligned_alloc(32, sizeof(float) * n); y = (float*)aligned_alloc(32, sizeof(float) * n); Where n is a int...
Most likely the problem is the overhead of the critical regions. #pragma omp critical minX = _mm256_min_ps(minX, TempMinX); #pragma omp critical maxX = _mm256_max_ps(maxX, TempMaxX); #pragma omp critical minY = _mm256_min_ps(minY, TempMinY); #pragma omp critical ...
65,552,639
65,552,702
WM_CLOSE message and application freeze
Having such supers simple Win app: int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) { ... MyRegisterClass(hInstance); // Perform application initialization: if (!InitInstance(hInst...
On WM_CLOSE the window should normally be destroyed with DestroyWindow, like: case WM_CLOSE: DestroyWindow(hWnd); break; In your case you just return without doing anything with that window, so it simple 'freezes'.
65,552,754
65,552,898
Why can i assign a value to a rvalue reference?
I recently started learning about rvalues,lvalues, move semantics and I can't understands some conceps like rvalue refs .. why can I assign a value to a rvalue ref like : int&& x = 10;.. doesn't that mean that an rvalue ref is an lvalue(I tought that a rvalue ref is a rvalue)? If that is true ... what's the point of ha...
why can I assign a value to a rvalue ref like : int&& x = 10 That's not an assignment. That's initialisation. Here, a temporary object is materialised from the integer constant and the reference is bound to that temporary. Same thing can be done with lvalue references to const: const int& x = 10. It cannot be done wi...
65,553,814
65,556,918
How to add mouse double click to ListBox
To this code: https://www.dreamincode.net/forums/topic/163804-microsoft-working-with-listboxes-part-i/ It is displaying list and looping nicely. Sadly my guru never finished his code. So plan would be adding double click detection on a name. How? case WM_COMMAND: { return 0; } Some...
First, according to the documentation: Parameters wParam The LOWORD contains the identifier of the list box. The HIWORD specifies the notification code. lParam Handle to the list box. Remarks This notification code is sent only by a list box that has the LBS_NOTIFY style. So in the first step you need to add this sty...
65,553,890
65,553,989
Arithmetic overflow warning when trying to allocate memory using new
This is my minimal reproducible example. struct Cell { }; void initializeCells(unsigned int width, unsigned int height, unsigned int size, Cell* outcell) { outcell = new Cell[(width / size) * (height / size)]; } int main(int argc, char* argv[]) { Cell* cells = nullptr; initializeCells(1200, 600, 10, cells...
This creates a size_t from an unsigned int, then multiplies the size_t with an unsigned int. outcell = new Cell[size_t{ width / size } * (height / size)]; Depending on the use of width, height and size you might instead consider making these a size_t.
65,553,985
65,554,088
Accessing element from reference to vector of pointers
I have a reference to a vector of pointers, as follows: std::vector<Object*>& objects; How can I access Objects from this vector?
That objects is a reference has no direct bearing on the question -- you use a reference in exactly the same way you use a simple identifier for the same object. Thus, you can select an individual element of the vector by any of the normal means, such as by index, by iterator, or whatever. The result is of the vector'...
65,554,091
65,554,271
C++ Networking: Request method POST
I'm trying to communicate with some server. To get username (with permissions), I need to do something like registration: HTTP request method POST send json-like body containing {"devicetype": "devicename"}. O tried to do it with ASIO library. asio::error_code ec; asio::io_context context; asio::ip::tcp::endpoint endpo...
What you have shown is not a properly formatted HTTP request. There is no Body header in HTTP. The JSON data needs to go after the \r\n\r\n that terminates the headers. And you need to add Content-Type and Content-Length headers so the server knows what kind of data you are posting and how large it is. Try this instead...
65,554,336
65,554,495
Function not returning any value in following code
#include <bits/stdc++.h> using namespace std; int myfunc(int n, int m, int k, int arr[], int arr1[]) { int x = 0, y = 0; for (int i = 0; i < n; ++i) { if (arr[i] > k) { x += 1; } } for (int i = 0; i < m; ++i) { if (arr1[i] > k) { y += 1; } ...
Your confusion seems to be arising from a misunderstanding of what it means to return a value from a function versus printing the value inside the function. Consider the following function that prints the right answer: void f() { std::cout << 42; } Fine, this works and can be called like f();, and it prints the val...
65,554,562
65,554,930
flip set of pixels with respect to a given row coordinate
I'm trying to write a program that flips a region(represented as a set of Segments) with respect to a given row coordinate. I don't know c++ well, so I got some errors I don't know why they appeared and how to fixed them. Here is what I got so far: struct Segment { int row; int colStart; int colStop; }; st...
This line for (std::vector<Segment>::reverse_iterator it = region.rbegin(); it != region.rend(); ++it){ needs to be changed to for (std::vector<Segment>::const_reverse_iterator it = region.rbegin(); it != region.rend(); ++it){ since region is a const container. Thus calling begin/rbegin/end/rend on const contai...
65,554,697
65,556,588
Global variable optimisation in anonymous namespace
Here is an example: namespace { int a = 0; } int main() { a = 1; } GCC and Clang optimized a = 1 out, but MSVC didn't. Example of output from GCC: main: xor eax, eax ret Another example: namespace { int a = 0; } int main() { a++; } None of compilers optimized out a++: GCC, Clang...
For your first example, MSVC will also optimize out the global (and writing to it) if you use the /GL flag. Unfortunately, when you do so, it doesn't produce assembly language output, so Godbolt will just tell you the output file is missing. To examine the code, you have to generate an actual executable, then disassemb...
65,555,207
65,556,443
Extracting the simd-vector length from a template parameter to use for a local type
I'm struggling to find the right C++/clang utterance to solve the following problem. Notice first that the following doesn't overflow the unsigned short because of integer promotions before the arithmetic happens. unsigned short testme = 16320; testme = testme * 257 / 64; The result is 65535. But when I use simd to tr...
So clang lets you pattern match on attributes and generate new attribute-modified types in templates. So we can do this. First pattern match on the simd width attribute: template<class T> struct get_simd_width; template<class T, std::size_t x> struct get_simd_width< __attribute__((__ext_vector_type__(x))) T >: std::...
65,555,216
65,555,283
Constrained auto doesn't work for msvc function parameters?
I have decided to go all out and use C++ 20's concepts in a library I am starting. I have tested the following code on GCC trunk and it runs just fine, however fails on MSVC 16.5.4 with C++20 enabled. Is this feature not confirmed by the standard, has it not been implemented yet, or is my version out-of-date> Thanks! #...
MSVC's compiler, as of 19.28 doesn't support constrained auto. Live example. Note that the compiler version is independent of the MSVC suite version. The compiler major version indicates an ABI change, and minor an improvement. The suite version is more tied to marketing-ish releases. Constrained auto did make it int...
65,555,351
65,555,389
Why should you give parameters names in function declaration?
I know that ommiting the parameter name in a function is sometimes used to indicate that that parameter is potentially unused. But is there a good reason why one should names to the parameters in a header function declaration in the first place? Why is int sum(int a, int b); in any way better than int sum(int, int); ...
Function declarations describe the interface, i.e. how the function is meant to be used. Consider the following example: void rotate(int x, int y); as opposed to: void rotate(int height, int width); These declarations have the same number and type of parameters, but the semantics of the parameters are very different....
65,555,475
65,555,527
A C++ large integer precision question during multiplication
If I run the following program: #include <iostream> int main() { using namespace std; uint64_t f12 = 18446744073709551568; uint64_t f3 = 2; uint64_t f123 = f12 * f3; cout << f12 << endl; cout << f3 << endl; cout << f123 << endl; return 0; } I get as output: 18446744073709551568 2 1844674407...
You can chalk it up to "extreme coincidence". 18446744073709551568 in binary is FFFFFFFFFFFFFFD0 We all discovered when we learned binary math that multiplication by two is equivalent to a left shift, which becomes: FFFFFFFFFFFFFFA0 Note that D0 is 11010000 in binary, with the high bit set, so shifting left the lowe...
65,555,483
65,567,424
Disabling OpenACC implicit pragma generation with pgc++ compiler
I'm using the pgc++ compiler on some C++ code that uses OpenACC directives, and I was wondering if there is a compiler option to disable implicit pragma generation that is performed when compiling code if the user leaves the required pragmas out. For example, when compiling my own code with the -Minfo=accel flag, I see...
This is the default behavior as defined by the OpenACC standard when a user does not use data clauses on a compute construct (parallel/kernels). A runtime check is performed and if the data is already present on the device, no action is performed. If the data is not on the device, then the data is copied. You can add...
65,556,044
65,582,933
How to use testing::_ in an EXPECT_CALL, excluding 2 values?
I have a method, which inside calls a method which returns bool value - in this question let's name the method: bool IsFilled(int value) Now in another method which I am testing this is being called multiple times: if (IsFilled(0)) { if (IsFilled(1)){ ... } else { ... } } for (int i = 1; i < rang...
TL;DR - swap the order of EXPECT_CALLs: EXPECT_CALL(adapter, IsFilled(_)).Times(otherCalls).WillOnce(IndexOtherResults); EXPECT_CALL(adapter, IsFilled(1)).Times(oneCalls).WillOnce(IndexOneResults); EXPECT_CALL(adapter, IsFilled(0)).Times(zeroCalls).WillOnce(IndexZeroResults); This works because of GoogleMock rules fo...
65,556,892
65,556,911
C++ class template not compiling when passing parameters to constructor
I am attempting to implement some small generic data structures as review and to learn more c++, but am running into problems with getting my basic template class to compile. Header file: template <class T> class ArrayList { public: ArrayList(T dataToAdd[]); }; C++ file: #include <iostream> #include "arra...
You have to implement the definition of template classes directly in the header file.
65,557,538
65,567,245
OpenGL - Render to single channel texture?
I'm trying to render to a single channel texture attached to a framebuffer but its not working. I create the texture using a sized format: glCreateTextures(GL_TEXTURE_2D, 1, &entityTexture); glTextureStorage2D(entityTexture, 1, GL_R32F, viewport.size.x, viewport.size.y); glTextureParameteri(entityTexture, GL_TEXTURE_MI...
Changing to layout(location = 3) out vec4 gEntityID; and assigning a vec4 with alpha 1.0 and the single channel value to the red component seems to have done it.
65,557,588
65,557,596
(C++) How to read two columns of data from .txt file into two vectors?
I have been trying to read data from a text file which contains float data in two columns 1 2 3 4 4.5 6.5 2 4 Now, I have tried the methods of several questions in stackoverflow like this, this and some others. The final code that I have written is: #include<iostream> #include<fstream> #include<string> #include<vector...
(Update): All you need is: float ai, bi; while (file >> ai >> bi) { a.push_back(ai); b.push_back(bi); number_of_lines++; }
65,557,839
65,574,590
Netbeans C++ Weird output
#include <iostream> using namespace std; int main(){ cout<<"Hello World!"<<endl; } I recently installed netbeans 12.0 and when I compile the code above, it says some weird words and numbers and a letter 'H'. Also the words using, namespace, cout, and endl are underlined and when I hover to it, it says: unable t...
As @user4581301 specified that the programs runs and immediately quits so you are not able to see anything. So, we need something to pause the program. #include <iostream> using namespace std; int main(){ cout<<"Hello World!"<<endl; system("pause"); }
65,558,367
65,558,434
c++ Copy Parameter Value
I want to specify the value pointed to by the parameter after dynamic memory allocation. But I get an error. How can I solve this? class Point { private: int *x; public: Point(int *a) { x=int new; x=a; } ~Point() { if(x) delete x; } void print() ...
The error is just a small typo: you have to write new int instead of int new. However, your code has a logic error, and that's this line: x = a; As x and a are both pointer types, you assign the pointer - and not the value it points to - to x. This way, the original value of x - the integer which was just allocated - ...
65,558,446
65,558,643
this is showing wrong output when i am giving this more then one test cases
this is codechef January challenge's first problemcodechef. When i am giving more than one test case ,it is giving wrong output. and when i am giving one test cases it is going right. my code:- #include<iostream> using namespace std; int long long N; int main() { i...
Your output is in the wrong place, it should be inside the test case loop not after it. You also need to print a newline after every result Your code is like this for(j=1;j<=t;j++) { ... } if(sum>d) { cout<<d; } else cout<<sum; but it should be like this for(j=1;j<=t;j+...
65,558,590
65,562,625
Is there a difference between a = -a and a *= -1 for floats in c++?
For types like signed int and float and double etc? Because, if I remember correctly (a very big if), it's a matter of flipping a bit and I thought whether there's an explicit operation that would do it to make code run faster? Edit: okay, just for floating-point types, the int parts were me forgetting to use my brain,...
-a and a * -1 are different operations.1 Nothing in the C++ standard overtly requires an implementation to produce different results for them, so a compiler may treat them as identical. Nothing in the C++ standard requires an implementation to treat them identically, so a compiler may treat them differently. The C++ st...
65,558,948
65,559,140
Prime number checker with two variable
int main() { int n, i = 2; cin >> n; if (n == 1) cout << "Not Prime"; else { while (n > i) { if (n % i == 0 && i != n) { cout << "Not Prime"; i++; break; } else { ...
You can implement the program like this: int main() { int n; std::cin >> n; for (int i = 2; i < n; ++i) if (n % i == 0) { std::cout << "Not Prime"; return 0; // end the program } std::cout << "Prime"; // must be prime if reached here } You can improv...
65,559,246
65,559,457
When does the 'const' qualifier guarantee the variable to be a constant expression?
As far as I know, the const qualifier in C++ basically declares internal linkage, and sometimes it allows the variable to be used as a constant expression so that it can be placed into array bounds, switch cases, etc. But apparently this is not always the case, and I have no clue regarding the proper usage of const and...
The only time const means the same thing as constexpr in the declaration of a variable, is when the variable is of integral or enumeration type. In addition, the initializer of this variable declaration must be a constant expression. e.g. const int n = 42; // same as constexpr // type is i...
65,559,482
65,563,749
Visual basic WPF load ATL C++ dll program exit when return String type
I'm using VB.net WPF with dll made with ATL for this project but every time I run dll function, program exit with no error please let me know why is not working and how to fix it. c++ function extern "C" __declspec(dllexport) BSTR __cdecl sprint(LPSTR str1, LPSTR str2) { TCHAR test[100]; sprintf_s(test, 100, "...
In COM programming, a BSTR is a special LPWSTR which is allocated by SysAllocString, freed by SysFreeString. The characters are preceded by the string length, at offset -1. That means you can pass a BSTR to all functions that expect an LPCWSTR L"helloworld" is a C++ literal, which happens to almost match the LPWSTR typ...
65,559,810
65,559,862
Inheritance with interfaces
I'm currently trying to wrap my head around the basics of C++ inheritance. Consider the following piece of code: // Interfaces class InterfaceBase { public: virtual void SomeMethod() = 0; }; class InterfaceInherited : public InterfaceBase { }; // Classes class ClassBase : public InterfaceBase { public: virt...
You are encountering a diamond problem. The solution is to use virtual inheritance (Live), to ensure that only one copy of base class members are inherited by grand-childs: // Interfaces class InterfaceBase { public: virtual void SomeMethod() = 0; }; class InterfaceInherited : virtual public InterfaceBase { }; //...
65,559,914
65,560,141
Window won't update while changing its shape
I have successfully created a window but it wont update the window to change its shape and color. I have tried to solve this for days an appreciate any help. The program is meant to show an orange window that can be reshaped. It would also help, if you could check the code by compiling it in Visual Studios. Here is the...
The line: buffer_width = rect.left - rect.right; => buffer_width = rect.right- rect.left ; You should draw in the WM_PAINT message, case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hwnd, &ps); unsigned int* pixel = (unsigned int*)buffer_memory; for (int y = 0; y < buffer_high...
65,559,969
65,560,029
C++ getnstr causes odd segmentation faults
So I'm currently working on a project which uses ncurses for output and input. In this program, the user should be able to, for example, write his name. The issue I'm having is with getnstr, as it can cause some very weird and unexplainable segmentation faults. For example this code right here works fine as it is: #inc...
You're asking to read 10 characters into a pointer that points nowhere in particular. Try either char word[10]; or char *word = malloc(10); So why does that sometimes work? Your uninitialized pointer variable may have pointed to a writable memory area by accident. You were overwriting something somewhere, which may not...
65,560,265
65,560,391
Passing a pointer by value - allocating memory in the function
When I want to assign a memory to the pointer in the function I have to pass the pointer by reference (or pointer), for example: void fun(int*& ptr) //or int** ptr { ptr = new int(1); } int* ptr = nullptr; fun(ptr); int x = *ptr; I have noticed that when I have a struct which contains a pointer passing by value ...
The type you are trying to return to the caller is int*. Using a typedef should help: using IntPtr = int*; void fun(IntPtr& ptr) // works { ptr = new int; } void fun(IntPtr* ptr) // works { *ptr = new int; } void fun(IntPtr ptr) // won't work { ptr = new int; } struct Foo { IntPtr ptr; }; void fun(Fo...
65,560,634
65,561,372
Monte Carlo simulation runs significantly slower than sequential
I'm new to the concept of concurrent and parallel programing in general. I'm trying to calculate Pi using Monte Carlo method in C. Here is my source code: #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> int main(void) { long points; long m = 0; double coordinates[2]; double d...
There are two sources of overhead in your code namely, the critical region, and the call to the rand(). Instead of rand() use rand_r: I think you're looking for rand_r(), which explicitly takes the current RNG state as a parameter. Then each thread should have it's own copy of seed data (whether you want each thread t...
65,560,644
65,561,134
Why can't gcc deduce the return value type after parsing the first return clause?
Why this code is not valid? auto f() { if (true) return 0; return {}; } After parsing 0, I think gcc should know that the return type of function f was int, but it still interpret the {} as the initializer_list when parsing the final return clause, why?
From function#Return_type_deduction if there are multiple return statements, they must all deduce to the same type and If the return statement uses a brace-init-list, deduction is not allowed: Which prohibit such construct. Once a return statement has been seen in a function, the return type deduced from that stat...
65,560,775
66,349,120
CMake - New Boost version may have incorrect or missing dependencies and imported
I am using CMake version 3.19 and Boost version 1.75 in Windows Server 2008. I also added environment variable "BOOST_ROOT" as shown below : However, I got the warning below while using CMake: CMake Warning at C:/Program Files/CMake/share/cmake-3.19/Modules/FindBoost.cmake:1204 (message): New Boost version may have ...
These warnings simply mean that your CMake version is older than your Boost version. The CMake devs can update their dependency lists only after a new Boost release, so you need to update to a CMake version that was released after boost 1.75. Look at the Boost version history: https://www.boost.org/users/history/ Boos...
65,561,102
65,562,911
Selecting item from array of char arrays in Arduino
I'm trying to write a function to play a random track from a predefined list of tracks from an Adafuit board connected to an Arduino Nano by serial. I've put the list of tracks in an array of char arrays and am having difficulty getting it to select an item from the array. char T00[20] = "T00 OGG"; char T01[20] = "...
Here you seem to be trying to copy a string/array by assigning it. char trk[20] = rndTracks[r]; That does not work with C-like arrays of char. Numerous ways exist to do the copying you try. E.g. using C++ strings, or strncpy()... But what you probably really want to do is to simply skip the copying and just output via...
65,561,144
65,561,439
How to print a square in c++
I want to make a function to print square like the following output. user enter the side of square (N). The total length of N is must an odd. int main() { int n, i, j; cin >> n; for (i = 1; i <= n; i++) { for (j = 1; j <= n; j++) { if (i == 1 || i == n || j == 1 || j == n || ...
add || i <= j && i + j - 1 >= n #include <iostream> using namespace std; int main() { // your code goes here int n, i, j; cin >> n; for (i = 1; i <= n; i++) { for (j = 1; j <= n; j++) { if (i == 1 || i == n || j == 1 || j == n || i == j || i + j - 1 == n || i <= j ...
65,561,224
65,563,777
stringstream: taking multiple ints in a string and returning those to vector
I am taking a string and using stringstream to pull out the ints in the string and then push those into a vector. My problem is doing this when I don't necessarily know the exact number of ints in the string. The string could be "23,45,68" or it could be "-1,10,15,-22,199,12". My code is below: #include <sstream> #incl...
I realised that the while loop was ending when it hit the "," in the string. In the loop I added code to drop the comma into a char holder "ch" This resolved the problem: #include <sstream> #include <vector> #include <iostream> using namespace std; vector<int> parseInts(string str) { //cout << "str is " << str; ...
65,561,520
65,564,476
Transform random integers into range [min,max] without branching
I got hold on an SUPER-FAST algorithm that generates an array of random bytes, uniformly. It's 6 times faster than c++ uniform distribution and mersenne-twister of std library. The count of an array is divisible by 4, so it can be interpreted as array of integers. Casting each entry to an integer, produces values in th...
But how can I transform these integer values to lie between my own [min, maximum]? Since the range may not be a power of two, bitmasking is out, but you found that out already. Modulo is also out, it does not exist as a native operation in AVX2 (and even if it did, that wouldn't necessarily make it efficient). There ...
65,561,573
65,563,230
C++: Remove object without calling destructor
For those unfamiliar with polymorphic memory resources (PMR), std::pmr::monotonic_buffer_resource: "the class std::pmr::monotonic_buffer_resource is a special-purpose memory resource class that releases the allocated memory only when the resource is destroyed. It is intended for very fast memory allocations in situati...
t.niese had a great suggestion in the comments, which was to change the allocator of the containers. After all, our issue is not with the container, but that the allocator thinks that it needs to call do_deallocate. We can simply copy the code of boost's polymorphic_allocator and replace deallocate with a no-op. You ca...
65,562,113
65,563,102
How can I use C++ concepts with type_traits?
I want to abstract type interfaces and I am having a hard time to decide between the two C++ means of concepts and type_traits. Consider the follow scenario: template <typename T> int foo(const T& t) { return t.size() + t.size(); } The type T is requested to provide int T::size() const. For creating better error messa...
You might also constraint your traits: template <typename T> concept SizeHaving = requires(const T& t) { t.size(t); }; template <typename T> struct Type_traits { auto size(const T& t) requires(SizeHaving<T>) { return t.size(); } }; template <typename T> concept TraitSizeHaving = requires(T t) { Type_trait...
65,562,628
65,563,104
Is it possible to assign to an array from an initializer list?
I am trying to make it possible to assign to an array from an initializer list in C++, if this is possible how to do it? may be the new versions of C++ needs to achieve it or not? Code: #include <iostream> #include <array> using namespace std; int main() { int arrayName_A[5]; arrayName_A = {1,2,3,4,5}; fo...
Arrays do not have the assignment operator. Arrays are non-modifiable lvalues. That is you may not write for example int a[3] = { 1, 2, 3 }; int b[3] = a; or int a[3] = { 1, 2, 3 }; int b[3]; b = a; You may set each element of an array with a value from an initializer list using the range-based for loop as it is sho...
65,562,666
65,573,792
Converting Char array to TimeStamp in C++
I have char start_time[40] = "2020-04-01 12:00:00"; How can I convert the char array to timestamp in C++ without using strptime?
You can try this: #include <time.h> #include <stdio.h> #include <stdlib.h> #include <iostream> int main(void) { const char T[] = "2020-04-01 12:00:00"; time_t result = 0; int year = 0, month = 0, day = 0, hour = 0, min = 0,sec=0; if (sscanf(T, "%4d-%2d-%2d %2d:%2d:%2d", &year, &month, &day, &hour,...