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
68,905,086
68,906,498
How can i parse whitespace, equal and quotes to vector in C++?
Is there any I could parse space and quotes to vector? like for example: #include <iostream> #include <vector> #include <string> using namespace std; void ParseFunc(string str, vector<string>& output) { //How can I do it? } int main() { string command = "hello world=\"i love coding\" abc=123 end"; vector<st...
This is trivial with std::regex_iterator: string command = "hello world=\"i love coding\" abc=123 end"; std::regex words_regex(R"([^ ="]+|"[^"]+"|=)"); for (auto it = std::sregex_iterator(command.begin(), command.end(), words_regex); it != std::sregex_iterator(); it++) { std::string token = (*it).st...
68,905,125
68,905,562
Palindrome program not returning correct answers
I am currently coding in C++ and am wanting only take notice of lowercase letters and numbers. My problem is that when I enter a string containing integers and characters (such as a lowercase letter), does not return the correct answer for and ODD length (of the array) above the value of 3. For instance, if I was to en...
I have a much better code. Usage of any data structure template does not indicate that it is a good code. If your target is to check if a string is palindrome including alphanumeric characters please refer to the following code. I have shared the screenshots as an example :- #include <iostream> #include<string>...
68,905,710
68,905,741
Is there any way to avoid "Debug Assertion Failed" Window in C++?
This is the window that I want to prevent from showing when executing: I know it is a bad practice but I am currently working on a code that collects all these exceptions and displays them in a different way, it would simply need the "Ignore" option to be executed automatically since the code is programmed so that rig...
You should be able to #define NDEBUG which ought to suppress this. Secondarily, try undefining _DEBUG as parts of the Windows API use that. That said, I wouldn't do this: assertions are really there as a last resort and therefore are meant to help the programmer. If you want to handle an assertion in a different way...
68,905,757
68,905,840
why i m getting [Error] no matching function for call to 'car::car()'
I have created two objects of class car with two member variables a and b....i want to make a new object whose a and b are the product of a and b of the objects that I created earlier. #include<iostream> using namespace std; class car { private: int a,b; public: car(int x,int y) { ...
Have a look at this documentation. https://en.cppreference.com/w/cpp/language/default_constructor From this it follows that a default constructor is not added to your class automatically if you define another constructor. Which you did. You will have to add a default constructor manually. eg. class car { public: ...
68,906,564
68,906,677
how to convert C-style compile-time arrays to std::array
In our sources we have often something like this: static const int g_numbers[]{ 1, 2, 3, 4, 5}; static const struct { const int m_nID; const char* const m_pszName; } g_collection[] { { 1, "Max" }, { 2, "Fabian" }, { 3, "Martin" }, … }; How to transform those compile-time arrays to moder...
You have a choice. Either use template argument deduction, or specify the arguments yourself. Using template argument deduction: static constexpr std::array g_numbers{1, 2, 3, 4, 5}; struct g_collection_element { int m_nID; char const* m_pszName; }; static constexpr std::array g_collection{ g_coll...
68,906,605
68,907,126
C++ std::chrono::high_resolution_clock time_since_epoch returns too small numbers. How can I get the correct time since 1970 in microseconds?
I am trying to write a function, which will return the current time in microseconds since 1970. While a debugging I noticed, that the returned numbers are too small. For example: 269104616249. I also added static_assert to check the returned value type is int64_t, which i big enough to hold 292471 years in microseconds...
There are three chrono-supplied clocks in C++11/14/17 (more in C++20): system_clock: This measures Unix Time (time since 1970 excluding leap seconds).1 steady_clock: Like a stop-watch. Great for timing, but it can not tell you the time of day. high_resolution_clock: This has the disadvantages of system_clock and...
68,906,777
68,913,924
Why this code outputs garbage value after swapping the values?
Take two numbers as input and swap them and print the swapped values.You do not need to print anything, it has already been taken care of. Just implement the given function.And the functions looks like this. pair < int, int > swap(pair < int, int > swapValues) { int c; c=swapValues.first; s...
Just replace the line cout<<swapValues.first<<" "<<swapValues.second<<"\n"; with return swapValues; As stated in your question You do not need to print anything, it has already been taken care of.
68,907,375
68,909,227
Can't call function with variant parameter using initializer_list
I'm not so skilled in using std::variant and couldn't completely understand all constructor cases. using map_type = std::multimap<std::string, std::string>; using union_type = std::variant<std::string, map_type>; void foo(union_type) { ... } void foo2(map_type) { ... } int main() { foo({ {"key", "val"} }); // give...
Template argument deduction for multimap constructor template fails because braced-init-lists do not have a type. You have to provide this information explicitly, creating an unnamed temporary object which in most cases will exist in compile-time only (for your code): foo(map_type{ { "key", "value" } });
68,907,492
68,907,570
How it works when assigning a pointer * to a pointer **?
I am learning about pointers. when i practice assigning pointer * by pointer ** then p_to_p = ptr but *p_to_p != *ptr. Here is my practice code #include <iostream> using namespace std; int main() { int value = 100; int *ptr = &value; int **p_to_p = (int**)ptr; cout << p_to_p << " " << ptr << ...
int **p_to_p = (int**)ptr; Here, you reinterpret the value of ptr as a int**. All object pointers can be reinterpreted as pointers of other types, but you generally may not indirect through such reinterpreted poiters except for rare cases. *p_to_p This is not such exceptional case. The behaviour of the program is...
68,907,608
68,907,679
Why there is no operator-> in std::array
I am writing a std::array class as a little exercise, during which I found out that std::array does not implement operator->. Thus for arrays the following is allowed struct S { int s; }; S c[2]; c->s = 2; but for std::array this is not possible struct S { int s; }; std::array<S,2> cpp; // cpp->s = 2; // does not com...
c->s works because a raw array like c[2], automatically decays to a pointer in expressions. So c->s is equivalent to c[0].s. An object such as std::array does not decay to a pointer and provides no -> or T* overloads, hence cpp->s does not work. std::array [is] not fully compatible to a C-array Fortunately not! It's...
68,907,684
68,907,718
Is it possible to combine AddressSanitizer and ThreadSanitizer into one build?
Or do I have to use separate builds? The -fsanitize flag only allows for either address or thread but are multiple allowed? Regards
No, it's not possible to combine AddressSanitizer and ThreadSanitizer into one build (but other combinations are possible). You need multiple builds -fsanitize=address Enable AddressSanitizer, a fast memory error detector. Memory access instructions are instrumented to detect out-of-bounds and use-after-free bugs. The...
68,908,329
68,908,387
Determine in which direction does a 2D vector face compared to other 2D vector
Here I have two vectors A and B, I want to determine in which direction does B face compared to A, so imagine A vector as screen devisor to two parts, left and right part and imagine B as just a 2D point in whichever left or right part, which part we don't know and thats what I want to determine. How do I go about doin...
Calculate cross product of vectors A and B. Sign of result show direction of vector B relative to vector A cross = A.X * B.Y - A.Y * B.X
68,908,663
69,232,879
cfapi: CfDehydratePlaceholder seems to be stucked
My target is, that files can be hydrated or dehydrated on user request via the Explorer "free up space" or "Always keep on Device" ContextMenu entry. In case I create a new placeholder file that is dehydrated from the beginning, everything works and I can hydrate it via the callback mechanics. But the way around does n...
I had a misunderstanding of the whole API and here is how I understand the API now, to help other people, who are struggling with it. You have to register your sync root and connecting your app to it. In case of connecting it, you will receive a CF_CONNECTION_KEY, which is needed to communicate with the virtual filesys...
68,908,988
68,913,529
How to prevent calling of MPI_Finalize() within class destructor?
I have a class that creates a new MPI_Datatype in its constructor and then deletes it in its destructor. However, the presence of the deletion of the custom datatype somehow triggers the calling of MPI_Finalize() within the destructor. #include <cstdio> #include "mpi.h" class foo { public: MPI_Datatype M_INT; ...
@VictorEijkhout suggested the following solution in his comments. The idea is to create a communicator object which calls MPI_Init and MPI_Finalize in its constructor and destructor, then pass that object to other functions or classes for further manipulation. #include <cstdio> #include "mpi.h" class MPI_Obj { public:...
68,909,264
68,910,976
SIGSEGV Segmentation Fault when dereferencing a pointer
I'm aware that there are several similar questions to this one already, but I've read through them and none of them seem to cover my specific problem... I'm trying to dereference a public pointer from a struct, but it's throwing a SIGSEV Segmentation fault, even though the pointer does point to a value It prints 1 & 2 ...
This allocates a std::vector with one element of BaseEntity environment = new std::vector<BaseEntity>(1); // this is where init then another element of Grass is appended environment->push_back(Grass()); // adding something to it works fine but maybe this is the first problem, since the vector only holds BaseEntitys, ...
68,909,488
68,910,548
No output in C++ program despite no errors and complete execution
I wrote the following recursive program in C++ to sort an array using QuickSort Algorithm, but I am not getting any output(while I should have received output as space separated array because of cout) despite the program execution being completed. I am relatively new to C++(not to programming) and wasn't able to find a...
I already place comments besides the bugs you made. #include <cmath> #include <vector> #include <iostream> #include <algorithm> using namespace std; int partition(int a[], int low, int high) { int pivot = a[high]; int x = low; int y = high - 1; // should be high - 1 while (x <= y) // this must be less...
68,909,833
68,911,145
Determining the replace string based on the match in a or regex
I have a regex that contains an or statement something like re2::RE2 regex = "(foo)|(bar)" Now, I want to replace all occurrences of foo to bar and all occurrences of bar to foo. In python I can pass a function to the regex function and do the following: def determine_replace_string(match: re.Match): if match.group...
The closest answer I can give you is this one. There is std::regex_replace but it can't swap groups. So I just use a three step swap approach. Probably not the fastest way to do it, but quite readable (no if's) #include <cassert> #include <string> #include <regex> int main() { std::string str{ "puzzlefoobarfoobarp...
68,910,001
68,910,086
Replacing/refactoring of naked pointers
I want to replace traditional naked pointer usage in a class inheritance situation. Example for what I mean: #include <iostream> #include <vector> #include <memory> using namespace std; class Base { public: void doBaseStuff () { cout << "base stuff\n"; } }; class Derived:public Base { public: void doDeri...
You can use std::unique_ptr instead of std::shared_ptr (it is recommended indeed, because ownership is clearly handled in your application, and not left unspecified to a kind-of garbage-collector), but you have to move them into the vector in order to transfer (unique) ownership. vector<unique_ptr<Base>> baseCollectio...
68,910,141
68,910,250
Const std::filesystem::path reference constness is not respected, is this something I did wrong?
I'm working on a file traversal project, and I want to keep track of the current item that's being examined, so I have an external filesystem::path CurrentItem value that I change on each level/step of traversal to keep up to date. I'm using a recursive function that takes a const filesystem::path& to traverse through ...
This is what happens when you use modifiable global variables. The object referenced by thisPath cannot be modified by the thisPath variable, but if there is another way to access that object, then it can take on different values. For example, if it is a reference to a global variable, if you modify that global variabl...
68,910,200
68,910,627
Using concepts in an unevaluated context gives inconsistent results
Consider the following useless concept C: template<class T> concept C = static_cast<T>(true); If we pass an arbitrary type to C in an unevaluated context, then all three compilers will compile successfully: struct S {}; decltype(C<S>) x = 0; But if we pass int to C in the unevaluated context: decltype(C<int>) y = 0; ...
Concept names do not work on the basis of evaluating an expression as we would normally think of it. A concept name resolves to a boolean that tells if the constraint-expression is satisfied or not: A concept-id is a prvalue of type bool, and does not name a template specialization. A concept-id evaluates to true if t...
68,910,523
68,910,671
C++ override member access operator for template class and return by reference
Is it possible to override the -> operator in template class and return something by reference? I saw this post: Overloading member access operators ->, .* And there is an example of overriding -> and return by reference, but I can't get this to work with templates. Here's a small example of what I'm trying to achieve:...
If you return a reference, you can't use it in ref->do_something(); which requires a pointer. You'd have to use this cumbersome method: ref.operator->().do_something(); Instead return a pointer - and make it a T* (or const T*), not a Ref<T>*. Example: #include <iostream> class A { public: void do_something() { ...
68,911,701
68,923,257
Communicating Through Protocol Layers With INET Packet
I'm troubling with the reception packet at the receiver side. Please help me to find a way. At the SENDER side, I encapsulate the data packet (which comes from UdpBasicApp through Udp protocol) when it arrives at Network Layer as follows: void Sim::encapsulate(Packet *packet) { cModule *iftModule = findModuleByPath...
Request tags are things that you add to a packet sending information down to lower OSI layers. On receiving end, protocol layers will annotate the packet with indicator tags so upper OSI layers can get that information if needed. You are adding an empty request tag to an incoming packet, so no wonder it is empty. What ...
68,912,145
68,912,700
cmake: compile header-only library into a STATIC library
I'm using VulkanMemoryAllocation, which is a header only library. I want to compile it into a static library using cmake, but I end up with an empty - 8 bytes sized - library file, and a lot of undefined symbols when linking. Here is the relevant part of the CMakeList.txt # The header with the implementation add_librar...
VMA_IMPLEMENTATION is a compile_definition not compile_option. You have to set file language, in addition to target (I think). set_source_file_properties( VulkanMemoryAllocator-Hpp/vk_mem_alloc.h PROPERTIES LANGUAGE CXX ) I would just copy the header so that CMake knows it's C++ from extension, it's just simpl...
68,912,234
68,912,268
Error with parameter constructors: Error C2511
Just starting out with OOP. Experiencing an error when calling the parameter constructor in my source file: Error C2511 'EuroVanillaOption::EuroVanillaOption(const double,const double,const double,const double,const double)': overloaded member function not found in 'EuroVanillaOption' Euro option calculator. What...
The signatures aren't the same. In the header, you pass references. In the .cpp, no references. They need to match. (See the & signs from the header.) It would be weird to pass these as reference. Get rid of the &.
68,912,252
68,912,303
Random string generation function not returning
I have the following function which aims to return a 16 character long alphanumerical string composed of 62 characters char type alphanumeric() function can return (A-Z, a-z alongside numbers 0-9). string random() { string code; int i; srand(time(NULL)); for (i = 0; i < 16; i++) { code[i] = alp...
string code[16] This creates an array of 16 strings. That's probably not what you want. A string is an arbitrarily long sequence of characters. You really only want one string. I don't know what your alphanumeric() method does, but if it returns one string, then you're creating 16 strings with 1 character each. Oh, an...
68,912,393
68,912,678
range function like python but for C++ 17 (double)
I'm trying to create a function that fills my vector with values from beginning to end with a certain step. For type double and C++ 17 version. Any idea how to do this? vector<double> generateRange(double start, double end, double step) { } int main() { // return [10, 10.5, 11,...., 12] auto range = generate...
You can for example write a simple loop to generate vector that you want. However, the range function in python doesn't return a list but a generator, which is much faster. You should be returning a generator (range) in C++ as well instead of returning a vector. Implementing a generator is a bit more advanced. The stan...
68,912,466
68,912,648
How to most concisely initialize std::map using an initializer list that includes a constructor call for the mapped_type
The vector constructor calls in the statement below construct vectors with 50 elements of identical values in each vector as values in the sviMap. The statement repeats vector<int> three times. Is there a more concise way to achieve this overall initialization of the sviMap where vector<int> appears only once in the st...
Strictly speaking, no. You need to have template specialization and two instances of the vector. But if you need to have "this text once", this workaround could work for you: using vi = vector<int>; map<string, vi> sviMap{ {"Leo", vi(50, 101)} , {"Brad", vi(50, 201)} }; Formally, this is not "the statement", but two s...
68,912,578
68,917,579
View QObject's objectName in Visual Studio Debugger
Unfortunately QObject has nothing like a QString m_objectName member visible in the debugger as one might expect. Instead, all of the implementation data is hidden behind opaque pointers. Is there any way to view the objectName at runtime from within the Visual Studio debugger? Background: When debugging a Qt Applicati...
Assuming Debug build (Qt5Cored.dll), add a variable watch as follows: ((Qt5Cored.dll!QObjectPrivate*)myQtObj->d_ptr.d)->extraData->objectName change "myQtObj" to the local variable name of the relevant QObject* (or derived class extending QObject) that you wish to inspect I will leave how to add this to qt5.natvis f...
68,913,251
68,913,313
What happens if the same lock is used to enter different critical sections
I have 2 critical sections in my code . Can I use the same lock to enter different critical sections ? I'm not understanding what can go wrong with this code . void func1(int y, int z) { writeLock.lock() x = y; // critical section 1 writeLock.unlock() ... while(1) { writeLock.lock() my...
If x and myvar are totally disjoint, then you should not use the same mutex for these two critical sections, but one for each instead. Doing so, if one threads is in the x critical section, then no other thread can enter the same critical section, but this other thread can enter the myvar critical section (and converse...
68,913,429
68,914,157
nlohmann json parse error at memory location
I'm making a C++ program that will (eventually) take some information from each page on an api endpoint and then add each page to an array. I'm using cpr as my requests library which is fetching the pages correctly as I need them and then I'm using nlohmann's json library to parse the json page result and then use it l...
Your code: "https://api.hypixel.net/skyblock/auctions?page=" + x; will produce a sequence of strings: "https://api.hypixel.net/skyblock/auctions?page=" "ttps://api.hypixel.net/skyblock/auctions?page=" "tps://api.hypixel.net/skyblock/auctions?page=" "ps://api.hypixel.net/skyblock/auctions?page=" "s://api.hypixel.net/sk...
68,913,457
69,095,920
How do I compile C++ code with Boost on Msys2
I (think) that I have all the libraries installed that I need, e.g., pacman -S mingw-w64-x86_64-boost Also the common development libraries that the msys2 install documentation recommends. I am testing it out with these includes: #include <iostream> #include <vector> #include <string> #include <boost/program_options.h...
Curating HolyBlackCat's comments into an answer that worked for me: Use mingw64 shell, not msys*. (Not sure what purpose the division into multiple binaries serves. Perhaps it matters for other windows versions.) Search for the archive file under /mingw64/lib that matches what you wanted to compile against. So if foob...
68,913,970
68,914,095
Various ways of calling C++ object destructor
A C++ object can be explicitly destructed using destructor call syntax (for non-class types pseudo-destructed). But it looks like that in addition to universally accepted syntax, almost any modern compiler supports its own ways of calling the destructor: using T = int; const int x = 1; int main() { x.~T(); ...
The grammar doesn't allow (1) and (2), so those are illegal. (See [expr.prim.id.dtor] -> id-expression -> unqualified-id -> type-name.) The grammar does allow (3) though (... -> unqualified-id -> decltype-specifier), and I don't see anything in [expr.prim.id.dtor] that would disallow using decltype in this scenario. I ...
68,914,078
68,914,196
How can I create a whole new console window for a new cmd.exe process?
I'm in the process of creating a game engine inside a Windows 10 console. The goal now is to simulate frames. All is good with one exception - I need a way to display logs outside of the program before I get more into frame machine implementation. So I want to have a new process of a console in a new window just to do ...
You can use the CREATE_NEW_CONSOLE or DETACHED_PROCESS flag in the dwCreationFlags parameter of CreateProcess(). See Process Creation Flags: Constant/value Description CREATE_NEW_CONSOLE 0x00000010 The new process has a new console, instead of inheriting its parent's console (the default). For more information,...
68,914,362
68,914,660
How to using boost::unordered_set with custom class?
I'm having a hard time calling hash_value. From this post, I want to apply to vector<vector<E>> where E is a custom object. My codes as follows: struct E; class myclass { private: vector<E> lhs; public: myclass(const vector<E>& v) :lhs{ v } { }; static size_t hash_value(const vector<E>& v) { size_t ...
You are trying to use boost::unordered_set<myclass>, which will internally use boost::hash<myclass>, which will look for a hash_value(myclass) function in the same namespace as myclass via Argument-Dependent Lookup. You made your hash_value() be a non-static member of myclass, so boost::hash will not be able to find i...
68,914,498
68,936,801
C++ : how to use spdlog to print custom class pointer?
I am facing a little problem. I need to use spdlog to log and I have custom classes. And since, spdlog is able to deal with user defined classes, I could use it log my classes. But, I my real application, I would like to feed spdlog with a pointer of my class (because there is polymorphism but it's not the point here)....
The problem comes from the library fmt since version 8 (used by spdlog since version 1.9.0), pointers are no longer supported. A solution can be to use a wrapper class to store the pointer and precise how fmt should deal with it.
68,914,540
68,916,076
Generate .so file by mixing C and C++ for DPI-C
I have several .c and .cpp files that I want to connect to the System Verilog testbench as a single .so shared object file. The approach I took was using separate .o files compiled into a single .so file, which was then added during vcs compilation with the rest of the SV files. gcc -w -pipe -fPIC -O -c file1....
In order to call a c++ function from 'c' the c++ function must be declared with the extern "C" binding, for example: extern "C" void foo(int); or extern "C" { void bar(); } Now you can call foo(3) or bar() from 'c' Also, you do not need an extra 'c' file to define DPI functions in system verilog. You can still use...
68,914,788
69,677,190
Why is my C++ code outputting NSString literals rather than plaintext?
I know this question seems odd, as NSString doesn't exist in C++. Yet, for some reason, when I run the following code: #include <iostream> int main() { std::cout << "Hello, World!" << std::endl; return 0; } I see the following output: @"Hello, World!\r\n" The C functions printf and puts show similar beh...
I figured it out a while ago but I forgot about my own question. In the debug window, it just displays output like that. It only gets formatted like that in debug mode; if I compile it and run the executable from the command line, then it works as expected.
68,914,851
68,914,990
What's the difference between =delete for templates and just using explicit?
I was reading Explicitly defaulted and deleted special member functions, and saw that in order to call only the function f with double and avoid an implicit conversion, one could write this (from the same page): struct OnlyDouble { void f(double d); template<class T> void f(T) = delete; }; Is there a reason wh...
Two things: explicit is not valid for functions so the explicit void f(double); doesn't compile. explicit doesn't prevent implicit conversions of arguments. That is, even if the comparison were between: struct OnlyDouble { OnlyDouble(double d); template<class T> OnlyDouble(T) = delete; }; and struct OnlyDoub...
68,914,859
69,068,288
Multi-thread. Undefined behaviour with two while loops in two different thread
#include <mutex> using namespace std; int counter = 0; mutex m; void thread1() { while(1) { m.lock(); cout << "th1 " << counter << endl; ++counter; if (counter == 300) { m.unlock(); break; } m.unlock(); } } void thread2() { while(1)...
This is non-deterministic because you have a race condition. Every time you unlock the mutex both threads race to lock it again. Also in your code you can increment over 10 and miss the exit condition in thread2 which is not what I think you want. One way you could sync the execution to be what you described (thread1, ...
68,915,236
68,915,301
Error using std::vector of templated variables INSIDE a struct INSIDE a class
I'm trying to do this: template <typename t> class MyClass { struct InnerStruct { std::vector<t> itemList; }; } The compiler does NOT like my trying to use std::vector<t> this way. Is this impossible with C++, or do I need to put some syntax around it? Nothing I try works. The error I get says: e...
Couple of possible errors here. Firstly, make sure you #include <vector>. Secondly, you need a semicolon after the closing brace of your class.
68,915,297
68,915,359
How do I print adjacent list in specific format without using the C++ standard library?
I have an undirected weighted graph: I want to print an adjacent list in the following format: 0--> 1 --> 2 1 --> 0 --> 2 --> 3 2 --> 0 --> 1 --> 4 3 --> 1 --> 4 4 --> 2 --> 3 --> 5 5 --> 4 --> 6 6-->5 This is my code: #include <iostream> using namespace std; int main() { int nodes = 7; int graphList[nodes][...
Since you are able to output the adjacency list alphabetically by the first element, you can simply output the format as you desire with a flag within the inner loop of : cout<<"Adjacent list: \n"; for(int i = 0; i<nodes;i++){ bool flag = true; for(int j = 0; j<nodes;j++){ if(graphLi...
68,915,365
68,924,898
Linux capabilities to launch process as root from a user mode program in C++
I am trying to launch a child-process as root from a non-root parent-process. I am thinking to use capabilities to make that work. What I have tried so far is that, have set the file cap permitted for parent process to cap_setgid,cap_setuid,capkill+p. Then on the same parent process, I am programmatically setting the s...
Try this (parent.cc): #include <iostream> #include <sys/capability.h> #include <unistd.h> int main() { cap_t caps = cap_get_proc(); cap_value_t val = CAP_SETUID; cap_set_flag(caps, CAP_EFFECTIVE, 1, &val, CAP_SET); if (cap_set_proc(caps)) { perror("failed to raise cap_setuid"); exit(1);...
68,915,392
68,915,393
How can I change dpi manifest settings in a premake VS C++ project?
Currently, I call SetProcessDPIAware() but the docs recommend using a manifest: We recommended that you specify the default process DPI awareness via a manifest setting. While specifying the default via API is supported, it is not recommended. Additionally, I find that on some machines calling SetProcessDPIAware() ca...
To change in Visual Studio: Open properties for the Startup Project Manifest Tool > Input and Output Change DPI Awareness to Per Monitor High DPI Aware To change in premake, set dpiawareness inside your project block: project( "ProjectName" ) kind "WindowedApp" dpiawareness "HighPerMonitor"
68,915,503
68,915,526
Is there a way to return a float from int variables in c++ functions?
My program is returning a value of the score array instead of the average. I am guessing the problem has to do with the type conversions. #include <iostream> using namespace std; float average(int length, int array[]); int main(){ int N; cout << "Enter length: "; cin >> N; cout << endl; int s...
When you divide the integer sum by the integer length, you get an integer result. The fact that you store it in a float doesn't change that. You probably want: return (static_cast<float>(sum) / static_cast<float>(length));
68,915,589
68,915,685
What is the actual path in C++ and how do I get the relative path?
Hey guys I am starting to learn C++, and there is one thing I do not understand - what is my actual path? So, for example, in Python, the actual path of xyz.py is where I run python3 xyz.py. But, how does it work in C++? My C++ project looks like this: --build --data --exampleData --src --example1 --include ...
A relative path is relative to the calling process's current working directory, wherever that happens to be pointing at the moment it is used. The working directory can be specified by a parent process. Or change dynamically during the current process's lifetime. So you can't really rely on the working directory being...
68,916,493
68,916,715
Qt: do I need a mutex if there is only one writer thread?
configuration:debug result: program exit with code 0. configuration:release result: main thread infinite loops,wont jump out of the loop(t.n==0 is true). how can I get out of the loop ? Only one writer thread,so I didnot use any mutex. qt5.13 vs2017 main.cpp: //#include"QtTestProg.h" #include<QApplication> #include<Q...
Only one writer thread,so I didnot use any mutex. That's undefined behavior. If you read and write the same memory location from different threads, you need synchronization. From https://en.cppreference.com/w/cpp/language/memory_model When an evaluation of an expression writes to a memory location and another evalua...
68,917,388
68,917,843
User defined conversion assigned to const ref variable via temporary object
The code below is a simplified version of the actual problem I am facing. Assume I do not have permission to modify class A (as it is external library), and its already widely used in my existing code base. The const & assignment from a temporary object (direct constructor) which also return a const & member variable v...
You can apply ref-qualified member functions (since C++11), i.e. mark the conversion operator with lvalue-reference, to prevent it being called on temporaries (rvalues). class Foo { public: ... ... operator A() const { return a; } operator const A&() const & { return a; } operator const A&() && = dele...
68,917,454
68,917,652
What is the big O memory usage of maps in C++?
I'm wondering what the big O memory usage of maps in C++ (like how arrays use O(n) memory). In the C++ documentation, it says Constant for the empty constructors (1), and for the move constructors (4) (unless alloc is different from x's allocator). For all other cases, linear in the distance between the iterators (cop...
There are N nodes, so the memory usage is O(N). For accuracy, its' N * sizeof(std::map<KeyType, ValueType>::node_type), and may plus one more node for the sentinel root node. Note that node_type is added since c++17. node_type is larger than value_type, since it contains value_type and some more info(red-black tree col...
68,918,312
68,918,981
Understanding std::inout_ptr and std::out_ptr in C++23
I've being reading the list of library changes proposed for C++23 and I'm quite curious about the std::out_ptr and std::inout_ptr (their _t siblings). As far as I understand they are some kind of wrapper for smart pointers to be compatible with raw pointers, but I haven't managed to understand them yet. Maybe someone h...
TL;DR - it is for simpler and more seemless interoperability between C out/inout pointer parameters and smart pointers Longer answer Let's separate the stuff. std::out_ptr and std::inout_ptr are functions used to create objects of type std::out_ptr_t and std::inout_ptr_t respectively. What are those types and functions...
68,918,367
68,919,383
Derived template class with std::array size type
I'm using C++17 and have a template class with restrictions on the template variable type. I want to add a derived class that additionally takes in a std::array parameter and templatize the size of the array. template <typename T, typename U = std::enable_if<std::is_same_v<T, int> || std::is_same_v<T, bool>>> class Bas...
IIRC ,I made 2 changes to your code: 1.from Derived(T param1, std::array<std::pair<T, bool>, N>&& param2) : Base(param1), to Derived(T param1, std::array<std::pair<T, bool>, N>&& param2) : Base<T,U>(param1), 2.from template <typename T, typename U = std::enable_if<std::is_same_v<T, int> || std::is_same_v<T, bool>>, t...
68,918,421
68,918,903
C++ Read getline from txt file and store into string array
I'm reading from a text file using (getline(MyFile, line))from a text file and want to store it inside a string array at each element. My code doesn't work properly. Basically, I need to read from a file, save each line into a string array, then iterate through each string at each element. The for loop doesn't increase...
I made 2 chages to your code to read and print all lines(<256 lines) of a text file 1.comment out the for statement 2.insert i++ in while loop #include <iostream> #include <fstream> #include <string> using namespace std; int array[16], i; fstream myFile; string filename, line, str[256]; int main() { // 1. The us...
68,918,813
68,919,228
Using the TList class to reorder multiple fields
int __fastcall ListSortFunc1(void *Item1, void *Item2) { MyStruct *item1 = (MyStruct*)Item1; MyStruct *item2 = (MyStruct*)Item2; return (item1->string1 < item2->string1) ? (item1->string1 > item2->string1) : StrToInt64(item1->number1) - StrToInt64(item2->number1); } Reading the online document...
TList::Sort() is passed a callback function that is called during sorting to compare pairs of values from the list. The callback is expected to conform to the specification of the TListSortCompare type. Per its documentation: Item1 and Item2 are 2 elements from the list. When these are passed to the TListSortCompare f...
68,918,882
68,919,259
C++ Creating GUID from unsigned char array
I have a function that takes as input an array of unsigned char (16 values exactly) and creates a GUID (from GUID struct) by parsing all values to hexadecimal and passing a guid-formatted string to UuidFromStringA(). My code is as follows: GUID CreateGuid(const uint8_t* data) { createGuidFromBufferData(hexValues, d...
You can't fill an 8-character array simply by dereferencing a cast pointer to your source data and assigning that value to its first element, as you are attempting. As you have noticed, doing so will only assign a value to that first element. For the 8-character array at the end of the GUID structure, you can initialis...
68,919,599
68,919,774
What happens when we reset a shared_ptr when there are other shared_ptr alias constructed from it?
I am currently learning shared_ptr's alias constructor, and I wrote code like this int main(){ std::shared_ptr<Father> father = std::make_shared<Father>(); std::shared_ptr<Son> son(father, &father->son); printf("%d\n", father.use_count()); printf("%d\n", son.use_count()); father.reset(); printf(...
After father.reset(), father doesn't point to anything. It holds a null value (officially "there is no managed object"). You are printing the use_count of nothing, not the use_count of the Father or Son object, and the use_count of a null pointer is 0.
68,919,818
68,926,800
Why am I getting a 'no matching token error' in c++ with SDL2?
I am using visual studio with the visual c++ compiler. I am getting an error about 'no matching token found'. I searched on the internet and found out that there is sometimes a missing bracket in this situation. However, I looked through my code and did not find any missing brackets. This is my project: https://github....
You are missing a parentheses: T* c(new T(std::forward < Targs>(margs)...); //should be T* c(new T(std::forward < Targs>(margs)...)); This error always points to the line where a closing bracket should be, but isn't.
68,920,095
68,924,136
Static assert that a function returns a weakly ordered type
Minimal example: template <typename TFunc> void func(TFunc f) { //Do something like: double x{1}, y{2}; bool z = f(x) < f(y); //Do comparison somewhere } I would like to add a static_assert to the function that checks that f(x) returns a type where std::less computes. In other words I would like f(x...
More complicated piece of code, but this seems more general way to check this, in case somebody else needs this: template <typename T> class is_weakly_ordered_type { private: typedef int yes[1]; typedef int no[2]; template <typename S> static yes& test(decltype(std::declval<S>() < std::declval<S>())) ...
68,920,222
70,085,212
Is it possible to create a Windows Terminal bigger than the Screen? C++
I'm testing something and I would like to create a Windows Terminal with bigger dimensions than the current screen. I know it sounds like a stupid idea, but it is what I'm trying to achieve. I've tried different things like: HWND console = GetConsoleWindow(); RECT r; GetWindowRect(console, &r); MoveWindow(console, r.le...
GetConsoleWindow very specifically doesn't work for the Windows Terminal like it used to for the vintage console, conhost.exe. When called in Windows Terminal, it's going to give you back a dummy HWND, not the actual HWND of the Terminal window. FWIW, it's generally not recommended to use that API moving forward. Even ...
68,920,256
68,920,483
What's the difference with SIZE_T and unsigned long?
I'm curious with the difference with SIZE_T and unsigned long. When I saw sizeof(SIZE_T), I trace that through declaration tracing in VS. Then, I watched them in basetsd.h file. typedef ULONG_PTR SIZE_T, *PSIZE_T; typedef _W64 unsigned long ULONG_PTR, *PULONG_PTR; what's difference with them? And why c language divide ...
SIZE_T is a Windows datatype, not a standard type. As for the difference, it is that SIZE_T may not be an unsigned long. Take a look at this page which lists Windows datatypes. The entry for SIZE_T says: The maximum number of bytes to which a pointer can point. Use for a count that must span the full range of a pointe...
68,921,217
68,921,747
CRTP: Pass types from derived class to base class
In CRTP, the base class can use functions and variables from derived class. However, the types from derived class cannot be used directly by base class, see code below: #include <iostream> template <class Derived> class A { public: //using Scalar = typename Derived::Scalar; // Error! static constexpr int NA1 =...
Inside A, B is an incomplete type - a compiler hasn't yet seen the complete declaration of B, so you can't use Scalar inside the declaration of A. This is a natural restriction. The difference between a type and a scalar in your example arises because instantiation of initialization of NA happens not at the point of de...
68,921,276
68,921,945
how to initialize object of class with two pointers?
Ok, so i know this is kind of basic, but i can't understand what i'm doing wrong here. this is the class: class numar_complex { friend std::ostream& operator<<(std::ostream& out, const numar_complex& numar_complex); friend std::istream& operator>>(std::istream& is, numar_complex& numar_complex); private: d...
In the constructor you don't initialize p_real and p_imaginar, you declare new variables, which only live within the scope of constructor, and hence get destroyed, resulting in memory leak. To avoid this I recommend using member initializer lists class complex { private: double* p_real; double* p_imaginar; pub...
68,921,386
68,922,110
how in doxygen tell a function param should be certain define directive
I have some legacy function that in the input only accept some int. how properly document them and tell that the input of the function can be only one of the defined items? #define API_TYPE1 0 #define API_TYPE2 1 /** * @param[in] argument1 can be either @sa API_TYPE1 or @sa API_TYPE2 */ int TestAPI( int argument1,...
Some suggestions based on my comment with the question: /// \file /// the meaning #define API_TYPE1 0 /// the meaning #define API_TYPE2 1 // * @param[in] argument2 can be either @sa API_TYPE1 or @sa API_TYPE2 /** * @param[in] argument1 can be either @ref API_TYPE1 or @ref API_TYPE2 * @param[in] argument2 can be eithe...
68,921,726
68,921,756
C/C++ - getrawmonotonic was not declared in this scope
I'm trying to use getrawmonotonic function in my C++ application (this question should be the same for C). I tried both of the following includes to no avail: #include <time.h> #include <sys/time.h> Any idea how to get this function included? I'm using GCC. Is there a special compiler option needed? I am compiling on ...
This is a function inside the Linux kernel. Programs can't call it, just like they can't call functions inside other programs. You might be looking for the clock_gettime function with the argument CLOCK_MONOTONIC_RAW.
68,921,788
68,922,680
how to fill array with contents of another array that has different size using loops
I am trying to fill an array sized by [4344][20] with the contents of other array sized by [5430][20]. I wrote the following code and it has no errors. It filled the X_train correctly, but the Y_train didn't filled successfully. it remained zeros as its initialized. my code: void split(int fold, int array_X_set[5430][2...
you can try this code, so that you don't need extra variable like nTest, nTrain, nTest1, nTrain1. for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { if (i < division) { X_test[i][j] = array_X_set[i][j]; Y_test[i] = array_Y_set[i]; } else { X_train[i-division][j...
68,921,948
68,922,027
Overloading std::array << operator
I'm having trouble trying to overload operator << for std::array. I tried doing it casual way as for all other collections: std::ostream& operator<<(std::ostream& os, std::array<int> const& v1) { for_each(begin(v1), end(v1), [&os](int val) {os << val << " "; }); return os; } But the compiler expects me to add ...
Templates are not just for "general types". std::array is templated on both the type it holds as well as for the size of the array. So you need to template your operator if you want it to apply for any size int array: template <std::size_t N> std::ostream& operator<<(std::ostream& os, std::array<int, N> const& v1) { ...
68,922,372
68,922,845
function pointer in c++ class throws compiler error
I am new to function pointer and tried to pass the function pointer as parameter from one class to other and getting compiler error. 'fncptr1': is not a class or namespace name" what am I doing wrong? fncptr1.h #ifndef FNCPTR1 #define FNCPTR1 #include "fncptr2.h" class fncptr1 { public: int addition(int a,int ...
Remove the includes of fncptr2.h and fncptr1.h from all .h files. Instead add them to fncptr1.c and fncptr2.c. you need f.implfncptr(&fncptr1::addition); instead of f.implfncptr(&addition); in fncptr1.cpp fncptr1.h #ifndef FNCPTR1 #define FNCPTR1 class fncptr1 { public: int addition(int a, int b); void testfncpt...
68,923,270
68,973,541
Rotating a shape to anywhere between 1 and 2 radians resets its rotation
I'm currently using GLM to transform shapes in OpenGL. However, when the rotation of the shape is between 1 and 2 radians, the values of the matrix that represent rotation are set back to how they would be in an identity matrix. I'm outputting the model matrix to the console currently which helped find out the exact mo...
Solved - the issue was related to a block of code specific to my project, which was likely why it is so unique. Specifically, I made a mistake related to what axes to affect when rotating via glm. The way I coded it the first time was as follows: // Variable to store the affected rotation axes glm::vec3 _active_rotati...
68,923,483
68,924,807
Why the "if" didn't work ? (n queen problem)
here is my code #include <iostream> #include <vector> using namespace std; int k = 4; vector<int> QLocation(k,0); vector<vector<string> > board(k, vector<string>(k, ".")); bool check(int row, int column) { if (row == 0) return true; for (int m = row - 1, n = 1; m >= 0; m--, n++) { if (board[m][co...
Edit: This answer assumes you have corrected the typo in if(column + n < n ...) to if(column + n < k ...) The problem is in this part if(j == k-1){ i -= 1; j = Qlocation[i]; } consider the case of k = 4 and i = 2 in the iteration. The board will be looking like this at that point. Q... ..Q. .... .... and here c...
68,923,792
68,923,913
cppcheck warning: access of forwarded variable
On the following code #include <utility> template <int i = 0, class F, typename... ArgsType> void g(F&& f, ArgsType&&... args) { if constexpr (i < 1) { f(std::forward<ArgsType>(args)...); g<1>(std::forward<F>(f), std::forward<ArgsType>(args)...); } } a run of cppcheck --enable=all gives the following warn...
It's warning you that your code uses a variable after a potential move. std::vector<int> v{1, 2, 3}; g([](auto v_) { }, std::move(v)); We pass v into the function by moving (so we pass an rvalue reference to it). When it will be forwarded in the invocation f(std::forward<ArgsType>(args)...), the argument v_ will be i...
68,924,157
68,926,307
SetTimer(NULL, NULL, UINT, NULL)
I am reviewing an MFC application that has the following line of code: SetTimer(NULL, NULL, 50, NULL); From the WinAPI docs: UINT_PTR SetTimer( HWND hWnd, UINT_PTR nIDEvent, UINT uElapse, TIMERPROC lpTimerFunc ); Parameters hWnd Type: HWND A handle to the window to be associated with the timer. Th...
What does hWnd == NULL do in SetTimer? When hWnd is NULL the timer is not associated with a window. Think of it as a global independent timer in your thread or application. Does nIDEvent == NULL always imply that I want to create a new timer (whose ID will be returned by the call), and not 'replace' an existing timer? ...
68,924,267
68,924,337
Using mmap with /dev/mem - Is it okay to use reinterpret_cast
I'm using mmap with /dev/mem. I've seen examples in C use the following pattern: #define OFFSET = ...; int fd = 0; void* base; fd = open("/dev/mem", ...); base = mmap(..., fd, ...); // Below is line of interest. *((uint32_t*)(base + OFFSET)) = 23; First question - What is happening here? It looks like we are adding...
base + OFFSET is a gcc extension where pointer arithmetic works on void *. "Why can't we just declare base as uint32_t*?" Because the arithmetic would come out wrong. void * arithmetic is in bytes. There seems to be some confusion as to the meaning of arithmetic in bytes. OFFSET is the number of bytes (not 32 bit integ...
68,924,325
68,925,242
Reason for getting garbage values in printing 2-D array through pointer
I have a pointer to a dynamically allocated 2-D array and am trying to print array values through dereferencing the pointer. Somehow, some of the array indices are showing garbage values even though I initialized them all to 1. Any insight into what I am doing wrong would be appreciated. int main() { int (*ptr)[4][4];...
Let's look at your basic code. int (*ptr)[4][4]; int** array; array = new int*[4]; for (int i = 0; i < 4; i++) { array[i] = new int[4]; } ptr = (int(*)[4][4])(*array); This is the part that matters. Let's look at what array is. Array is a pointer to pointers. While you're doing this in a very C-style fashion, wh...
68,924,451
68,924,656
How to append a long to a string in C++?
I'm working on a school project and I'm making a VEX Robotics program. It's in C++, and I am very new to this language. I can't import any new libraries to help me and I want to display a value on a screen. Unfortunately, I need to make it say "Left Stick tilt: " and then the tilt value of the VEX controller's left sti...
How to append a long to a string in C++? In order to append long to a string, you must convert the integer to a string. You can for example use std::to_string. You can append to another string like this: long l = 42; std::string s = "look at this long: "; s += std::to_string(l); Alternatively, you can use a format s...
68,924,606
68,943,447
Check file existence with fstream using x86_64-w64-mingw32-g++ for cross compilation
I have a program that is written in C & C++ and I'm rewriting some parts to improve it. This program has to work with files, but I am not able to check if a file exists on Windows with a cross-compiled exe. To check if my code was the problem, I have created this simple example: #include <fstream> #include <iostream> ...
Rest a bit always helps... I have found a workaround to my problem just reading 0 bytes. #include <fstream> #include <iostream> int main(){ std::fstream in_file("test.noexists", std::ios::in|std::ios::binary); char dummy; if (in_file.read(&dummy, 0)) { std::cout << "File exists " << in_file.tell...
68,924,842
68,940,093
Is this a truly Thread-Safe LRU Cache Design with Minimal Blocking?
Below is pseudocode for a LRU cache design with minimal blocking that I've been working on. The cache has the following characteristics: It has a fixed size MAX_CACHE_SIZE It is LRU I want the following conditions to be true: If a cache miss occurs, no blocking will occur while the data becomes available (downloaded...
The pseudocode does not describe a thread-safe algorithm. Consider that multiple threads may be waiting for a particular item to be fully downloaded. Each of them would be holding (in stack memory) the same item_iterator. Download finishes. When the first waiting thread wakes up, to maintain the LRU, it will invalidate...
68,925,756
68,925,864
C++ Dynamic Array Access Violation, Reading & Writing Location
Trying to create an array inside of an array inside of an array which holds int values, I already know the lengths of all 3. When changing or reading the value I get an access violation, imagine it's from creating the array within the loop, but I need to access and change these values outside of the loop, as the loop's...
Consider if std::cout << meshFaces[878] << "\n"; //test 3, prove range works is actually out of range, accessing past the end of allocated memory for meshFaces but it was not the last block of memory in the heap, so it returns something in memory, belonging to some other allocation. Printing this as a pointer, it's no ...
68,925,865
68,927,696
why does the first 2 chars get skipped when executing? C++
while(!Info.eof()) { std::getline(Info, line,'\r'); char a[line.length()]; char things[]= ":.\n\0"; for(int i=0;i<sizeof(a); i++) { a[i]= line[i]; } ptr = strtok(a, things); ptr = strtok(nullptr,things); while (ptr!= nullptr) { ptr = strtok(nullptr,things); st...
Well, for starters, you are calling strtok() 3 times before your 1st cout print. So you are skipping the first few substrings. Also, you have mistakes in your code, namely using eof() in a loop, and using non-standard variant-length arrays. Try something more like this instead: while (std::getline(Info, line)) { c...
68,925,977
68,926,232
why array is smaller than matrix smaller than vector ? c++
I am trying to read the mnist file and put the elements in a vector of matrix. code to read mnist for(int r = 0; r < n_rows; ++r) { for(int c = 0; c < n_cols; ++c) { unsigned char temp = 0; file.read((char*)&temp, sizeof(temp)); data[r][c] = temp; //std::cout << "r: " << r << " c...
Basically you are misunderstanding what sizeof does. It returns the size of an object's type but not the size of all the memory that is owned or referred to by an object. To be specific the size of a pointer is typically 8 bytes regardless of how much memory the pointer points to, e.g. int main() { int* foo; st...
68,926,118
68,933,338
Can a method be referenced using a child class name in C++?
Please consider a struct A with a method f, and an inherited struct B, which does not redefine f. In this case B::f refers to the same method as A::f. Is it allowed to invoke the method f of an A object using B::f name as in the following example? struct A { void f() {} }; struct B : A {}; int main() { A{}.B::f(); } C...
GCC is correct: [class.access.base]/6 requires that a pointer to the left-hand operand of . be able to be implicitly converted to a pointer to the naming class of the right operand. The term "naming class" is defined in [class.access.general]/5; in your example it is B, and obviously an A* cannot be implicitly conver...
68,926,188
68,926,356
Can a template class alias itself without specifying its template parameters twice?
I'm trying to define a new class template which has many parameters. For writing some methods (such as overloaded operators), I'd like to alias the template class type. Right now I'm doing it like this: template <class T, int a, int b, int c, int d, int e, int f> class ExampleClass { using ExampleClassType = Example...
You can actually just use ExampleClass for this purpose. It's called the injected class name and inside the class definition you can use it and it will implicitly be the fully instantiated class. Example: #include <iostream> template<class T, int a> struct ExampleClass { ExampleClass operator+(const ExampleClass& ...
68,926,526
68,936,409
Template Friend Function of a Template Class (Friend with More Parameters)
I can't get this to work: template<std::size_t s, typename T> class A; template<std::size_t s, typename T, typename U> A<s, T> operator *(U const lhs, A<s, T> const& rhs); template<std::size_t s, typename T> class A { // Blabla template<typename U> friend A<s, T> operator * <>(U const lhs, A<s, T> co...
Since there is an additional template parameter (compared to the template class parameters), it seems that one does not need to add the <> after the function name. In conclusion, this worked fine for me: template<std::size_t s, typename T> class A; template<std::size_t s, typename T, typename U> A<s, T> operator *(U ...
68,926,633
68,926,695
Is it wrong to declare two pointer variables with comma?
#include<iostream> using namespace std; int main() { string y="hello"; string* x, *z= &y; cout<<x<<endl; cout<<*x; } In the above code, when I delete *z I get the correct output (address of hello and "hello"). But, when *z is present I get some weird output. Why can't both z and x store th...
The shown program is wrong. You provide an initialiser only for z and not for x. Thus, you've default initialised x and it has indeterminate value. When you read the indeterminate value (and indirect through the pointer), the behaviour of the program is undefined. Why can't both z and x store the address of y. Two po...
68,926,707
68,926,813
Is there a way to avoid storage overhead when using a function as a callback?
Given the following setup: // ***** Library Code ***** #include <concepts> template <std::invocable CbT> struct delegated { explicit constexpr delegated(CbT cb) : cb_(std::move(cb)) {} private: [[no_unique_address]] CbT cb_; }; // ***** User Code ***** #include <iostream> namespace { inline constexpr void fu...
There are no objects of function types. The type will be adjusted to be a function pointer, which is why you delegated{func} and delegated{func_ptr} are exactly the same thing and former cannot be smaller. Wrap the function call inside a function object (lambda, if you so prefer) to avoid the overhead of the function p...
68,926,995
68,927,176
pass char array properly to templated method
I have some class with enum variable and I wants to stringify that enum. For that reason I added typeValue with stringified values. Also I added separate class for getting stringified values but I can't pass variables in correct way. Code like this: #include <iostream> #include <string> #include <algorithm> #define st...
Two issues: const char(*name)[] defines a pointer to an array of const chars, not strings. MyClass::typeValue is of type const char* (&)[10] so it cannot be implicitly converted to a pointer to that array. This works: class MyClass{ //... constexpr static const char* typeValue[10] = { stringify(TYPE::...
68,927,069
68,927,959
How do you pack three 4 bit signed integers (so 5 bits) into a single 16 bit integer?
I want to pack 3 signed 4 bit integers (4 bits data, 1 bit sign bit) into one 16 bit integer, but I have no idea how to do it or where to start :( I need this to represent a position in a 3D grid in as little data as possible (Since with higher grid sizes, it REALLY adds up). If it helps, I'm using GLM (OpenGL Mathemat...
@JDługosz 's answer is great if you're on a platform that supports that struct syntax. However, you mention OpenGL. Here's a version that will work in a shader. Basically, test the sign in a platform-agnostic way, set a bit for that (1 for negative, 0 for positive), add the lower four bits of the int you want to pack, ...
68,928,310
70,608,597
Build specific modules in Qt6 (i.e. QtMqtt)
For a project which uses MQTT, I always had to compile the QtMqtt module from source, because it wasn't included in the prebuilt windows release and couldn't be chosen for installation either. In Qt5 that was pretty easy: Download source code from official git (https://code.qt.io/cgit/qt/qtmqtt.git/), open the .pro fil...
From what I understand, I cannot compile single modules on their own from now on, but have to get the whole Qt 6.2.0 source code instead (i.e. via installer option) That's not correct. Given a pre-built Qt, you should be still able to just build the qmqtt package from source by running e.g. <QTDIR>\bin\qt-configure-...
68,928,366
68,931,683
Can using this function queue::size() of C++ STL in loop affect behaviour
I am writing code for left view of Binary Tree. And here in the loop when I am putting condition as i<q.size() I am getting different(wrong) output and when storing it in a variable and using that variable in loop, Like: int size = q.size(); for(int i=0; i<size; i++) I am getting correct output when using above code. ...
There code does have different behavior: int size = q.size(); for(int i=0; i<size; i++) for(int i=0; i<q.size(); i++) The first version has a certain loop size: the current queue's size. The second one has a dynamic loop size, it's not deterministic since in the loop we may push into or pop element from the queue, th...
68,928,507
68,928,543
Move ctor is not getting invoked
Below is my code #include<iostream> #include<string.h> using namespace std; class mystring { private: char * ptr; public: mystring() { ptr = new char[1]; ptr[0] = '\0'; } mystring(const char * obj) { cout<<"param called "<<endl; i...
In the line mystring s1 = move("Hello World"); you are moveing the string literal "Hellow Word", not an object of type mystring. int main() { mystring s1 = move("Hello World"); // moving a c-string, not very useful mystring s2 = s1; // calls copy constructor mystring s3 = std::move(s1); // new line, calls ...
68,928,916
68,928,991
pass map from file to class c++
I have this situation where I'm trying to pass a map after I populated it, from a file to a class: A.h - a normal header file where I have a function prototype and a map #include <unordered_map> func1(); static std::unordered_map<glm::ivec3, Chunk*, KeyHasher> chunks; A.cpp #include "A.h" func1() { // ... chun...
You are declaring the chunks variable as static in A.h. That is the problem. Every .cpp that #include's A.h will get its own copy of the chunks variable. That is why chunks is populated in A.cpp but is empty in B.cpp. If you want to share the chunks variable across translation units, it needs to be declared as extern...
68,928,971
68,929,117
Constructor class requires parameters but want to use it as a property
So I have a class #include <SPI.h> #include <Keypad.h> #include "Debug.h" class Keyblock { private: Debug debug; Keypad keypad; public: void init(byte * keypadRowPins, byte * keypadColPins, Debug &debug); void read(); }; void Keyblock::init(byte * keypadRowPins, byte * keypadColPins, Debug...
Is there a trick to making this work Not a trick, but since Keypad doesn't have a default constructor, you need to initialize it in the member initializer list of your Keyblock constructor(s). Example: class Keyblock { private: static constexpr byte ROWS = 4; static constexpr byte COLS = 3; char keys[R...
68,929,006
68,929,559
C++ file renaming best style
I have 50 image files which I want to rename. from: img (1) - Copy.jpg to: picture_1.jpg Do you know more elegant way to write it? I came up with this: #include <iostream> #include <cstdio> #include <string> using namespace std; int main() { string oldname = ""; string newname = ""; char oldfilename[20...
I'm going to simplify what the asker had and apply some general best practices. For ease of comparison, I'm sticking to old school C++ code. Comments explaining what I did and why are embedded to keep the explanations close to what they explain. #include <iostream> #include <cstdio> #include <string> // using namespace...
68,929,308
68,929,614
Use a std::vector to initialize part of another std::vector
Is there a way to "expand" a vector variable in an initialization list to achieve something to the effect of std::vector<int> tmp1{1,1,2,3,5}; std::vector<int> tmp2{11,tmp1,99}; //tmp2 == {11,1,1,2,3,5,99} I know it could be done with std::copy or insert. Was wondering if there was list-initialization way achieve that...
With this solution you can have something close the the syntax you want. (And yes some of the work will be done at runtime) #include <type_traits> #include <vector> namespace details { // recursive part template<typename type_t, typename arg_t, typename... args_t> void append_to_vector(std::vector<type_t>& vec, arg_t...
68,929,434
68,929,961
Visual Studio 2019 C++ cross-platform directives #if #else ignored
I am using Visual Studio 2019 (updated to date, running on Windows) to rewrite old program code in cross-platform C++ language (Windows & Linux). In the code, I am using the pre-compilation directives #if, #else, #endif to toggle platform-specific blocks of code. Example: 76 #ifdef WINDOWS_OS 77 errno_t success...
Problem solved. The problem was in the definition of the WINDOWS_OS flag, I had defined it in the code with the #define WINDOWS_OS statement. The IDE recognized the instruction, but the preprocessor didn't. The solution was to include the WINDOWS_OS flag in the list of definitions in: Project Properties -> Settings Pro...
68,929,647
68,929,786
selection sort algo does not correctly sort numbers
I'm trying to create a selection sort algorithm in C++. Whenever I run the program, it does not sort the list properly in ascending order. Any help would be appreciated. #include <iostream> #include <string> using namespace std; void swap(int arr[], int indexA, int indexB) { int tmp = arr[indexA]; arr[indexA] ...
The algorithm is missing a step. The minIndex needs to be set at the start of each i loop.
68,929,897
68,929,930
`make_unique_for_overwrite` still initializes `std::pair` elements
I was hoping that auto myPairs = make_unique_for_overwrite<pair<uint64_t, void*>[]>(arraySize); would give me uninitialized memory for my pairs. I am overwriting those later anyway and the (unnecessary) initialization is currently responsible for 120ms out of 600ms overall runtime for my algorithm. What is the most id...
According to cppreference, the default constructor of std::pair always value-initializes (aka zeroes) its elements. The solution is to get rid of pair. You can replace it with a structure with two members. I know I could still just allocate ... and then reinterpret_cast Attempt to reinterpret_cast such structure to s...
68,931,194
68,931,351
Templated class-- semicolon after constructor?
I have a templated class: template <typename vtype> class BNode { public: BNode::BNode(std::vector<BPoly<vtype>>& thePolys) {if(thePolys.size()) Build(thePolys);} BNode::BNode() {} BPlane* mPlane=nullptr; //And more stuff }; When I compile, I get this error on the BPla...
The following code compile without any error: #include <vector> class BPlane; template <class T> class BPoly { int i; }; template <typename vtype> class BNode { public: BNode(std::vector<BPoly<vtype>> &thePolys) { if (thePolys.size()) Build(thePolys); } BNode() {} BPlane *mPlane = nullptr; void Buil...
68,931,243
68,931,268
Understanding the offset fields in the OVERLAPPED structure
I am going through some code that uses ReadFile and specifies an OVERLAPPED type. From what I understand so far from reading other posts, this is what I got. If you wanted to start a ReadFile at the 8th byte of the file, you would set the Offset variable of OVERLAPPED to 8 and the OffsetHigh variable to 0 before passin...
The actual offset is a 64-bit integer. The Offset field is the low 32 bits, and the OffsetHigh field is the high 32 bits. This is stated as much in the documentation: Offset The low-order portion of the file position at which to start the I/O request, as specified by the user. ... OffsetHigh The high-order portion of...
68,931,611
68,932,258
Does this problem have overlapping subproblems?
I am trying to solve this question on LeetCode.com: You are given an m x n integer matrix mat and an integer target. Choose one integer from each row in the matrix such that the absolute difference between target and the sum of the chosen elements is minimized. Return the minimum absolute difference. (The absolute ...
This problem is NP-hard, since the 0-1 knapsack problem reduces to it pretty easily. This problem also has a dynamic programming solution that is similar to the one for 0-1 knapsack: Find all the sums you can make with a number from the first row (that's just the numbers in the first row): For each subsequent row, add...
68,931,699
68,931,877
Why does this return a copy of the drop_location?
In the following code when I edit drop_location.materials it doesn't edit the drop_location that already exists in prod_config. Where is the found drop_location being copied, and how do I avoid the copy operate directly on the field in prod_config? auto prod_config = getProdConfig(nh); models::dropLocation_t drop_l...
To change existed values, we need to access then by reference or pointer. So a fixed code might like: auto prod_config = getProdConfig(nh); try { auto& drop_location = getDropLocationByName( prod_config, query_drop_location_name, drop_location); drop_location.materials = materials; } catch (...) { } models::...
68,932,107
68,932,361
Best way to iterate over a string without going over its size
I am having trouble splitting words of a string into a vector. I am trying to keep track of each word with a first and last integer. I believe my main issue has to do with how I am iterating over the string. What would be ways to improve this function? Input: "hello there how are you" Actual Output: "hello", "there", "...
I suggest: #include <iostream> #include <string> #include <vector> #include <sstream> #include <iterator> using namespace std; vector<string> wordChopper(const string & s) { istringstream iss(s); return vector<string>(istream_iterator<string>{iss}, istream_iterator<string>()); } int main() { for (auto & ...
68,932,367
68,932,647
How do I easily print rows without doing multiple couts? (C++)
So I'm trying to do something like this: std::cout << "*" << std::endl; std::cout << "**" << std::endl; std::cout << "***" << std::endl; std::cout << "****" << std::endl; std::cout << "*****" << std::endl; Instead of doing it 5 times, can I just do a range function to cout rows that add up? So if want it to be 50 "*" ...
Without using loops or recursion this can't be done. I had used for loop for your question. #include<iostream> using namespace std; int main() { for (int i = 1; i <= 50; i++) { for (int j = 1; j <=i ; j++) { cout<<"*"; } cout<<endl; } return 0; } This will have 2 nested loops, one fo...