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
66,846,541
66,848,332
Using thrust::reduce to compute the sum over a vector of 8 bit integers without overflow
I've got a device vector of type uint8_t and I want to compute a sum over it using thrust::reduce if possible. The problem is that I get overflow, since the sum will be much larger than 255. I thought the code below would compute the sum, by storing the results as 32 bit integers, but it doesn't seem to be the case. Is...
I think the only solution that will work is to use thrust::transform_reduce to explicitly cast the 8 bit input data to a 32 bit quantity before the accumulation operation in the reduction. So I would expect something like this: #include <thrust/transform_reduce.h> #include <thrust/functional.h> #include <thrust/executi...
66,846,882
66,846,958
Segmentation fault when reading text file
I am trying to run a code sorting the ages of Titanic survivors from a text file. It compiles fine, but the program terminates simply saying "segmentation fault" when I choose option B (option A is not written yet.) Here is a small sample of the text file for reference. 29 1stClass TRUE 0.9 1stClass TRUE 2 1st...
In sortAgesLiving(), you have forgotten to open the file before starting your pre-sort processing. As a consequence, your first reading loop will fail to read anything at all. Therefore eldest will stay 0. You then construct a vector and populate it. But since the loop is based on eldest, the vector survivorVector wi...
66,847,735
66,847,794
Access an index of a map from a pointer
I currently have this struct test { std::map<int, UINT64> ratio; } where pContext is a pointer to test int group = 1; auto a = (*pContext).ratio[group]; <---Error In the above I get the following error Severity Code Description Project File Line Suppression State Error C2678 binary '[': no operator f...
You seem to have left out important details, but fortunately the error message is sufficient to fill those in. Your pointer is not just "a pointer", it's obviously a const pointer. The reason this is a problem is due to how operator[] on maps works. That function is non-const (therefore cannot be called on const obje...
66,847,793
66,929,204
Write a sequence of byte data using basic_ofstream
I have a info_list variable of type std::list<std::pair<std::size_t, std::byte*>> that I want to iterate and save data in binary format sequentially into a file. Here is what I tried: void write_data() { std::basic_ofstream<std::byte> file("data.bin", std::ios::binary); for (decltype(auto) info : info_list) { ...
Here is what you're missing: When using std::basic_ofstream<std::byte>, you are actually instantiating std::basic_ofstream<std::byte, std::char_traits<std::byte>>. The problem lies with std::char_traits, since the Standard specializations (types for which the behavior is well-defined) are: std::char_traits<char> std::c...
66,848,369
66,848,747
Why does whether a struct's destructor runs depend on the type of a member variable?
I'm fairly new to C++ and when wandering around the constructor and destructor behavior I found this problem: #include <iostream> struct Student { std::string a; ~Student() { std::cout << "Destructor called\n"; } } S; int main() { std::cout << "Before assigning to S\n"; S = {""}; std::...
You are seeing Copy Elision. This is an optimization that will bypass construction of temporary objects in certain cases. In GCC, that can be disabled by passing the following compiler flag (although it's generally not recommended): -fno-elide-constructors In your case, I believe the optimization is triggering due to...
66,848,564
66,848,614
old-style cast for a complicated long
Can anyone point to where/how I can get rid of old-style-cast warning for the long variable latency? time_t timestamp; suseconds_t timestamp_us; int tod; #define ONE_MILLION 1000000 #define USEC_IN_DAY (long)8640000000 long latency =((timestamp % SEC_IN_DAY )*ONE_MILLION+ timestamp_us - long(tod * ONE_MILLION) + USEC...
The problem is with the USEC_IN_DAY macro. The (long) is an old style cast.
66,848,568
66,848,691
Trying to append a value to class List from a function "splitoList" in C++
So I'm trying to write a function called "splitoList" to take 3 arguments, a string, another string that defines where to split the first string, and a class List to append the data to. Here's what I have so far. split.h #include <iostream> #include <sstream> using namespace std; string splitoList(string s, string spe...
You need to change your function's prototype, with a reference argument, then the print statement works as you expected string splitoList(string s, string spechar, List <string>& lst) When passing lst as value, the instance in function splitoList is a copy of the one in your main function; as a reference, they are the ...
66,848,835
66,848,999
Pointer address assignment in c++
i'm code beginner #include <bits/stdc++.h> using namespace std; void init(int* arr){ arr = new int[10]; cout << arr << endl; } int main(int argc, char* argv[]){ int *arr; init(arr); cout << arr << endl; } this is a simple code. My question is that why arr's address in init function and arr's addr...
Step back a little and think about how arguments are passed into functions. void foo(int x) { } int main() { int x; foo(x); } Here the x in main() is actually passed by value to foo() which means a copy of x is created when passing to foo(). With the same logic, if you think of int * as another variable ...
66,849,725
66,849,827
DllImport, C/C++ -> C#, out array of doubles
I want to get array of doubles from C++. I tested with array of ints, it works fine, but I don't know array of doubles cannot work. The first and the second elements of array of doubles are wrong. There is another weird thing, I comment out FreeCoTaskMem, because if I don't, the application will be crashed, ints and d...
This: DllExport void TestOutOfDoubles(double** doubles) { double xyzs[9] = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9 }; (*doubles) = xyzs; } Is undefined behavior even without the C# interop. You are returning a pointer (array) to stack memory. Next function call and the contents of xyzs gets corrup...
66,850,419
66,855,400
Is the "module;" statement required for c++-20 modules
I have been experimenting and hade realized that on some sites the examples starts with the line: module; to define that the file is a module. My question is twofold: Is the "module;" going to be required for a c++-module Is it supposed to be a way of differentiating between module files and non module files (instead...
module; on its own starts the global module fragment. You can have a module file without that specific form, but you will need the keyword module somewhere. The C++ standard has never mandated particular file extensions, so it would be strange to do so here.
66,851,175
66,851,579
How to define a template function with two relative parameters
I'm trying to define a function, which allows us to call the standard hash function or some custom-defined function, and return the value of hash. Here is an example about how to use my function: auto res = myfunc<std::hash>(2); //hash the integer 2 with the function std::hash auto res2 = myfunc<std::hash>("abc"); ...
You need to declare both parameters. Moreover, std::hash is a class template, not a function. You can use a template template parameter: #include <cstdint> #include <functional> #include <iostream> #include <string> template<typename T, template<typename> typename H = std::hash> std::size_t myfunc(const T &t) { re...
66,851,210
66,851,342
How to sort a string from bigger to smaller
res is string but I can't sort. res.begin(), res.end() is not working, What I should do? //for example: input: a = 13; b = 17 sort before : 1314151617 sort after : 1111134567 #include <iostream> #include <string> #include <algorithm> using namespace std; void test3 () { int a, b; cin >> a >> b; int l =0; ...
You are missing a comparator. By default C++ sorts elements based on the < operator. If you want to sort elements in descending order, you use the same code, but provide an extra comparator: std::string s = "12341532231858092"; std::sort(s.begin(), s.end(), std::greater<char>()); // notice the 3rd argument! std::cout <...
66,851,586
66,851,696
Unintended behavior in c++ when passing in an incremented integer to a recursive function
The code itself accepts N and M from standard input and prints M-length combinations from 1 to N. #include <iostream> void print(int *arr, int size) { for (int i=0; i<size; i++) std::cout << arr[i] << " "; std::cout << "\n"; } bool is_found(int *arr, int size, int num) { for (i...
This: // option 1 (original, works) arr[cur] = i; recurse(arr, n, m, cur + 1); Does not modify cur. The loop continues with the next loop and the value of cur is the same in the next iteration. On the other hand, this // option 2 (doesn't work) arr[cur++] = i; recu...
66,851,951
66,852,425
How to check if a std::function is set and valid?
I have an std::function which is being set like below: typedef std::function<void(bool some_state)> TheListener; void ListenTo(TheListener the_listener) { m_the_listener = the_listener; } How do I check if the std::function is set? private: void SomePrivateMethod() { // How do I check here that m_the_l...
This does state that verifying the std::function instance in a condition should be sufficient to verify if it has a valid callable target. So yes, if (m_the_listener) should be enough.
66,852,101
66,852,222
Segmentation Fault when calling class functions in async
I am a beginner at c++ and was messing around with dynamic memory and asynchronous functions and I was not sure why the following code did not work. What I wanted to do is to basically dynamically create an object of Loop and an async function which calls the start method of the object, each assigning to a different ma...
You have to make sure that all variables are valid within the lifetime when they are used. Your code: std::async(std::launch::async, [&storeClass](){ storeClass["randomthing"]->start(); // uses storeClass }); return 0; } // calls storeClass destructor Has a race condition, where storeClass destruct...
66,852,189
66,852,238
Printing a simple 2x3 matrix
I'm very new to C++ and I have a little task of printing a simple 2x3 matrix consisting of just 0s. However despite some attempts I cannot figure out how to code to print the matrix correctly. This is my code: #include <stdlib.h> #include <iostream> using namespace std; int main() { int n_rows = 3; int n_cols ...
You have to add {} for the for (int a = 0; a < n_cols; a++) loop to have cout << "\n"; executed in each iteration, not after executing the loop. #include <stdlib.h> #include <iostream> using namespace std; int main() { int n_rows = 3; int n_cols = 2; for (int a = 0; a < n_cols; a++) { // add this ...
66,852,417
66,852,527
List share between two threads
I would like in c++ to share a list between two threads. I would like very simple not by taking FIFO or Shared memory so i just use mutex and locks. I tried this way and its working : #include <string.h> #include <mutex> #include <iostream> #include <thread> #include <list> std::list<int> myList; std::mutex list_mute...
Ted's comment is important, what you are working with are threads, not processes. Processes don't share memory (besides using Shared Memory, but you wanted to avoid that). Threads share their entire memory space with each other. You also mentioned that your supervisor wants you to use unlock/lock sections. You could do...
66,852,754
66,852,814
C++ "string subscript out of range" problem
Please help with debugging. The compiler gives me an error 'string subscript out of range error'. The idea of the part of the program is to read in several lines from a text file and combine them into a single string. The last line has a semicolon ';' at the end. For example: "The cat sat on the mat by itself"; The fin...
temp.length() will become zero for empty line and then temp[temp.length()-1] will be out-of-range. You should check for that. // add this condition // | // v while (temp.length() == 0 || temp[temp.length()-1] != ';') { inFile.getline(temps, 500); temp = temp.append(temps); }
66,852,759
66,854,156
Unpredictable copy elision?
According to this Wiki page the following code: #include <iostream> struct C { C() = default; C(const C&) { std::cout << "A copy was made.\n"; } }; C f() { return C(); } int main() { std::cout << "Hello World!\n"; C obj = f(); } may produce different outputs depending on the compiler and that compiler's s...
Write code that doesn't depend of presence or absence of copy-elision. It is mainly to respect rule of 3/5/0. Here, the main purpose of your class C is to exhibit copy-elision. In regular case, class contains data and or manage resources. So then should implement correct copy/move constructors to maintains there invari...
66,853,432
66,854,678
how to pass uint[] c# to c++ dll?
I am developing a C# program that communicates with a C++ DLL. The structure type in the provided C++ DLL is as follows: struct ST_TEST { unsigned long* anIDs; unsigned long anIDCount; }; The C# structure I created to match the above structure is as follows: [StructLayout(LayoutKind.Sequential)] public struct ...
You can't use uint because the Marshal class doesn't have an overload for that type, since it is not CLS compliant. However, since you're copying the bytes in the array, int will work, since it is the correct size, and the C++ code will still consider the array elements to be uint when it receives them. Also, note that...
66,853,917
66,855,466
cv::imread and other does not working with emscripten?
I have following C++ code with opencv. It is basic code for display image. I'm trying to compile it using emscripten but it seems that emscripten can't load some function of opencv. For example the cv::Mat is ok. Test for build_js went all right. Do you know what I'm doing wrong? Code: #include <stdio.h> #include <open...
This is not a problem with includes, since opencv2/opencv.hpp automagically pulls in all the module top-level headers if the modules are available. The obvious conclusion is that those modules are not available in your build of OpenCV, and now the question is why is that the case? As it turns out, some of the OpenCV fu...
66,854,143
66,854,452
std::uniform_real_distribution always returns infinity
When I run this code: double getRandomDouble() { static std::mt19937 entropy_ = std::mt19937(); std::uniform_real_distribution<double> distribution; distribution.param(typename decltype(distribution)::param_type(std::numeric_limits<double>::lowest(), ...
The choice of parameters violates the precondition of std::uniform_real_distribution (c.f. §26.6.9.2.2.2). The preconditions being a ≤ b and b - a ≤ numeric_limits<T>::max(), where a and b are the min and max of the distribution. Using numeric_limits<double>::lowest() and numeric_limits<double>::max() would go against ...
66,854,325
66,854,382
Does C++ automatically commute some operation overloads?
I've been trying to understand operation overloading and the commutative property between classes and fundamental types. I declared the Test to Int asterisk operation but not the Int to Test, just to see if C++ would automatically provide with some sort of commutative function. The testing code is: #include <iostream> ...
Your constructor with the form of Test(float number){ x = number; } is what is called a converting constructor. Since it is not explicit, it allows you convert a float to a Test implicitly. You see that in (3 * my_test).x Here the 3 gets converted to a float in the standard conversion sequence and then that flo...
66,856,259
66,856,294
Can a memory leak be a reason of a segmentation fault?
I have a complicated application with lots of third-party libraries, dynamically loaded plugins. And something causes the app to crash (SIGSEGV) after main exits. The call stack points to unknown addresses so not only I can't debug, I don't even have an idea where the crash happens. I tried to run the app with Valgrind...
No, memory leaks by themselves would not cause a segmentation fault. However, memory leaks usually indicate sloppy code, and in sloppy code other issues, which would cause a segmentation fault, are likely to be present.
66,856,560
66,860,962
How to convert an iterator-like that has a `next()` methode to a regular `begin`/`end` iterator pair?
In the codebase I inherited, there is a class that look like an iterator (this isn’t the exact code, but the logic is similar). template <class T> struct IteratorLike { T* next() &; // either return a pointer to a valid value or nullptr }; The way you use it is very similar to the way you use Rust iterators: Itera...
Since IteratorLike isn't default constructible, but is obviously copy constructible, you could use the instance you have to construct your end() iterator too. Example: // used by `my_collection.begin()` explicit MyIterator(const IteratorLike<T>& iter) : m_iter{iter}, m_value{m_iter.next()} {} // used by `my_co...
66,856,719
66,861,497
Not getting all the elements of an array Visual C++
I'm trying to add the elements from a text file to an array ,I used strtok() in order to split them and then tried to add them into the array,but for some reason the program is showing me only the first element.I've tried every possible combination of for and while but still not managed to solve it and get all the elem...
The main problem in your code is that the structure suggests that you want to read a line and then tokenize it with strtok. Unfortunately f >> user (with user being a char*) is the equivalent of fscanf(f, "%s", user)1, which tells the parser to skip any whitespace and then read any character stopping as soon as it find...
66,857,153
66,860,069
How to pass a lambda to a template paramater
I'm trying to define a function func(), which returns a std::string. template<typename T = std::string, template<typename> typename F = decltype([](const T &t){return t;})> std::string func(const T &t){ F f; return f(t); } As you see, what I'm trying to do is to pass a lambda as the template parameter so that ...
In C++11? With a lambda as template parameter? Given that a lambda (before C++20) can't be used in an unevaluated context (so in a decltype()) and can't be default constructed, I don't see a way. The best I can imagine, in C++11, to reproduce something similar is something as follows template <typename T, typename F = ...
66,857,275
66,863,832
Bridge pattern: how to define functions that call the implementation of the derived class
I am working on a polymer simulation code that employs the Bridge pattern to separate abstractions (the objects involved in the simulation) and their implementations (how they are represented e.g. one particle per monomer, continuous grid, etc.). A problem that I am facing is that I am struggling to define a class hier...
My answer is going to be split between the code, some comments in the code, and text here. First, the code: #include <iostream> #include <memory> #include <vector> // Create a pure virtual interface for your MonomerImpls class MonomerImpl { public: virtual ~MonomerImpl() = default; // Required in non-concrete clas...
66,857,531
66,859,932
C++ Unable to assign base class "this" pointer the derived class object inside base class constructor
Hi I am learning C++ and was trying to construct something where base class *this pointer is assigned the derived class object using the following construction. My question is that, is it possible in C++ in this way? Because, when i try to compile it, i get the error error: expected type-specifier before ‘Derived_1’ ...
You absolutely can't do what you're doing. You can't do this: *this = new Derived_1(); I don't even want to think about all the things wrong with this. What you want instead is to implement the factory pattern (which you can google for).
66,857,629
66,858,104
C++17 - variadic template arguments - call class method on return value from previous with templated argument
I have this code: struct Foo{ int sum; Foo() : sum(0) {} Foo(int x) : sum(x) {} Foo bar(int x){ return Foo(sum + 1); } Foo bar(std::vector<int> x){ return Foo(sum + 1); } Foo bar(const char* str){ return Foo(sum + 1); } }; template <typename ... T> int f...
You can use a folding expression for that. ((foo = foo.bar(args)), ...); We need an additional () around the assignement to make the compiler accept the syntax. I'm assuming this is what you want? I can't really tell what the code is supposed to do... Edit: As pointer out by @AVH doing a left-fold or right-fold here w...
66,857,673
66,857,720
Can you explain what this typecast do?
Given a string in terms of const char* const char *str = "Hello, World!\n"; std::cout << *str; will give H, but std::cout << *(char (*)[12])str; will give the complete string Hello, World!. I can understand that this cast takes 12 of some kind of data, but what does the (*) here mean?
but what does the (*) here mean? The difference between char [12] and char (*)[12] is that former is an array of 12 char while the latter is a pointer to an array of 12 char. Note that when you cast array (such as a string literal) to a pointer type, it will first decay to a pointer to first element of the array. The...
66,858,101
66,858,804
BST with function ptr, How to add in extra argument?
is there a way to pass in an extra argument to my function pointer in BST? I am trying to use BST inOrder to get value from a map<string, int>. this BST will be storing the key of the map. The map will act as a database that uses date + time as the key. each BST will be created to store the date+time of each year and s...
If you want to access variables outside of the BST template class (such as the map), then I advise changing your template to the following (assuming that m_root is a member variable of BST<T>, and that it is the root of tree): template<class T, class Fn> void BST<T>::InOrder(Fn funcPtr) const { InOrder(m_root, fn);...
66,858,300
66,861,248
MFC CScrollView does not clear background
My English is not perfect. I am using Visual C++ 2019 and MFC. Example program: an SDI program, the base of the view is CScrollView, draws 128*128 0s in a matrix. But MFC does not clear the background at scrolling with the scrollbar. Have you an idea? Thank you. In settings of Windows, I am using 96 dpi * 3 = 288 dpi. ...
The CScrollView class is a view with scrolling capabilities. You use it almost like a CView (ie drawing in the OnDraw() member), only you have to take into account the possible scrolling. The GetClientRect() function returns the visible client area, and the coordinates returned are not relative to the view origin, but ...
66,858,497
66,858,577
How do I call this function correctly in C++
I included the code I thought was relevant, I'm not certain how to call the get_data function. I've created instance of the sensor stream class, however can't figure out what to put in the get_data(____) enum flagState_t { /// Data has been successfully retrieved from the log FLAG_DATA_GOOD, /// There was ...
Assuming that stream is the instance of your class: flagState_t state; float result = stream.get_data(&state); get_data expects a pointer to a flagState_t variable so that it can store the error status in case of failure. After the call you can check the value of state to see if there's been any error.
66,858,726
66,858,892
Premature exit and destructors
I'm writing a linux deamon in a class, which is a smart pointer of an App class: App.hpp class App { public: App(void) { this->ptrDaemon = std::make_unique<Daemon>(); this->ptrDaemon->ptrApp = this; } ~App(void) = default; // Members public: std::unique_ptr<Daemon> ptrDaemon = n...
Is it a good practice (looks ugly to me)? No, it is usually not a good practice to call a destructor in a member function. Is there any other solution I could use? Sure. Here are a few: Don't bother deallocating. The "memory leak" won't matter since the process is about to be terminated. Note that if the destructo...
66,858,858
66,860,836
Can I dynamically create instances of C++ objects in the stack?
Just as it's possible to create a new instance of an object in the heap using new Class(), is it possible to create an object in the stack? I'm learning about heap vs stack. One way, in C++, is to have a static member in the cpp code: static MyObject myObject; but suppose that I have this: static int emptyArray[100000...
Just as it's possible to create a new instance of an object in the heap using new Class(), is it possible to create an object in the stack? Sure, simply declare it, without static, as a local variable inside of a function, eg: void doSomething() { ... MyObject myObject; // <-- allocated on the stack ... }...
66,859,271
66,859,726
Is it possible to initialize a vector with openMP with O(1) complexity? (C++)
I'm trying to parallelize some vector functions in a struct using openMP. While it works well with most of my implementations, I find that since the constructor for std::vector<> has a linear complexity, I can't get better performance and instead get something that's even worse than doing it sequentially for initializa...
template<class T> struct uninitialized_allocator:std::allocator<T> { template<class...Us> void construct( T* p, Us&&... us ){ ::new((void*)p) T(std::forward<Us>(us)...); } // don't construct when passed 0 arguments void construct( T* p ) {}; }; then later: int dimension = 0; std::vector<double, u...
66,860,228
66,860,554
How can I iterate over a stack of maps: std::stack< std::map<string, string> >?
I have a for-loop that iterates over the stack of maps, but when I execute the code i get a segmentation fault. My code is this: // std::stack< std::map<string, string> > STACK; size_t getStackSize() { return this->STACK.size();} std::stack< std::map<string, string> > getSTACK() { return this->STACK;} for (size_t i = 0...
getStack() is returning a copy of the std::stack each time it is called, thus while (!ObjSTACK.getSTACK().empty()) would be very inefficient at best, but ObjSTACK.getSTACK().pop(); would be a no-op, since you are popping from a temp std::stack, not the original. Thus getStackSize() would not change value, and the ou...
66,860,592
66,932,062
Hello, i am new in WTL, i dont understand how to reseive messages on CListViewCtrl
I create .rc file where put my DialogBar. In section of this DialogBar i create CListViewCtrl.And fill it. Then i need to receive messages on SelectedItem. Please, give me some code, or links to read about my problem. Thank you. Here is my code of DialogBar, where i calling the function to create CListViewCtrl #includ...
LRESULT OnLButtonDown(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { switch (LOWORD(wParam)) { case (int)LVN_ITEMCHANGED: MessageBox(TEXT("U am here"), TEXT("Here"), NULL); } return 0; } This looks wrong. WM_NOTIFY handler should use ...
66,860,603
66,860,741
Access private members in requires clause
Consider the following program: #include <iostream> template<typename T> void f1(T& v) { std::cout << "f1: can call g" << std::endl; v.g(); } template<typename T> void f2(T& v) requires requires (T& v) { v.g(); } { std::cout << "f2: can call g" << std::endl; v.g(); } template<typename T> void f2(T&) requires...
When you friend a function or function template, it's only the body of that function that gains access - not its various accoutrements. The constraints attached to it are extraneous. You can fix this by moving the check inside the body of f2, so that it's checked in a context that has this access: template <typename T>...
66,860,745
66,861,189
How to write a deduction guide for union type
Let's suppose we have this template for a union of a struct and an array of bytes of the same size template<typename T> union point { struct { T x, y; } coord; static constexpr size_t buffer_size = sizeof(coord); unsigned char buffer[buffer_size]; }; and we would like to use CTAD and aggregate initializati...
Deduction guides are based on constructors, either hypothetical ones created by explicit deduction guides or those that actually exist. Designated initializers are a form of aggregate initialization, and a type can only be an aggregate if it has no constructors. While that might still allow explicit deduction guides, t...
66,861,320
66,870,391
Compiler error info : No matching function for call to FUNCTION(TYPES ARGS) with unused typename template
I have had an issue with this bit of code, and compiler info didn't help much. I have a structure where I define an unsigned int array in a structure : struct TypeHolder { uint8_t byte_size; uint8_t values[8]{ 0 }; TypeHolder() { byte_size = 0; }; uint16_t calcCRC() { return Fast...
After investigation, it turns out the issue was related to the template header that was sitting on top ! template <typename any_type> //guilty piece of code Even unused, these can cause trouble. It is a realy stupid inattention/lazyness error, but at least knowing that it could happen may be valueable to you.
66,861,974
66,862,189
Overload function template using a templated type
I have a given function like this: template <typename T, typename F> T function(const F& f) const; This function has various overloads, some of them concept based. Similar to the following: template <typename T, std::integral F> T function(const F& f) const; template <typename T, std::same_as<double> F> T function(co...
You have to write your own concept. Adopted checking whether a class is a specialization from Check if class is a template specialization? and added a requires-clause to only accept the standard allocator. template <class T, template <class...> class TT> struct is_specialization : std::false_type {}; template <templat...
66,862,153
66,862,303
How and where using directive injects member names?
AFAIK a using directive exposes or injects all the names of a namespace in the nearest enclosing namespace. and here is from C++ primer: In contrast, a using directive makes the entire contents of a namespace available In general, a namespace might include definitions that cannot appear in a local scope. As a conseque...
Yes, this is quite convoluted, but the quote you were giving explains exactly what's going on. In your first example (reduced number of variables to 1): int x = 1; namespace A { namespace B { int x = 5; } void foo(){ using namespace A::B; std::cout << x << '\n'; } } The nearest...
66,862,274
66,862,520
Why do I need to declare a default constructor in order to compile when returning an unordered_map value?
This example fails to compile unless I uncomment the default constructor declaration: #include<unordered_map> #include <iostream> struct foo{ int data; /*foo(){ data = 0; std::cout << "DEFAULT\n"; }*/ foo(int d){ data = d; std::cout << "PARAM\n"; } }; struct bar{ ...
When the compiler compiles this line: foo f3 = b.getElem(1); 1 is passed as a parameter to a function (unless a whole lot of optimization magic occured, which is not guaranteed). This function cannot know that 1 will never be a missing key. As such, the code that allocates an entry in the map is called. And what is pa...
66,862,291
66,862,461
how does operator of type "operator class()" works
Im trying to figure how such an operator works: I found nothing about it searching the web... Is it used as a casting between types? Why do I need the = operator (in line a = b) instead of a b ? What other uses does it have? thanks class A{ int a; }; class B{ int b; operator A() { return A(); } }; int main(...
What you are looking at is a user defined conversion operator. IT has plenty of uses, for example. Consider a smart pointer: class SmartPointer { // Constructor destructor, operator* and & etc .. } If it were a raw pointer, we could check for it being nullptr like this: if (ptr) { ptr->do_something(); } So ho...
66,862,690
66,863,861
How to make older versions of clang happy with atomic's default exception specification
I have a class that has a member variable that wraps a std time_point in an atomic. I'm having a hard time getting older compilers happy with it. I initially had issues with versions of GCC earlier than 10 accepting it. I addressed this via explicitly initializing it. I thought that made all the compilers happy. But on...
As a workaround, you can make TimePoint a subclass (with a noexcept default constructor) instead of a typedef. #include <atomic> #include <chrono> struct A { A() {} using Clock = std::chrono::system_clock; class TimePoint : public Clock::time_point { public: using time_point::time_point; constexpr Tim...
66,863,151
66,863,167
How does C++ know which '++' operator to call?
I'm dabbing with C++ here and this question poped up when looking at some operator overloading functions. In the functions below, I understand that the int parameter in the second function is just a way to provide a different signature, allowing for the first function to be called if the prefix increment is used, and t...
If you write ++itr, the compiler translates it into itr.operator++() and the first function is called. If you write itr++, the compiler translates it into itr.operator++(0) and the second function is called. You can also implement operator++ as a non-member function, though this is rarely done. In such cases, the trans...
66,863,893
66,864,139
Type-safe composition of maps in C++
I want to write a type-safe function in C++ that composes an arbitrary number of maps. I approached by writing a helper function point that computes the application of the composition at a point– template <typename K> const K& point(const K& k) { return k; // recursive base-case. } template<typename K, typename V, ...
Here is my final version using the type deduction provided by @NathanOliver and using std::optional to omit any element that cannot be fully mapped through the composition. template<typename K> const K& point(const K& k) { return k; } template<typename K, typename V, typename ... Ts> auto point(const K &k, const std::...
66,863,931
66,863,971
use greater<char>() in priority_queue
#include <iostream> #include <iterator> #include <queue> using namespace std; int main() { vector<char> a(256); copy(istream_iterator<char>{ cin }, istream_iterator<char>{}, begin(a)); priority_queue<char> q{ less<char> (),a }; // less -> greater = compile error while (!q.empty()) { cout << q....
The problem is, given priority_queue<char> q ..., the compare type would be the default template argument, i.e. std::less<char>, which doesn't match if you pass greater<char> as constructor argument. You can specify all the template arguments explicitly as priority_queue<char, vector<char>, greater<char>> q{ greater<ch...
66,864,192
66,864,245
chapter 3 of C++ Primer Plus 6th - about how to use universal character name
The original text in c++ primer plus 6th is as follows: Using universal character names is similar to using escape sequences.A universal character name begins either with \u or \U.The \u form is followed by 8 hexadecimal digits, and the \U form by 16 hexadecimal digits.These digits represent the ISO 10646 code point f...
Four hex digits after \u, eight after \U. From the C++ standard: [lex.charset]/2 The universal-character-name construct provides a way to name other characters. hex-quad: hexadecimal-digit hexadecimal-digit hexadecimal-digit hexadecimal-digit universal-character-name: \u hex-quad \U hex-quad hex-quad
66,864,421
66,866,355
Split dynamic char into N sized chunks C++
I have a long dynamic char that I am trying to split into chunks of 20 characters max. The code below is what I have so far. The issue I am facing is it seems to work in the "for loop calculations" section, but when I then read out the results again in the "Checking results" they all seem to be set to the last output f...
I fixed the issue of your code as below char* largeWord = "aaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbccccccccccccccccccccddddddddddddddddddddeeeeeeeeeeeeeeeeeeeefffffffffffffffffff"; char* chunks[6]; int index = 0; const int blockSize = 20; Serial.println("=== for loop calculations ==="); for (int i = 0; i <...
66,864,613
66,866,040
How to read file containing a list of integers with an unknown size
I want to read from a file containing an unknown list of 4 integers each. So each line of the file contain something like this"12.0 43.0 19.0 77.0" I thought of using a 2 dimensional array but I don't know the size of the file because its a very big file. I ended up reading each line as a string and used a "while(!in_...
You don't need to know how many lines are in your file or how many numbers are in each line. Use std::vector< std::vector< int > > to store data. If in each line, integers are separated with a space, you can iterate a string of integers and add them one by one to a vector: #include <iostream> #include <string> #inc...
66,864,689
66,864,734
Returning an Enumerated Value's Member in a Function (C++)
I have an enumeration data type as follows: enum class CellColor {white, black};. I need to write a public member function that shall be named get_color and shall return type CellColor and shall accept no input parameters. This function will also return the value of Cell's color member. I've tried writing it out dozens...
When you define the enumeration and the variable inside the function, you define brand new and distinct entities that are separate from the member enumeration and variable. If we take your constructor: Cell() { // DEFAULT CONSTRUCTOR enum CellColor {white, black}; CellColor color = white; // Shall...
66,864,973
66,865,006
Unable to resolve segmentation fault
Hello am newbie here am getting segmentation fault when running the program but unable to find reason behind it . I have googled and know that it occurs due to memory violation but unable to find what is causing seg fault in my code. Code below #include <iostream> #include<algorithm> using namespace std; int main() { ...
The problem is very likely these two lines: int t, n, m; int arr[n]; First you define the variable n, which is uninitialized and will have an indeterminate value. Then you define the array arr using the indeterminate value of n. You can't do this until you have initialized n to a specific value. Using n here leads to...
66,864,986
66,865,156
String replacing deletes latter strings not working
I am trying to replace phrases in a text, but I tried to run this c++ program, but this deletes all the string after the replaced one, so I can't continue replacing different texts using this function. for example: input is hellookyou and the output is hellohello. the "you" part is missing. could you please explain why...
The problem lies in the way you are using the a.replace() function. The replace() function works in the way a.replace(0,3,"red") This would change 3 characters from the 0th index and replace them with the string "red". So in you case you are going to the index where you encounter the first occurence of "ok" string usin...
66,865,002
66,931,610
How to made QGraphicsView fullscreen?
I have a QDialog window of size 800x480 and my sample image also have same size (800x480), But when it put it in QGraphicsView it showing a small space between image and window, how to avoid this space (yellow color ) I am using Qt5 in windows10 My code is #include "dialog.h" #include "ui_dialog.h" Dialog::Dialog(QWi...
I used both QDialog and QMainwindow, but both of them have same problem with QGrapgicsView. Finally I changed QGraphicsView with QLabel and it does not have this problem.
66,865,572
66,865,720
Error with assigning memory to std::array
My intention is to pass a image buffer in a queue to some other function (in another thread) for processing, using example in http://www.cplusplus.com/reference/array/array/data/ .However I have gotten the following error: error: request for member ‘data’ in ‘frame’, which is of non-class type ‘std::array<unsigned char...
I think you should not using parentheses in front of the frame in this line : std::array<unsigned char, FRAME_HEIGHT * FRAME_WIDTH> frame(); the right command is: std::array<unsigned char, FRAME_HEIGHT * FRAME_WIDTH> frame;
66,865,854
66,866,137
WM_KEYUP for non-Virtual Keys (windows.h WindowProc)
I see that WindowProc can use WM_CHAR and wParam to detect character input, and I also see that WindowProc can use WM_KEYUP and wParam to detect virtual key releases. However, I would like to detect the moment that the user releases some other key (semicolon for instance). I haven't yet found the documentation for this...
All keys have a virtual key code, some of them are just not exposed through a macro. For example, a key that is asociated with a letter has a VK value of that letter's ASCII code. For a semicolon, according to this list, you would use one of the OEM keys, depending on the keyboard. As a more portable way to solve your ...
66,866,052
66,866,151
In Cpp for is not working properly from the function
I need to do this exercise, with struct and include the function in the struct to do the calculations, but for some reason, it's not working. I recommended you to check the image for a better idea. #include <iostream> using namespace std; struct Alfa{ double h,x,n,a; void shuma(){ cout << "enter n: "; ...
You are not following the formula in the image. Use this instead: double sum = 0; for (int i = 1; i <= n + 1; i++) { if (i != 4) { sum += 2 * i + a; } } h = x / 2 + 3 * sum;
66,866,054
66,866,107
Unordered_map weird characters
std::wifstream ifs("debug.txt"); std::wstring s; std::unordered_map <LPTSTR, LPTSTR> x; std::wstring delimiter = L"|"; size_t pos = 0; std::wstring first; std::wstring second; while (std::getline(ifs, s)) { pos = s.find(delimiter); first = s.substr(0, pos); ...
You are only storing pointers to first.data() and second.data() in your map. If any of them relocate the string data the pointers become dangling and you have UB (undefined behavior) if you try to dereference them. If they don't relocate, you'll have pointers to exactly the same strings in memory. If the map outlives f...
66,866,284
66,866,365
Converts Decimal To Hexadecimal In C++
Yesterday I wrote a program that converts Decimal to Hexadecimal. But I did not satisfy my code because I think my code needs something else. And I want to know another solution for this conversion.(eg-using quotient and remainder, using function or something else) Can you help me? //I really sorry for my English skill...
you can have from decimal to hex std::stringstream ss; ss<< std::hex << decimal_value; // int decimal_value std::string res ( ss.str() ); std::cout << res; from this topic Be sure to search before.
66,866,302
66,866,349
Vector behaving wierdly
I was trying to find super lucky numbers that is numbers that contain only 4 and 7 as their digit (lucky number) and the number of 4's and 7's must be same (super lucky number). I used recursion to find the lucky numbers and stored them in vector. Then i looped over all lucky elements to check if it is super lucky. But...
You print n1 whatever value it is. Then if it isn't super lucky number, you remove v[i] which is same as n1 then print new v[i], which is the next value of original v[i].
66,866,463
66,876,370
Calculating upper and lower limits using C++
I am writing a class that spits out polynomials based on a constants array a and exponent array b, such that this equation is generated: However, this equation does not have a solution for f(0), but it can be calculated using the limits from both sides (given that they are equal). How could you implement this in C++, ...
Generally, the limits for f(0) will depend only on the smallest exponent of the normalized polynom. The normalized polynom (as I call it) is the polynom, where all a values, that belong to a repeated b value are added up and only the non-zero a values are kept. If the smallest exponent is greater than 0, then f(0) = 0...
66,866,821
66,866,934
(C++) How can I print a long message without breaking words at the end of a console line?
This is technically two things, but they're essentially the same so I combined them into one question. I want to print long messages without having to control where a line break is in the text. For example, I wrote a long string and printed it with std::cout << str << std::endl;. Pipes | added here for demonstration pu...
You could use a function like void OutputText(std::string s) { int bufferWidth = GetBufferWidth(); for (unsigned int i = 1; i <= s.length() ; i++) { char c = s[i-1]; int spaceCount = 0; // Add whitespace if newline detected. if (c == ‘n’) { int charN...
66,867,129
66,872,400
why std::copy in reverse order
I want to copy a sequence of bytes into integer values, presumably they will whim with the port's UPD #include <iostream> #include <cstring> int main() { uint8_t arr[8]; uint32_t arrNew[2]; arr[0] = 0x11; arr[1] = 0x22; arr[2] = 0x33; arr[3] = 0x44; arr[4] = 0x55; arr[5] = 0x66; ar...
This is a very fragile thing to do. As mentioned in one of the comments, it depends on the endianess. The number 0x01020304 can be stored: x01 x02 x03 x04 But on others, it's the other way around. This is big-endian versus little-endian. A google for little endian vs. big endian will result in some great pages to read,...
66,867,300
66,867,577
C++ Queue with Linked-list
Question: struct QueueNode { int data; QueueNode *next; }; do int size() const: return data size. bool is_empty() const: void enqueue(int val): add a new node to the end of the list. void dequeue(): remove the node which head point to. int top() const: return the data which will be dequeue next. This is my c...
As @Kaylum pointed out, you have not returned the size of the queue if it is empty. It should return 0 in that case, but you have no else part in your size() method. This should probably work: int size() const { if (! is_empty()) return _size; else return 0; }...
66,867,419
66,869,452
Register a static class method in a global map<>
I have a main project which, depending on specific applications, includes a variety of other library projects. Those library project contain one or more implementations derived from a certain common interface. The main project instantiates implementation classes based on a config file which contains names of the implem...
You are trying to execute code outside of a function. This is not permitted in C++ except for static duration variable initialization. So you could easily get rid of the compilation error by making Configurator::registerImplementation non void and using its value to initialize a static duration variable: class Configur...
66,867,644
66,874,155
Tried to decompress a zip file into memory with boost,but it doesn't work
I tried to unzip a zip file with boost zlib, but it doesn't work ,my boost version is 1.75 which is binary which is have been built,I tried the code below with VS 2013 CE #include<iostream> #include<fstream> #include<algorithm> #include<iterator> #include<sstream> #include <boost/iostreams/filtering_streambuf.h...
zlib does not process zip files. zlib can process zlib, gzip, and raw deflate streams.
66,868,386
66,869,263
Reverse order of boost::dynamic_bitset
Is there a clean way to return the reverse ordering of a boost::dynamic_bitset object? For example: 01001100 becomes 00110010. The simplest solution I can think of is to convert the bitset to a string, reverse the string and convert it back to a bitset, but this seems a rather slow method that nullifies the speed of bi...
boost::dynamic_bitset doesn't have iterators, so a long range of comfy STL solutions like, off the top of my head, std::reverse or std::swap or their boost counterparts are not available, I reckon that a good way would be to make your own trivial reverse method: #include <iostream> #include <boost/dynamic_bitset.hpp> ...
66,868,761
66,869,224
How to program a function whose return value is depending on the flag without using "if"?
I want to make a class function like the conceptual code below. double function(){ if(flag==true){ "some process and return " } else{ "another process and return" } } where flag is the boolean member of the class. I want to make this function without using if because I use this function many times. T...
If you want to call one of two different member functions depending on the value of a bool without using an if or something else that might lead to branching, you could create a table containing two function pointers and use that for lookup by using the bool for indexing. If you only want to do this lookup when the val...
66,869,050
66,869,486
C++ - Two member functions differ by a single function call
I am trying to improve my C++ coding and I would like to ask what would be the most efficient and elegant solution of the following problem: I implemented a class with two member functions. They both fill an array of doubles. The bodies of these functions are identical except one call deep inside. In one of them, I wan...
Using function pointers has the downside that the compiler might not be able to do all possible optimizations, so you want to give the compiler as much information at compile time as possible. To do so you would pass that information as a template argument and not as a function argument. One way to do that would be usi...
66,869,212
66,869,349
Deduce parameter type of pointer to member function template parameter
I'm trying to write a C++ function template f with one template parameter of type void (Foo::*FUNC)(T const *) where Foo is some class type. Furthermore, I would like to deduce T from the concrete member function pointer specified for FUNC. So one idea would be: template<typename T, void(Foo::*FUNC)(T const *)> void f(...
Here's a trait to extract an argument from a member function pointer that looks like you expect it to look: namespace detail { template<typename M> struct extract_arg; template<typename R, class C, typename A> struct extract_arg<R (C::*)(A const*)> { using type = A; } } And here's a C++17 function template...
66,869,387
66,871,559
Function is not usable as a 'constexpr' function
Take a look at the following code #include <type_traits> template <typename T> struct basic_type { using type = T; }; consteval auto foo(auto p, auto x) noexcept { if constexpr (p(x)) { return 1; } else { return 0; } } int main() { // This compiles return foo( []<typename T>(basic_typ...
In order to evaluate this: if constexpr (p(x)) { We need for p(x) to be a constant expression. The rules for whether something qualifies as a constant expression or not are based on a list of things that you're not allowed to do. When x is a basic_type<int> and p is a function that takes a basic_type<int> by value, ...
66,869,520
68,120,006
runtime error: applying non-zero offset 18446744073709551615 to null pointer (basic_string.h)
I am solving a question on leetcode where I have to multiply strings and I got this error which I cant understand Line 518: Char 69: runtime error: applying non-zero offset 18446744073709551615 to null pointer (basic_string.h) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/...
For the case where ans="", Instead of returning "0" (string), you are returning 0 (Integer). As the return type is a string it is causing a problem. if(ans=="") { return "0"; } This Should work fine, I think.
66,869,550
66,869,685
ordering a list formed of char
struct nod { char info[21]; nod* urm; nod* ant; }; nod* p; nod* u; void ordonare(nod* p) { nod* o = new nod; o = p; while (o->urm != NULL) { if (strcmp(o->urm->info, o->urm->urm->info) > 0) { //mut o->urm->urm->info in locul lui o->urm->info nod* aux ...
The problem is the assignment operator = is not valid for a type of char[21]. You need to copy the contents of o->urm->info into aux->info. I like to use std::copy, like so. Instead of writing aux -> info = o->urm->info;, write std::copy(o->urm->info, o->urm->info+21, aux->info);
66,869,600
66,873,812
timer couldn't work with wiringPiISR (QtQuick application)
I have created a class Capteur_Input and one of the options in the constructor creates an interrupt using wiringPiISR wiringPiISR(m_pin, INT_EDGE_RISING, isrInput); my class also has an attribute m_impulsion and I am incrementing this value each time that an interruption happens. this what my interrupt handler looks li...
Static QObject instance is not supported in Qt, as stated below (QObject reentrancy section ): In general, creating QObjects before the QApplication is not supported and can lead to weird crashes on exit, depending on the platform. This means static instances of QObject are also not supported. A properly structured si...
66,870,436
66,870,489
A function to replace an element in a string with another element
I want to replace all of the Uppercase letters in string with lowercase letters is there any function to do so because the replace function is not giving any result. Here is my code.. for (int i = 0 ; i < string. size() ; i++ ) { if (string[i] >= 65 && string[i] <= 90) { string.repla...
You should read the documentation for replace - first argument is position of the substring to replace, not the character you want to replace. So, string.replace(i , 1 ,string[i]+32); should work. Personally, I would go with for(auto& p : string) p=std::tolower(p);
66,870,825
66,873,444
Why would a class need move operations to bind to a std::function that has a signature in which the class is passed by value?
In the following code: struct X { X() = default; X(const X&) { printf("copy construct\n"); } X& operator=(const X&) { printf("copy assign\n"); return *this; } X(X&&) { printf("move construct\n"); } X& operator=(X&&) { printf("move assign\n"); return *this; } // Replacing the above two lines with the...
std::function<void (X)> fx(f) constructor invocation is ill-formed. First, the requirements on this constructor: [func.wrap.func.con] template<class F> function(F f); 7 Constraints: F is Lvalue-Callable (20.14.16.2) for argument types ArgTypes... and return type R. [func.wrap.func]/2 A callable type (20.14.2) F is Lva...
66,870,981
66,872,040
Why is a std::function with signature void (X) allowed to bind to a function void f(X&&)?
In the code below, why is a std::function<void (X)> allowed to bind to a function void f(X&&)? #include <functional> struct X {}; void f1(X x) {} void f2(X& x) {} void f3(const X&) {} void f4(X&& x) {} int main() { X x; f1(x); // ok f2(x); // ok f3(x); // ok // f4(x); // doesn't compile ...
As you might know, the std::function type is a polymorphic wrapper around any function-like types. That include function pointer, classes with operator() and lambdas. Since it has to implement type erasure, it only checks if what you send is callable using the arguments it receives. The type erasure will simply do the ...
66,871,779
66,871,999
strange behavior while sorting vector of pairs
I am populating the following vector with non-negative integers for a codejam problem: vector<pair<int,pair<int,int> > > v; Following way of sorting fails the submission: sort(v.begin(),v.end(),[](auto a,auto b){ return a.first < b.first; }); But if i just change the sorting as below: sort(v.begin(),v.end()); Th...
Your lambda only takes the first element into account, but obivously a pair consists of two elements. With your lambda pairs with identical first but different second elements will be considered as equal. Thus their relative order after sorting is unspecified. If you want to sort data like the following: {1, {1, 1}}, {...
66,871,811
66,872,097
(Q. is little wrong So please check body) C float *q=NULL; printf("%f",q) ; output is 0.000000 but in C++ float *q=nullptr; cout<<q; give output 0?
[My Question is little weird but it's not right to change it now as it is answered with good explanation but I am Editing it with [Update].......[Update End] tag to avoid confusion to upcoming visitors to my post] C #include<stdio.h> int main() { float *q=NULL; printf("%f\n",q); } OUTPUT 0.000000 In C o...
printf("%f\n",q); The format specifier %f requires that the type of the passed object is of type double (float argument will be converted implicitly, so that is OK too). You passed a float* which is the wrong type. Passing argument of wrong type into printf results in undefined behaviour. printf("%p",q); This one...
66,872,573
66,872,712
Are Unit Tests with Google Test exported with project?
I've been studying Unit Testing with Google Test in C++. If the purpose of Unit Testing is to ensure certain segments or objects of the code are working the way they are supposed to, I would assume it's not necessary to compile and export the unit testing code with the final project, right? It's not like the user will ...
If you're publishing a library, it's quite common to publish the unit tests. Imagine you're developing on Mac or Linux, for example, and someone wants to compile on Windows. Well, they should probably be able to run your tests to ensure they pass on a different environment. Or Android, or some microcontroller. Whatever...
66,873,190
66,873,365
Why does console want me to enter something after I use cin.ignore?
I have an array and I need to remove one element from it by its name. When I'm entering a name of magazine I want to remove, an input line is called by console, and it doesn't matter what I'll put in there, I can even press an instant enter. int removeMagazine(string name[], double price[], int length) { if (length...
You don't need cin.ignore() after getline(). Unlike operator >>, getline() extracts also the delimeter character, leaving nothing in the stream. cin.ignore() reads and ignores exactly 1 character from cin. So if called after getline(), cin.ignore() will block until another character is entered.
66,873,418
66,873,566
Can you avoid out of range error if you use range based for loop instead of the standard for loop?
I was experimenting around with range-based for loop found that if you use range-based for loop to loop through a vector it runs into out of range error is there any way to avoid this error if you are using range-based for loop int main() { vector<int> num{ 1,2,3,4,5 }; for (auto i : num) { cout << ...
It's nothing to do with the type of loop. Your loop looks at all the values i inside the vector num, then it prints num[i]. One of them is 5, so it prints num[5]. But num has 5 elements so they only go up to num[4]. Out of range.
66,873,508
66,878,808
C# PInvoke of C++ function that returns struct by value crashes if the struct is left uninitialized
In this post they use a bool which can have variable size between platforms. No such thing is going on here. The struct is blittable. The method crashes on return if the struct is left uninitialized - I'm not sure why. Suppose I wanted to return a struct with random content. Is it simply that this is invalid C++? C++: ...
The problem was that the code was compiled debug-mode and runtime checks for (lack of) variable initialization were setting a breakpoint. Since this was P-invoked and I was attached to the calling C#, I couldn't see what was going on in the C++ and it was simply exiting with error code 0x80000003, as @HansPassant point...
66,873,558
66,873,915
search QStringView in QHash<QString, DataType> without memory allocation?
After parsing of text data I got QStringView. And I need to search if it exists in variable of type QHash<QString, DataType>. Is it possible without conversation of QStringView to QString, in other words is it possible without allocation? May I can use some other Qt type for this with similar to QHash functionality?
There is a technique called "transparent maps" that std::map, but not std::unordered_map or QHash supports. A transparent map allows non-key types to be used to look up elements, so long as they support == and they hash equivalently. As QHash doesn't support that you are in trouble. No QString constructor permits it t...
66,874,302
66,874,736
How to find common value
I have an area struct where i store upper_area. The struct is in map with AreaID as a key. Area can have direct upper_Area or indirect upper_area struct Area { AreaID area_id_; Name name_; std::vector<Coord> coords_; std::vector<Area*> lower_areas_; Area* upper_area_ = nullptr; bool check_area_ ...
I don't think that you can avoid having two loops. starting from here, you could do AreaID Datastructures::common_area_of_subareas(AreaID id1, AreaID id2) { std::unordered_map<AreaID, Area>::iterator areaIt1 = areas_.find(id1); if (areaIt1 == areas_.end()) { return NO_AREA; } std::unordered_map...
66,874,494
66,874,717
comparing char buffer to string not working
When trying to compare a char buffer to a std string in an if statement it's not working as intended Here is the code if (ConnectNamedPipe(hPipe, NULL) != FALSE) // wait for someone to connect to the pipe { while (ReadFile(hPipe, buffer, sizeof(buffer) - 1, &dwRead, NULL) != FALSE) { /...
Instead of reading the data into a char[] and then copying that data into a std::string, you could use a std::string directly. Building blocks: std::string cmd; cmd.resize(wanted_buffer_size); // Set the proper buffer size ReadFile(hPipe, cmd.data(), cmd.size(), &dwRead, nullptr); // Read directly into cmd cmd.resiz...
66,874,663
66,875,320
Printing a graph from a file
So basically I have a file that his lines compose a graph, in which the 1st line is the number of vertices and arcs and the rest is the connections. The problem is that in my graph printing function for some reason it doesn't print anything. Program: #include <iostream> #include <vector> #include <cstdlib> #include <cs...
The Problem here is the signature of your function declaration, which calls the graph by-value and not by-referrence. The latter one is needed to get a modifiable version of the object and not just a local copy. Since your version did a call-by-value, the graph object (initialized as empty vector) is not modified by th...
66,875,237
66,875,429
Does "try-catch" catches run time error (especially Out of Range error)
I'm following an example code from Programming Principles and Practice Using C++ in one of the example for exception it shows this snippet of code int main() { try { vector<int> v; // a vector of ints for (int x; cin >> x; ) v.push_back(x); // set values for (int i = 0; i <= v.si...
Does “try-catch” catches run time error (especially Out of Range error)? No, in C++ most run time errors lead to Undefined Behavior, not exceptions. Only errors which explicitly throw exceptions can be caught. std::vector<T>::operator[] does not specify that it throws an exception when you access out of bounds, it is...
66,875,463
66,875,663
abort called is showing in Hackerrank
I was solving a problem of the array in which I have to do a left rotation of an array. wrote the code and submit successfully some test cases passed in some it showing abort called I don't know whats the problem. I googled it shows it's due to storage becomes full. what if I declare my temp array in heap. would it mak...
The problem is in your 3 loops: for (int i = 0; i < d; i++) { temp[i] = arr[i]; } for (int i = 0; i < arr.size(); i++) { arr[i] = arr[d + i]; } for (int i = 0; i < arr.size(); i++) { arr[arr.size() - d + i] = temp[i]; } first loop will crash if d > n. It can be the case ...
66,875,565
66,875,723
Zero initialization of std::vector<std::array<double,10>>
Consider the following code std::vector<std::array<double,10>> a(10); If I understand the standard correctly a will not be zero initialized, because en.cppreference.com on std::vector constructors says Constructs the container with count default-inserted instances of T. No copies are made. So because default initi...
It's correct that the overload will default insert elements. But you have to keep on reading, as default insertion means that the values inserted will be value initialized, and value-initializing an aggregate (like std::array) will value-initialize all elements in the aggregate. And value initialization of double value...
66,875,879
66,876,036
Reading a file and ignoring whitespace
how can you able to convert video.movieTitle, video.movieGenre and video.movieProduction into a string. I test my program but it only reads the line and ignore whitespace. while((infile,"%d\n",&p->video.videoID), fscanf(infile,"%s\n",p->video.movieTitle.c_str()), fscanf(infile,"%s\n",p->video.movieGenre.c_str()...
As others have commented, fscanf is the wrong tool for this job. Even in C, using fscanf with the %s conversion would still be the wrong tool1. As it stands now, your first fscanf will read and convert the first number (the video ID) correctly. But fscanf's %s conversion reads only a single, white-space delimited strin...
66,875,929
66,876,226
How do I force this template to only accept an integer of a matching type?
template <typename integral_t, integral_t empty_Value> struct IntegralHandle { IntegralHandle(const integral_t value) : value(value) {} // Initialised with value IntegralHandle() : value(empty_Value) {} // Not initialised, handle is empty bool isEmpty() { return value == empty_Value; } ...
We can do it with std::numeric_limits and a larger non-type parameter, something like this: template <typename integral_t, auto empty_Value> struct IntegralHandle { static_assert( std::numeric_limits<integral_t>::min() <= empty_Value && std::numeric_limits<integral_t>::max() >= empty_Value && ...
66,876,140
66,876,401
C++ Dynamic Arrays Creation
I am prompted with the question as follows Write a program that prints dynamic arrays. The program creates an int 1D dynamic array of 3 elements and a float 2D dynamic array of 3 ROWS and 3 COLS. Initialize both arrays with random values. Both arrays will be printed separately in two separate functions void print_2d_...
You never allocate memory for the 1D int array, nor for the float 2D array. Your declarations are also wrong, for example float** arr_two[3][3] is an array of size 3 of arrays of size 3 of pointers to pointer to float, clearly not what you want. Your code should look more like this: int *arr = new int[3]; // pointer to...
66,876,384
66,876,455
Problem with c++ sorting of objects, vectors
Consider the following code: #include <iostream> #include <vector> #include <algorithm> using namespace std; class Vertex { public: int id; vector<Vertex*> edges; Vertex(int id) : id(id) {} int get_id() const {return id;} }; class Graph { public: vector<Vertex*> vertices; Graph(int V) ...
The parameters of your comparators are non-const references. More specifically, "references to non-const pointers to const Vertex". You either need const references: const Vertex *const &one, or even better, just pass by value: const Vertex *one. Also note that &*one < &*two is equivalent to one < two.
66,876,586
66,876,684
Applying the lvalue-to-rvalue conversion to variable `x` does not yield a constant expression in the code below. Why is that?
The snippet below was obtained from DR 2083 by Hubert Tong. extern int globx; int main() { const int &x = globx; struct A { const int *foo() { return &x; } } a; return *a.foo(); } Then the author writes: x satisfies the requirements for appearing in a constant expression, but applying the lval...
Applying the lvalue-to-rvalue conversion to x reads the value of the mutable global variable globx, which makes it not a constant expression as the value of globx is subject to change (and, even if it were const, there would be the issue of its value not being known at compile time). Of course, this is not surprising: ...
66,876,605
66,902,248
getting corrupt file error while connecting c++ with mysql
I'm trying to connect MySql with C++ using visual studio 2019 but i'm getting a corrupt file error ,I downloaded the no-install-1.1.12-winx64 version of the connector(my pc is 64bit), then i downloaded boost 1.75.0 and linked it. i did my linkings as follows: (on All configurations, Win32/x64 platforms): Configuration ...
Ok so basicly i solved it with the most "programmer" way ever, I just went crazy and deleted the whole project and started again, this time making sure that everything is x64 bit (i made sure that its 64 bits before but it seems i overlooked something) and made sure that i followed the docs word by word, and what do yo...
66,876,641
66,877,381
Return words from a file alphabetically
I'm attempting a little self learning while on spring break I've created a program that will accept words store them in a file then print them out to the console. I am looking for the best way to print them in alphabetical order instead of the order they were inputted. I have seen a few examples online of how to do thi...
A vector is a homogenous container of variable size. It's the default container you should use, provided there are no special requirements for what you're doing. If you put the words in a std::vector, you can then use std::sort() to sort it alphabetically. Here is an example: #include <iostream> #include <algorithm> #i...