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
63,327,473
63,358,916
JPEG Decoding problems with WIC
I am currently trying to load images from disk into memory using WIC. I used the MSDN documentation here to write my code. Everything works fine for loading PNG images. Loading JPEG images works without any error but does not produce the correct result! The interesting thing is, that when I convert the image from JPEG ...
The code above is totally fine and works! The problem was in the omitted DirectX 12 Feature support check: ID3D12Device->CheckFeatureSupport(...) I forgot an inversion which resulted that the following code snipped was executed memcpy(&frameNativeFormat, &GUID_WICPixelFormat32bppRGBA, sizeof(GUID)); targetFormatDx = D...
63,327,543
63,327,607
Can a code run if initial array value is less then input value?
I am confused after the following C++ code executed: #include <iostream> using namespace std; int main() { char name[0]; int roll; cout << "Enter your name: "; cin.get(name, 30); cout << "Enter roll no.: "; cin >> roll; cout << "You have entered:" << '\n'; cout << "Name: " << name << '\...
This code: char name[0]; cin.get(name, 30); invokes undefined behavior because name does not have enough space to store 30 chars. This means anything can happen, including the program appearing to work sometimes. Instead, you can do: std::string name; std::cin >> name; // or std::getline(std::cin, name); // if you wan...
63,327,868
63,327,950
Failed to print data of a linked-list
I'm learning about linked list than I wrote a code where I expected to see data1 and data2 displayed on the console window. However, only data1 showed up and I couldn't figure out why. I wonder if I wrote the member function print() wrongly. Thanks. Define class node as below class node { public: node(T _da...
Print should not be a member function. Instead write a global function like this (I've renamed the function print_list). void print_list(node* n){ while (!n->isEnd()){ std::cout << n->getdata() << endl; n = n->getlink(); //go to the next node } } Use it like this pri...
63,329,118
63,329,153
Segmentation error in simple inheritance related code
Shortened code I wrote for learning purposes. Still the way it is, it doesn't work properly. Removing last line (&&) it works OK, but with it, code doesn't reach line noted as ##, expressing segmentation error, after the "BazOnly" text displayed. #include <stdio.h> #include <iostream> #include <string> using namespace...
string setstr(string& val){ //str.assign(val); num= 7; } This method is declared as returning a std::string, but nothing actually gets returned from it. This is undefined behavior. Most modern C++ compilers will warn you about this. If yours' did, this is an example of why you cannot ignore w...
63,329,639
63,334,036
Different declarations of the lambda that capture the parameter inside the C++20 requires expressions
Consider the following two simple concepts: template <typename T> concept C1 = requires(T t) { [t = t]{ t; }; }; template <typename T> concept C2 = requires(T t) { [t]{ t; }; }; In my opinion, the two declarations should be equivalent, but GCC rejects the concept C2 and says: <source>:10:9: error: use of paramete...
A simple-capture (like [t] in your second example) can only capture local variables and/or this. However, the parameters of a requires-expression aren’t local variables. That’s not an issue for init-captures (as in your first example).
63,329,779
63,329,879
Can we rename cout, endl keyword in cpp?
As typedef can give change names of types and define can make an alias for values and functions, Is there any way to change the name of cout, endl etc???
Two ways to do that. In C++ sense, you could use std::ostream: #include <iostream> std::ostream& alias = std::cout; Or, in a better manner, use reference to auto to let the compiler decide the correct type. auto& print = std::cout; Some important notes: You can't create aliases of std::cout, std::endl, etc. with usi...
63,329,897
63,337,332
Calculating the exact needed height for a QTableWidget
I want to calculate the exact height a QTableWidget needs so that no vertical scroll bar is shown. What I do right now is for example: tableWidget->setMaximumHeight(tableWidget->horizontalHeader()->height() + tableWidget->rowHeight(0) * 4 + 4); for this case,...
You can get tableWidget's height with "tableWidget->viewport()->height()" . Regarding the vertical scrollbar, you can use this functions. setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff) Then, the vertical scrollbar will be permanently hidden.
63,329,986
63,330,002
Why does the type deduction for std::endl fails?
In the following code: #include <iostream> auto& print = std::cout; // Type deduction for std::cout works auto& end = std::endl; // But the std::endl is exception here int main(void) { print << "Hello" << end; return 0; } The type deduction for std::cout takes place properly, but why doesn't it works for std:...
std::cout is an object of a concrete type std::ostream (aka the std::basic_ostream<char> specialization), so auto can deduce its type. std::endl is not an object at all, it is a template function (specifically, a stream manipulator taking a templated std::basic_ostream object as a parameter): template< class CharT, cla...
63,330,104
63,331,157
How to use boost::beast, download a file no blocking and with responses
I have started with this example so won't post all the code. My objective is to download a large file without blocking my main thread. The second objective is to get notifications so I can update a progress bar. I do have the code working a couple of ways. First is to just ioc.run(); and let it go to work, I get the fi...
I strongly recommend against using the low-level [async_]read_some function instead of using http::[async_]read as intended with http::response_parser<http::buffer_body> I do have an example of that - which is a little bit complicated by the fact that it also uses Boost Process to concurrently decompress the body data,...
63,330,114
63,330,613
Unable to use the "runas" verb on programs requiring UAC
I have the following C code that should run the default Windows program changepk.exe with an UAC prompt ShellExecute(NULL, "runas", "C:\\Windows\\System32\\changepk.exe", 0, 0, SW_SHOWNORMAL); (Side note that the output of the ShellExecute is 2). However, when I try to execute the 'changepk.exe' with these lines nothi...
Error 2 is ERROR_FILE_NOT_FOUND. Make sure that changepk.exe actually exists on your machine at that path. More importantly, if your app is a 32bit EXE running on a 64bit Windows, then you are likely encountering the File System Redirector at work, which will redirect "C:\\Windows\\System32\\..." to "C:\\Windows\\SysWO...
63,330,115
63,330,704
Time Limit Exceeded [c++] : last digit of each of numbers' factorial
I have a Time Limit Exceeded error in my c++ code. It's a simple algorithm that output the last digit of each of numbers' factorial given by the user. Example1 : Input : 4, output : 4, explanation : 4! = 4 * 3 * 2 * 1. = 24. Last digit of 24 is 4. Example2 : Input : 5, Output : 0, Explanation : 5! = 5 * 4 * 3 * 2 * 1...
This is what you need? #include <iostream> #include <vector> int FactLastDigit(int n) { if (n > 4) { return 0; } else { long int number = 1; for (int i = 1; i <= n; i++) { number *= i; } return number % 10; } } int main() { int ...
63,330,463
63,330,530
Overloading C Preprocessor Macros - Discimination Based on Call Syntax
I'm currently working on a cpp logger which aims at displaying the __FILE__ and the __LINE__ before each printed message. In my case, we are mostly using 2 methods for printing out: printf-style and std::cout-style. For the moment I have a macros for each style: #define HATFormatFatal(...) HATLogger::logFormat(HATLo...
The simplest approach would be not overloading the macro at all, but instead having the macro return an object that has both operator<< and operator() overloaded. Something like this: class error_logger { public: error_logger( HATLogger::LogLevel level, char const * file, char const * line ...
63,330,626
63,340,661
Why is defining the type of a pointer causing issues in my code?
When initializing a pointer to allocate memory in the heap, should we specify the type as a pointer? That is, should it be: int* ptr = new num; OR ptr = new num; Both seem to work, and I was under the impression that the first method is better, but doing it is causing some issues in my code below. I have a class with...
The short answer is that you are misunderstanding the distinction between locally scoped variables and class members. One way to think about this is that you only need to tell your program the type of an identifier once. In your class definition you declare two pointers using the type int (int *pa,*pb), but in your con...
63,330,694
63,368,155
Output values from VVC VTM reference software to a text file
Edited code from CABACWriter.cpp This is the code I used to get the no.of bits in a macroblock and output them to a text file: int before; int after; int diff; ofstream outfile; outfile.open("Macroblock.txt"); if (isEncoding()) { before = m_BinEncoder.getNumWrittenBits(); } coding_unit( cu, pa...
So I figured it out. This is the correct answer to get what I was looking for: int before; int after; int diff; ofstream outfile; outfile.open("Macroblock.txt", ofstream::app); if (isEncoding()) { before = m_BinEncoder.getNumWrittenBits(); } // coding unit coding_unit( cu...
63,330,890
63,338,799
Reference to any character in a string::string in C++
I want the reference to the i th character of a string name. I couldn't a find a function for the same.
This is the sort of question that begs for a good C++ reference. Look up std::string in that reference (which might redirect you to the more general std::basic_string), then look for a member function that lets you access characters (or "elements" as a more general term). For example, cppreference.com lists the member ...
63,331,161
63,331,304
Is placeholder for the deduced class type of non-type template parameter a C++20 feature?
With the addition of non-type template parameter of class type into the C++20 standard (P0732R2) was introduced the possibility to declare a non-type template parameter using a placeholder for deduced class type for non-type template parameter [dcl.type.class.deduct]§2: A placeholder for a deduced class type can also ...
Is placeholder for the deduced class type of non-type template parameter a C++20 feature ? Yes. [temp.param]/6 is quite clear about this: A non-type template-parameter shall have one of the following (possibly cv-qualified) types: a structural type (see below), a type that contains a placeholder type ([dcl.spec.aut...
63,331,264
63,360,589
Stripping only function names of a binary with wildcard exclusion
I want to strip my binary in a way where certain function names are retained since the binary is a shared library and all other function names are stripped from the symbol table. Using the -g switch removes all debug information which is great but that does not include the function names. If I use --s --wildcard --keep...
If I use --s --wildcard --keep-symbol="blabla_*" --keep-symbol="blabla" ... it still strips too much and breaks compatibility. You are probably confused: since your binary is a shared library, it doesn't need any symbols in its regular symbol table (the one displayed by nm foo.so) -- it only needs the dynamic symbol ...
63,331,359
63,332,387
Detecting type inclusion in std::tuple at compile time
My goal is to write a function that: is callable at compile time takes a template argument Tuple that represents an arbitrary std::tuple takes a template argument Match that represents the type to test for returns true if the tuple has 1+ element of type Match I'm on GCC 10.2, which I can upgrade if needed. I could a...
Here's another solution that is pretty similar to @HolyBlackCat's answer, but uses std::disjunction instead of a fold-expression, and can be used the same way you have in your question (it doesn't require ::value for the usage): template<typename, typename> struct tuple_holds; template<typename ...Ts, typename T> stru...
63,331,546
63,331,684
How to customize std::make_heap comparison function based on some data structure?
I am trying to use std::make_heap which has most of the properties I need. I have a vector of ints which are just the indices of my data structure and I want the heap to be built upon some property of that data structure. If I want to have a lambda function for comparison it would be simple: [](int x, int y){return ele...
std::make_heap takes three arguments: two iterators denoting a random access range, and a comparison function. Simply provide your custom comparison function are the third argument. #include <algorithm> #include <vector> // ... std::vector<Foo> v{/* ... */}; std::make_heap(v.begin(), v.end(), [&elementList](auto lhs...
63,331,579
63,331,705
Size of reference to std::array not available at compiletime
I'm interested to know why the second static_assert in my code below doesn't work. It seems like even though the array c is a reference to a, the size of the array is embedded in the type, so it should be available at compile time. #include <array> int main() { std::array<int,2> a = {1,2}; std::array<int,2> b ...
the size of the array is embedded in the type, so it should be available at compile time. This is true. But regardless, c is not a constant expression and therefore expression that contains it as a subexpression cannot be a constant expression - except certain operators that interact only with the type of the operand...
63,331,661
63,335,614
Trying To Run C++ Code, A "Procedure Entry Point" Error Occurred
I've been trying to run this piece of code: #include<iostream> #include<vector> using namespace std; int main() { vector<int> s = {0}; cout << s[0] << endl; return 0; } But there is an error that is popping: I tried to run it using cmd, by writing g++ Source.cpp Which compiled into a.exe and I can't ...
Edit: The Answer brought by ted helped me! I wrote g++ -static Source.cpp and then I ran the code flawlessly! I added it to the compiler options in atom and that works as well! Thanks guys! I love this community :)
63,331,787
63,332,797
Why is dereferencing of nullptr while using a static method not undefined behaviour in C++?
I was reading a post on some nullptr peculiarities in C++, and a particular example caused some confusion in my understanding. Consider (simplified example from the aforementioned post): struct A { void non_static_mem_fn() {} static void static_mem_fn() {} }; A* p{nullptr}; /*1*/ *p; /*6*/ p->non_stat...
Standard citations in this answer are from the C++17 spec (N4713). One of the sections cited in your question answers the question for non-static member functions. [class.mfct.non-static]/2: If a non-static member function of a class X is called for an object that is not of type X, or of a type derived from X, the be...
63,331,843
63,331,913
Different assignments in pointers
As you can see in the code, I assign different values to the pointer: fin->siguiente = nuevo_nodo; fin = nuevo_nodo; Does this make any difference? void append(Nodo *&frente, Nodo *&fin, int valor){ Nodo *nuevo_nodo = new Nodo(); nuevo_nodo->valor = valor; nuevo_nodo->siguiente = nullptr; if(empty(fre...
As you have changed to question, I will change the answer too. When your else part runs, you assign 'fin->siguiente = nuevo_nodo'. Say 'fin' was initally at address 1000 and 'nuevo_nodo' as at address 2000. fin's siguiente pointer is pointing to address 2000. In the next line you assign 'fin = nuevo_nodo', so fin now p...
63,332,471
63,332,617
C++ Remove string as duplicate in vector based on partial match of substring
Is there an efficient way to remove a string as a duplicate based on a match of a substring? Consider a vector (combinedvect) containing a number of CSV strings of the same form: 'QWERTY, PROTMD, PEDKF, 12345.15454' 'ASDFGH, LDMEMA, PWEMDE, 23456.938984' 'ZXCVBN, NMDFN, MNMWNS, 34567.903' 'ASDFGH, LDMEMA, PWEMDE, 23444...
This is working as you want: #include <vector> #include<string> #include<algorithm> #include<map> #include <iostream> int main() { std::vector<std::string> v{ "QWERTY, PROTMD, PEDKF, 12345.15454", "ASDFGH, LDMEMA, PWEMDE, 23456.938984", "ZXCVBN, NMDFN, MNMWNS, 34567.903", ...
63,332,529
63,333,355
Appended strings producing a string that is multiple lines
I am trying to write a program that figures out the path to a person's desktop (on macOS) and creates a text file. For testing, I made it output the path as well. Here is the code: #include <iostream> #include <string> #include <fstream> #include <cstdio> using namespace std; int main(){ char text[255]; //finds ...
To fix the pathvar string, I deleted "\n" from it using this: pathvar.erase(std::remove(pathvar.begin(), pathvar.end(), '\n'), pathvar.end()); Which fixed the outputted path and allowed for the creation of the text file on my desktop. The original issue was due to fget including \n when reading the "whoami" fi...
63,332,778
63,334,526
Is there any way to improve the acl lib of DPDK
I am learning about the ACL lib of DPDK and I want to speed up the ACL classfication process.Is there any way or suggestions to make it?
As a user of the rte_acl library you could take few aspects into considerations to get best classification/lookup performance: Classification method: In rte_acl_init() one of the highest classification method is choosed as default one. CPUs which are AVX2 supported vector instruction set would give very good classific...
63,332,855
63,339,182
Remove object from vector if private variable matches
I have a class Inventory class Inventory { private: vector<Item> items; public: void addItem(Item item) { items.push_back(item); } void removeItem(string n) { # Complete this } } And a class Item class Item { private: string name; ...
The correct way of doing this is to use the combination of std::remove / std::remove_if and erase. You can find the documentation in the CPP Reference here and here. In the std::remove example code, you can see also the combination of remove and erase. You can also find tons of similar examples here on SO. std::remove_...
63,333,338
63,333,396
std::basic_string as a parameter of a function template cannot be deduced from const char*
Why does putting std::basic_string as a parameter of a function template will fail to deduce from const char*, but it can be deduced successfully when it is constructed directly? #include <string> #include <iostream> template<class Char/*, class Traits, class Allocator*/> //^doesn't matter whet...
Because implicit conversion (from const char* to std::basic_string<char>) is not considered in template argument deduction, which fails in deducing the template parameter Char. Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload resolution, whic...
63,333,462
63,333,483
Is there a way to put a vector into a pair in brackets
So I would like to put this vector into a pair for animation states. However, obviously this doesn't work because apparently it doesn't match the argument list. So basically my question is, is there a way to create a vector in a pair without using brackets? Here's my code. std::vector < std::pair < std::string, std::ve...
Braced initializer lists are typeless, and cannot be deduced when using with forwarding references, such as the ones used in std::make_pair's constructor. You must explicitly type them: std::pair < std::string, std::vector < int > > animations ={ std::make_pair("PlayerStand.png", std::vector<int>{ 0,0,0,0 }) };
63,333,536
63,333,583
condition_vairable::wait_for() question using Stroustrup example
The following example code is from Stroustrup C++ 4th Ed Page 1234. I'm questioning if this is errata not listed in his errata document. The code throws a system error due to timeout, when from what I have read about wait_for on the specs page can return spuriously. Therefore, not_empty == false and it may not be th...
You are referring to this part: 1) ... It may also be unblocked spuriously. The crucial detail is that this is describing only wait_for's first overload, that's what "1)" means, which does not use a predicate. The 2nd overload is the one that has a predicate parameter. The second overload gets described below, and it...
63,334,011
63,334,093
Is there a way to do in-place member construction in C++ (without copying and destructing an object)?
So, I finally tracked down a strange crash in my software, which is happening because of an issue that I've run into before: m_member = Foo(var1, var2) Which I've realized is performing a construction of Foo using var1 and var2, assigning this instantiation of Foo to m_member via a copy assignment, and then is deletin...
A few options there, assuming your problem comes from the copy assignment: Use a pointer type instead Change m_member to be a Foo*, or better a std::unique_ptr<Foo>, to better match the previous behavior, and then do: m_member = std::make_unique<Foo>(var1, var2); No copy, will still be destroyed at the end of your...
63,334,513
63,334,551
Unresolved external symbol error using uint16_t c++
endianness.cpp #include "endianness.h" #include <cstdint> using namespace io; void switch_endianness(uint16_t* n) { *n = (*n >> 8) | (*n << 8); } void switch_endianness(uint32_t* n) { ... } void switch_endianness(uint64_t* n) { ... } endianness.h #ifndef ENDIANNESS_H #define ENDIANNESS_H ...
In my endianness.cpp file I changed the function declarations to include the folder directory it was in and now it works.. (As it was complaining about this in the header file not being able to find function definition) void io::switch_endianness(uint16_t* n) { ... }
63,334,555
63,335,485
How to store more than 2 values in multimap?
im stuck at a problem, How do we store 3 values through multimap. For example one int and 2 c++ strings. How do we store those 3 values. I tried making a struct and storing 2 strings and then passing it in multimap code as struct names{ std::string name; std::string secondname; }; and done with multimap<int, names>Mult...
Please define type of pair too like this: struct names{ std::string name; std::string secondname; }; multimap<int, names>Multimap; Multimap.insert(make_pair<int, names>(number,{"name","secondname"}) ); // or simply you can use pair() too instead of make_pair()
63,335,115
63,335,185
How to use a templated typedef on capturing lambda parameter?
So I've been learning about templates and lambdas so I tried to combine the two. I am trying to create a templated typedef that specifies what the lambda is supposed to return and accept. It works well for non capturing lambdas but it cannot handle any lambdas that capture. This is my code for now: template<typename T>...
L is decalred as function pointer type. Lambdas without capture list could convert to function pointer implicitly, but lambdas with capture list can't. This user-defined conversion function is only defined if the capture list of the lambda-expression is empty. You can use std::function instead. template<typename T> u...
63,335,336
63,335,503
How to save memory when using a trie?
I came across this quesiton: https://atcoder.jp/contests/agc047/tasks/agc047_b and my code is as follows. My solution is very similar to the editorial. I'm confused why this has memory issues. I make 10^6 * 26 nodes in the worst case scenario. The memory limit is 1024MB which seems like much more than enough. How is me...
With 26 million nodes and 1024 megabytes, each node will need to be less than 40 bytes. But sizeof(node) is going to be at least 112 bytes, just for its members. The "self-referential" part comes from 26 pointers, each of which needs to be 4 bytes to support 1024MB. You'll need another data structure. One solution is t...
63,335,538
63,336,166
Selecting a method using different enable_if conditions
I want to write a generic validate function. So i tried writing a meta program. But it does not gets compiled, and rightly so. Can anyone tell me a way to achieve it. I am posting my sample code. There can be 3 or more types of structs (here A, B, C), some having a particular type of header, another having other type o...
if constexpr can be a means for partial compilation, but the condition inside if must always be compilable. In your case v1<St> and v2<St> only exist when St is of the right type, hence the errors. You can use specialization of variable templates instead, e.g. like this template<typename, typename = void> constexpr boo...
63,335,560
63,335,659
In C++, std::atomic generates race condition. But when using std::async, it generates race condition
In C++, std::atomic generates race condition. But when using std::async, it generates race condition. std::atomic<int> k = 0; int func() { for (int i=0; i < 1000000; i++) { k++; } return 1; } int main(void) { auto fut = std::async(launch::async, func); auto fut2 = std::async(launch::...
You have to wait until your async call is finished. fut.wait(); fut2.wait(); std::cout<<"k : "<<k<<std::endl; On my PC I got with your code always 0!
63,336,050
63,452,310
How can I shift elements to left (in order to implement erase) in c++ container?
From my previous question: How to implement erase on vector in c++, I have tried to implement erase via allocating new memory, and copying all elements except of that one erase to new array. From the answers, it is not a standard way of vector from STL, where the vector keeps old elements untouched, and only moves elem...
To compile I needed to add this method declaration: T* erase(T *const i); I added some quick test code to recreate your segfault: int main() { Vec<int> test; test.push_back(1); test.push_back(2); test.push_back(3); test.push_back(4); test.erase(test.begin() + 2); std::cout << test[2] << std::endl; // sho...
63,336,090
63,369,103
Windows CMake GUI cannot find Boost library
This is my first time using cmake gui in windows. I am trying to install the vsomeip library in Windows. This is mainly required for my common API someip application. Now, I am having issue to compile the vsomeip library. When I run CMake gui, it says Could NOT find Boost (missing: system thread filesystem) (found suit...
I fixed the issue by changing the boost version inside the boost/version.hpp. Previously the version was written as 1_55_0. So I just changed the version to 1_55. The other fixed was to add the environment variable Path. I added the boost include directory itself: C:\local\boost_1_55_0\boost I am not sure this is the r...
63,336,211
63,336,885
Building SDL2 using hunter
I'm trying to include SDL2 using the Hunter package manager. hunter_add_package(sdl2) find_package(SDL2 CONFIG REQUIRED) The package is downloaded, but the include dir is not being defined, so this does nothing include_directories(${SDL2_INCLUDE_DIR}) and the compile fails, on trying to #include SDL. If i manually in...
Yes, that warning is very related. You should set the CMP0074 policy to the NEW behavior: cmake_policy(SET CMP0074 NEW) That will make it honour the settings offered by the SDL_ROOT variable.
63,336,800
63,343,931
How to separate botan encryption and decryption operation via command line argument?
i try to explore c++ cryptography using botan. From the provided example,the method of encrypt and decrypt a plaint text is shown below include <botan/rng.h> #include <botan/auto_rng.h> #include <botan/cipher_mode.h> #include <botan/hex.h> #include <iostream> int main() { Botan::AutoSeeded_RNG rng; const std::s...
The problem is that you are trying to decrypt the hex-encoding of the encrypted plaintext. You encrypt the plaintext and write the hex-encoding of the encryption to the file. For decryption, you read the hex-encoding into encordedText, and then you construct a Botan::secure_vector tmpPlainText from the data contained i...
63,337,011
63,337,218
C++20 concepts: multiple return type requirements?
I want to implement a concept in which there are multiple return types of the member function. Ex: template<typename C> concept Container = requires(C a) { {a.begin()} -> std::same_as<typename C::iterator> || std::same_as<typename C::const_iterator>; }; The code above is to enforce the return type ...
Use the unsugared form. template<typename C> concept Container = requires(C a) { requires std::same_as<decltype(a.begin()), typename C::iterator> || std::same_as<decltype(a.begin()), typename C::const_iterator>; };
63,337,303
63,337,641
How can I prevent overshadowing during ADL?
Suppose I have a class that extends a (STL) container and provides a customary begin member function: #include <vector> template <typename Cont> struct Bar { Cont c; auto my_begin() { return begin(c); } }; int main() { Bar<std::vector<int>> b; b.my_begin(); } By ADL, I do not have to specify std:: be...
You can just use the two step method: auto begin() { using std::begin; //1 return begin(c); //2 } 1: bring std::begin into consideration 2: If c has begin() in its namespace, call that, otherwise default to std::begin() You can read more about it here
63,337,346
63,338,113
Create a template function that returns different tuple types depending on template argument types conditions
First, is it even possible to return different types depending on some condition? Second, is there a more concise way to handle this kind of mapping, without enumerating all possible if's and else's? here are lots and lots (and lots) of if's, and's and but's Basically, I want to define an incomplete tuple, which I wa...
C++17 solution, C++11 if you replace _v usings with ::value. Does not require distinct bases, but it will always replace each default base in the default tuple by the left-most matching type in the passed tuple argument. #include <tuple> #include <type_traits> // Returns the first type from Ts that is derived from Ba...
63,337,454
63,337,668
Using basic arrays for compatibility
Imagine a function from a library that takes an array as argument, in their own code, the users may use various array implementations, some will use std::vectors, some will use std::array, some will use basic arrays, some may even create their own classes, we can't satify every user. But every type of array works with ...
could using a pointer and a size (if needed) as arguments solve this problem ? Yes. That's typical C-ish api used since forever, like string functions with bounds checking or mem* functions like memcpy or memcmp functions or qsort takes a pointer and count of elements etc. But C++ saw that not every "array" has to be...
63,338,608
63,339,241
Get address of const method
I would like to be able to form a pointer-to-member type knowing only the class itself and method name. Unfortunately I am not able to do so having a const and non-const method variants in my class. Example code snippet: struct A { void method() {} void method() const {} }; int main() { decltype(&A::method...
You can do it like this: struct A { void method() { cout << "Non const\n"; } void method() const { cout << "const function\n"; } }; int main() { typedef void (A::*method_const)() const; method_const a = &A::method; //address of const method typedef void (A::*m...
63,338,609
63,338,667
Qt add statically parameters to connect directive
My code looks like this: connect(c_name, SIGNAL(stateChanged(int) ), employeesList, SLOT(changeVisibility(int))); where c_name is a QCheckBox, and i would like to connect its stateChange to the visibility of an attribute in employeesList, which method looks like this: void changeVisibility(int prop, int visibility){ ...
Using lambdas should indeed resolve your problem: connect(c_name, &QCheckBox::stateChanged, employeesList, [employeesList](int visibility){employeesList->changeVisibility(Class::first_enum_property, visibility);}); Note that the third argument (i.e. the context object) is optional, but useful to automatically destruct...
63,339,040
63,339,210
What do you do in C++ if you ask for an integer and the user inputs "b"?
I'm new to statically typed C++. In JavaScript, I could just check the data type first, but that seems to be very complicated, and the answers all seem to imply that you aren't "getting" the language. here's the code I was testing out rand() with, where I came upon the issue of converting strings to integers: int main...
Regarding to the documentation of std::stoi it throws an std::invalid_argument. What you could do is to place your std::stoi call inside a try and then catch the std::invalid_argument, but personally i wouldn't do that. Instead, it is (most likely) a lot better to check if the first character of your input is an int, b...
63,339,179
63,339,514
Is there a more concise way to initialize a unique_ptr<char[]> than this?
So at the moment I have: std::string a; std::unique_ptr<char[]> b(std::make_unique<char[]>(a.size() + 1)); std::copy(std::begin(a), std::end(a), b.get()); Is it is possible to initialize this directly in one step?
Is it is possible to initialize this directly in one step? I would suggest keeping it as std::string or std::vector<char>. However, if you really insist, Yes! Using an immediately invoking a lambda, this can be done. std::unique_ptr<char[]> b = [&a]() { auto temp(std::make_unique<char[]>(a.size() + 1)); std::co...
63,339,921
63,341,221
Cannot deduce function return type
This doesn't work with either gcc-10 or clang-10. template <typename R, typename T> auto invoke_function(R (&f)(T), T t) { return std::invoke(f, t); } invoke_function(std::to_string, 42); This works with gcc-10, but not clang-10. template <typename R, typename T> auto invoke_function(T t, R (&f)(T)) { return std::inv...
It isn't clear why this code is rejected. Since T is deduced, the overload of std::to_string can be determined. That's not how it works exactly. Template deduction deduces each parameter/argument pair independently first - and then we bring all the deductions together and ensure that they're consistent. So we deduce ...
63,340,030
63,340,088
find_first_of with multiple characters doesn't return string::npos when substring shouldn't be present
I've written a small snippet like this: #include <string> #include <iostream> int main() { std::string s1{"abcdefghijklmnop"}; std::cout << "s1(fg) = " << s1.find_first_of("fg") << '\n'; std::cout << "s1(fo) = " << s1.find_first_of("fo") << '\n'; } I expect that it returns 5 and string::npos, but it actu...
std::string::find_first_of returns the position of any of the characters you supply to it. In your case, it finds f both times. You should be using std::string::find.
63,340,072
63,353,465
Function using struct template - function(struct<T1> x, struct<T2> y)
my problem is similar to - Template function accepting any type similar to map<X, Y> - yet, it didn't solve it, because I'm using already templated object. typedef struct _foo { int x, y, z; } Foo; // Note - it cannot be specialized for CBufferInt, CBufferFloat // because it holds additional informations, left the...
Thanks @Asesh for suggestion, it helped me "solve" this problem (I have too low rep to give upvotes :< ). The way that worked for me was: class RaytracingResources { public: RaytracingResources() = default; } template<typename T> inline void CreateRaytracingPipeline(CBuffer<T> cb) { } When I was trying to declare...
63,340,419
63,340,647
Protected method in UML diagram?
I have the following UML showing how to create a class Point2D. I have created a header file for this class based on the UML: #ifndef Point2D_h #define Point2D_h using namespace std; // Header file for class Point2D class Point2D { protected: int x; int y; double distFrOrigin; se...
Total freedom C++ gives you total freedom for this. You may for example: group the members by access specifier. You could inside a section optically group variables and functions; group the members à-la UML, with variables on one side and functions on the other, having each time a private, protected and public sectio...
63,340,664
63,340,918
Gradually resizing image inside an imshow window OpenCV C++
I have a Windows form where I have a button, zoom out. How can I resize the image in this way when I click zoom out? I tried resize() but I did not figure out how to gradually zoom out every time the user clicks zoom out? How can I achieve that
If you wanna protect the aspect ratio, its not possible because there can not be common divisor for width and height for couple iteration. After a while, it ll crash anyway(if width and height not equal). You can determine the ratio according to your requirements. I just chose 1.05 and tested, looks fine. You can do it...
63,340,677
63,341,166
Name Lookup - operator>> Not Found
I fail to understand the reason why the code below does not compile. Live. Thank you. #include <iostream> #include <iterator> #include <sstream> using namespace std; namespace N { class C { public: enum class E { a, b, c }; }; } using U = N::C::E; istream& operator>>( istream& is, U& e ) { //... return ...
https://en.cppreference.com/w/cpp/language/adl Because of argument-dependent lookup, non-member functions and non-member operators defined in the same namespace as a class are considered part of the public interface of that class (if they are found through ADL) So, move istream& operator>>( istream& is, C::E& e ) int...
63,340,778
63,340,905
How to choose iterator direction at runtime
I'd like to choose the direction to iterate over a container at runtime, like in the following sample code: #include <iostream> #include <vector> void iterate(bool forward, std::vector<int> v) { auto start = v.begin(); auto end = v.end(); if (!forward) { start = v.rbegin(); // this doesn't end = v.rend()...
With a little bit of indirection, ie, using a helper function you can make a call to a template function that accepts the iterator types you want to loop with like template<typename Iterator> void iterate_helper(Iterator start, Iterator end) { for (auto it = start; it != end; ++it) { std::cout << *it <...
63,341,322
63,341,460
Calling the default constructor on c structs
The code below compiles just fine (unless the call to method is uncommented). Why is it allowed to "call" to the default constructor? (there shouldn't be one) Why is the declaration of the member function not an error? . extern "C" { struct S { int some_int; void method(){} }; } int main(...
First, S s(); declares a function named s that takes no arguments and returns an object of type S. Just like int f();. Second, that extern "C" isn't relevant here. It's used, roughly, for functions that are written in C and called from C++. It doesn't mean "pretend that this code is C code". Third, S does have a defaul...
63,341,575
63,341,645
Why this code of CPP async gives error however the function without async works well?
The code below gives the following error, however the function without threads and async works well: main.cpp:38:93: error: no matching function for call to ‘async(std::launch, void (&)(sqlite3*, std::string*, std::ofstream&), sqlite3*&, std::string*, std::ofstream&)’ 38 | ultFromDB = std::async(std::launch::async, ...
std::thread and std::async do not accept references implicitly, you have to wrap them in std::ref: std::async(std::launch::async, writeToDB, DB, &z, std::ref(logFile));
63,341,719
63,342,392
cpp: define class member variable type by type passed to constructor
I would like to define a type of a member variable using the type of a parameter passed to the constructor in C++. Is this possible? I tried in C++14 but I got an compilation error: error: missing template arguments before ‘a’ I think of something like this: template <typename SOMETYPE> class A { public: SOMETYPE...
In C++14 and before, you would have a corresponding make_T factory function: template<class SOMETYPE> A<SOMETYPE> make_A(int foo, SOMETYPE bar) { return A<SOMETYPE>(foo, std::move(bar)); } // Sometimes spelt `A::make` or `A::create`, // but the standard library uses `make_pair`, `make_tuple`, etc. int main() { ...
63,341,732
63,352,229
How to integrate the opencv to webots environment in windows?
I want to use opencv for a project for robot simulation. But I am having trouble with using it inside webots. I can't include it. I have the opencv version 4.30 and I changed my makefile to use the opencv but It doesn't work. Can You guys help me how can I add opencv to webots?
Here are some documentation about how to use external library with Webots controllers: https://cyberbotics.com/doc/guide/using-webots-makefiles?tab-language=ros#adding-an-external-library-ccp You can also find an example of integration of OpenCV (not version 4.30 but you can for sure take inspiration) in a Webots contr...
63,341,744
63,343,769
Segmentation fault in recursive program
I am doing the coin problem, the problem says that, Given a set of coin values coins = {c1, c2,..., ck} and a target sum of money n, our task is to form the sum n using as few coins as possible. suppose you have 9 dollars and you have set of {6,5,1} so, the minimum no. of sum/change for 9 dollars would be ( 6+1+1+1=9...
The code which have been took from: https://www.geeksforgeeks.org/find-minimum-number-of-coins-that-make-a-change/ #include <iostream> using namespace std; int minCoins(int coins[], int m, int amount) { if (amount == 0) return 0; int res = INT_MAX; for (int i = 0; i < m; i++) ...
63,342,081
63,342,390
C++ memory doesn't get freed for seemingly no reason
I am working on a 3D editor using Qt and OpenGL and encountered a severe "memory leak" for seemingly no reason. I have isolated the issue to a single class, which looks like: template <size_t SIZE> class GlVoxelChunk { private: gl::FunctionsX *glFuncs; // unmanaged pointer, points to a global variable Color dat...
When the vectors get cleared or when you delete something you allocated with new etc, the destructors are called and memory is released and available for new uses. But it is not necessarily returned to the OS. Usually the compilers runtime libraries will hold on to the memory and it will be used to satisfy new allocati...
63,342,501
63,343,169
How to create Makefile with includes and libraries?
I am trying to create Makefile for my C++ project. My main.cpp contains this custom includes: #include <mysql_connection.h> #include <cppconn/driver.h> #include <cppconn/exception.h> #include <cppconn/resultset.h> #include <cppconn/statement.h> #include <cppconn/prepared_statement.h> For compilation I use: g++ -stdlib...
You could build the makefile step by step. Start with the build command and make it a makefile target (I removed -stdlib=libc++): app.cgi: main.cpp g++ -o app.cgi -I/usr/local/include -I/usr/local/mysql-connector-c++-8.0.21/include/jdbc -L/usr/local/mysql-connector-c++/lib64 main.cpp -lmysqlcppconn Next you can ex...
63,342,521
63,343,829
Clang on MacOS having problems with its includes
I have built from scratch Clang on MacOS and I am having problems with it. Used following to configure Clang for building: cmake -G "Unix Makefiles" -DCMAKE_INSTALL_PREFIX=/opt/clang-12 -DCMAKE_BUILD_TYPE=Release -DLLVM_TARGETS_TO_BUILD="AArch64;ARM;X86" -DLLVM_ENABLE_PROJECTS="clang;libcxx;libcxxabi;lldb" ../llvm Thi...
Add the following to the shell profile file ~/.bash_profile or ~/.zsh_profile or any other way to set environment variable accessible to the shell you're running it in. export SDKROOT="/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk" Verify the correct path to the SD...
63,342,815
63,342,863
How to cast const pointer to non-const pointer in c++?
I would like to implement constructor with std::initializer_list, I have tried: #include <initializer_list> template <class T> class Vec { public: typedef T *iterator; typedef T *const const_iterator; typedef T value_type; Vec(std::initializer_list<T> init) { create(init); } ... pr...
Initializer lists are light-weighted proxy objects to short-lived sequences, and they are not supposed to be used for writing data into those structures or preserving them for future uses. If you want to implement your own vector class constructor accepting initializer list, you'd have to copy data from provided initia...
63,342,933
63,343,000
Why are the files not being included
This is my first time attempting a big project in C++, and I wanted to create a game in SFML. I divided my program into a bunch of classes that included each other, and that's where I am getting my error. I have three main classes, Game, State, and Entity. The main.cpp includes the Game.h file and starts the game. The ...
You have an include cycle: Game.h includes state.h which includes entity.h which includes game.h. You need to find a way to break the cycle. Typically, you do that with a forward declaration in the header: class State; And then include the .h in the .cpp file.
63,342,971
63,343,307
Should this be a constexpr or not?
Consider this code snippet (godbolt): #include <cstdio> #include <string> #include <string_view> struct Option { std::string_view name; constexpr Option( std::string_view const n ) noexcept : name{n} {} }; template< std::size_t N > class TransformedOption : public Option { public: constexpr TransformedOp...
The constexpr declaration works in all compilers when t is also declared static. constexpr static auto t = make( "abcd_efgh_ijkl_mnop_peqst" ); The reason is the string_view. It's a reference type that refers into the object being initialized. So one way or another, you are initializing a contexpr pointer. Now, a cons...
63,342,980
63,343,225
why does my code get segment fault on SPOJ for Sum of Digits problem?
When I submitted the solution of a dp problem on spoj for this problem I always get a segment fault. But my solution works on other platforms like visual studio and Ideone. I do not know why I am getting this error, Can you help? My code: #include <iostream> #include <cmath> #include <string> #include <string.h> #inclu...
Well, this kind of spoonfeeding is pretty discouraged, but here I go: #include <iostream> #include <string> //number of headers = 3 //no use of using namespace std; int main() { int n = 100; long sum = 0; for (int i = 1; i <= n; i++) { std::string num_as_string = std::to_string(i); for(co...
63,343,126
63,417,621
CGAL::Voronoi_diagram_2 rounding to integers incorrectly
I am attempting to create a Voronoi diagram from line segments with the following code. #include <iostream> #include <CGAL/Exact_predicates_inexact_constructions_kernel.h> #include <CGAL/Segment_Delaunay_graph_Linf_filtered_traits_2.h> #include <CGAL/Segment_Delaunay_graph_Linf_2.h> #include <CGAL/Voronoi_diagram_2.h> ...
To follow up on Marc's comment, I needed to change the definitions at the top. The result that works is #include <iostream> #include <CGAL/Simple_cartesian.h> #include <CGAL/Segment_Delaunay_graph_filtered_traits_2.h> #include <CGAL/Segment_Delaunay_graph_2.h> #include <CGAL/Voronoi_diagram_2.h> #include <CGAL/Segment_...
63,343,513
63,343,577
What is relative order and what does stable_partition do?
So I got this code: #include <vector> #include <algorithm> bool isEven(int x) { return x % 2 == 0; } int main() { std::vector<int> vec = {1,7,3,10,9,6}; std::stable_partition(vec.begin(), vec.end(), isEven); } Now I didn't understand what was the concrete difference between stable_partition and partitio...
The relative order of the elements is simply the order that the elements within a particular partition have with respect to each other. For example, after partitioning {1,7,3,10,9,6} we get: {6,10} {1,3,7,9} // one of the possible results // ^^^^^^ ^^^^^^^^^ elements within partition can be in any order s...
63,343,581
63,343,683
How to render only a part of EBO in OpenGL?
I have VAO with bound VBO and EBO. Previously I've just been rendering it with glDrawElements( GL_TRIANGLES, EBO_size, GL_UNSIGNED_INT, 0 ). But now I wanna draw it in parts, changing some uniforms in-between. Aka if I have 36 indices in EBO; I might wanna draw 18, change the uniform, and draw the remaining 18. I tried...
glDrawElements void* indices parameter is actually a starting offset in bytes. And as you know, GLsizei count is the amount of elements to draw (not in bytes!) For example, this would draw an EBO of 36 indices in two parts: glDrawElements( GL_TRIANGLES, 18, GL_UNSIGNED_INT, (void*)(0) ) glDrawElements( GL_TRIANGLES, 18...
63,343,831
63,344,205
How to detect index of a specific number in a std::integer_sequence?
I basically drafted compile time prime checking using this question as a reference: Compile time prime checking I have a IsPrime<3>::value available. I want to design a find meta function that basically identifies if there is a prime in my integer sequence at compile time, if there is then returns the index else return...
This can be done with a recursive template. Recursion terminates early when a prime is found. // Base failure case: our list is empty (or the specialization below would match) template <int, int...> struct find_prime_impl { static constexpr int value = -1; }; // Specialization for at least one item remaining. If...
63,343,914
63,343,938
I have a question about dynamic allocation of memory in c++
I'm new to c++ and I can't understand something in dynamic allocation. why does the following program build but gives an error and stops? #include <iostream> using namespace std; int main() { int amount; int *p = new int[amount]; cout << "enter the size of array" << endl; cin >> amount; for(...
You are trying to use amount before you have assigned any value to it. You need to read the user's input for amount first, THEN allocate using it. Not the other way around. #include <iostream> using namespace std; int main() { int amount; cout << "enter the size of array" << endl; cin >> amount; int ...
63,344,332
63,344,423
Why can't I compare a constant instance of a class with a non-constant instance of the same class?
I have the following function: #include <cstdint> using int_32 = int32_t; bool func(const Coord<int_32> c) { for (Coord<int_32> i : boxes) if (c == i) return 0; return 1; } Coord<int_32> is a struct with two members of type int (int32_t). Here is its overloaded == operator: bool operator =...
In your comparison: if (c == i) the variable c is const. However, your operator== is not const-qualified, so the left hand side of == is required to be non-const. The correct fix for this is to mark operator== as const if it's a member function: bool operator == (const Coord<T> &p) const { ...
63,344,376
63,351,956
floats getting rounded to 1 decimal by C++
I'm writting a C++ program that takes user input and put it inside a file. In this case, it takes in a number (eg. 299.99), but C++ rounds it to 300 (used to be doubles) when using doubles and floats 299.9... My code: void Bank::deposit(){ std::cout << "You currently have " << getBalance() << " in your account.\nHow mu...
This link may help [link][1] float iBalance = getBalance(); std::cout<< std::setprecision(2)<<iBalance<< endl; [1]: https://stackoverflow.com/questions/5907031/printing-the-correct-number-of-decimal-points-with-cout#:~:text=You%20have%20to%20set%20the%20'float%20mode'%20to%20fixed.&text=To%20set%20fixed%202%20digit...
63,344,481
63,349,672
Is it possible to declare template of template?
I have objects of type 'value' from OCaml in C++ (they are provided by some integration channel, but it is offtopic). This object contains OCaml data of some type (primitive: int, long... or structural). It can be converted to a C++ object, from OCaml int to C++ int, etc by some provided by "caml/mlvalues.h" functions ...
You can forward the operation from a function template to a class template and specialise the latter, leaving the former fully generic. // base case: conversion disallowed template <typename K> struct convert_to { static K convert_to(value) = delete; }; // convert to specific types te...
63,344,551
63,345,017
how to indicate that a namespace is only for library use?
I'm working in a project where I happened to define a global std::map variable which will store run-time fabricated values. I want to specify that such variable and the two functions (one that updates and other which searches) for that map are only for library use. What I'm doing until now is to declare the namespace a...
What I'm doing until now is to declare the namespace as namespace stored__ This is a bad idea because that name is reserved to the language implementation. If you only need to access the names in single translation unit, then you can declare them in an anonymous namespace which will prevent the names from being refer...
63,344,585
63,382,898
Using boost mp11 to switch on runtime value efficiently(breaking when processing function is done)
I have the following code where I implement dispatching on runtime value to interpret the data in certain way(in this toy example data can be either uint8_t or short). Code seems to work, but I am wondering if I can somehow microoptimize the code so that when I have a hit(processing function matches) processing is stop...
The runtime performance of this heavily depends on the size of your tuple. You can make your own for_each_tuple implementation that does an early out when your function gets executed: template<typename FuncTuple, typename Selector> void tuple_for_each(FuncTuple const& funcTuple, Selector selector) { std::apply([se...
63,344,936
63,368,165
How to retrieve IP and port from a `sockaddr_storage` instance?
How can I retrieve IP and port from a sockaddr_storage instance with getnameinfo() (ref)? When I used inet_ntop, it worked like normal, but when I replaced it with the getnameinfo function, Windows returned an error: Code 10047: An address incompatible with the requested protocol was used. #ifdef USE_IPV6 int fd = so...
I took a look at your issue and was able to reproduce the error you were having. Reproducible example: #define WIN32_LEAN_AND_MEAN #define _WINSOCK_DEPRECATED_NO_WARNINGS #include <cstdint> #include <cstdlib> #include <iostream> #include <windows.h> #include <WinSock2.h> #include <WS2tcpip.h> int main(int, char **) {...
63,345,093
63,345,122
Unions in C++ (Please explain it)
#include <iostream> #define print(x) std::cout << x #define println(x) std::cout << x << std::endl struct Vector2 { float x, y; }; struct Vector4 { union { struct { float x, y, z, w; }; struct { Vector2 a, b; }; }; }; void PrintVector2(const Vector...
The behaviour of the code is undefined. This is little more than an elaborated union type-pun. This is not allowed by the C++ standard, as the C++ union has the concept of an active member. Once the active member is set, you cannot read another member in a defined manner. (You can of course change the active member by ...
63,345,414
63,350,200
Bitwise operations for comparing numbers?
I've spent too many brain cycles on this over the last day. I'm trying to come up with a set of bitwise operations that may re-implement the following condition: uint8_t a, b; uint8_t c, d; uint8_t e, f; ... bool result = (a == 0xff || a == b) && (c == 0xff || c == d) && (e == 0xff || e == f); Code I'm looking at has...
So, if you really want to do bit-twiddling to make this "fast" (which you really should only do after profiling your code to make sure this is a bottleneck), what you want to do is vectorize this by packing all the values together into a wider word so you can do all the comparisons at once (one instruction), and then e...
63,345,737
63,345,769
Circular dependency in a simple, 3-file project
This issue have been coming up frequently in a previous project and I've been avoiding it by keeping the definitions of methods inside the same header file as the declarations of said methods, despite knowing how bad of a practice that is, but now I'm trying to setup a project template and I want to do this correctly, ...
in Window.h use extern sf::RenderWindow w; extern sf::Event e; extern window_methods mw; in Window.cpp use sf::RenderWindow w(sf::VideoMode(690, 500), "Hello World"); sf::Event e; window_methods mw; Defining these three variables in the header file makes them exist in every translation unit (compiled .cpp leading to ...
63,345,892
63,346,693
How to keep good aspect ratio in parallel view
I'm currently working on a STL file viewer which provides two types of views. A perspective view (it's working perfectly): and a parallel view (light calculation having trouble on this one but it's not the subject): As you can see the parallel view is deformed. Here is how I calculate the view matrix: float distance ...
Delete one of the screen size bits? Right now, if your window is 3/4 as tall as it is wide, then you're making the height 3/4 as tall (so far so good) but you're also making the width 4/3 as wide. You need to do one or the other, but not both. Most computer games seem to keep the height the same - so the vertical view ...
63,346,074
63,354,401
How can I send a C++ String to node.js?
Im very new to making C++ addons for node.js So my Question is: Is there a way for an addon-function to return a String? And if so, How? Further Explaining: Lets say i have a string called std::string testString in my C++ Source File. When given following JS code: const myAddon = require('path'); console.log(myAddon.my...
Here is an adapted version of the hello world example in the documentation: #include <node.h> #include <string> namespace demo { using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; using v8::Object; using v8::String; using v8::Value; std::string testString; // value is set elsewhere. void MyFunc(con...
63,346,276
63,346,302
Merge sort program doesn't do anything to the array that I want to sort
I'm new to C++ and I'm trying to implement a merge sort but when I print my array in my main method it remains unmodified and I'm unsure of why that's the case. I tried printing the contents of the arrays that I split but it gave me values that I was unsure of where it was coming from. #include <iostream> #include <vec...
You are creating a copy of the vector when you pass it to merge_sort. Any changes made to arr in the function will not be visible in main. Instead, you need to pass the vector by reference if you want the function to modify the argument: void merge_sort(vector<int> &arr) { // ^ by reference S...
63,346,772
63,346,834
How can the synthesized default constructor initialize already initialized class members?
I am learning about classes, and chapter 7.1.4 of the book C++ Primer says the following: The compiler-generated constructor is known as the synthesized default constructor. For most classes, this synthesized constructor initializes each data member of the class as follows: If there is an in-class initializer (§ 2.6....
In class initializers don't actually initialize anything. All they are are syntactic sugar for use this initializer if none is provided. So, with struct foo { int a = 42; int b; }; The compiler is going to generate a constructor like foo() : a(42)/*, b()*/ {} Since a has an "initializer" and b does not. no...
63,347,138
63,347,270
Is this auto template deduction guide is correct?
I am learning about the auto template deduction guid: https://en.cppreference.com/w/cpp/language/class_template_argument_deduction. Therefore I wanted to try this out. I have the following nested class structure in which MyClass is a templated class with non template parameter, and the inner struct MyStruct simply have...
You can write a deduction guide that considers the brace-initializer-list argument as an array like this: template<size_t N> MyClass(int const (&)[N]) -> MyClass<N>; and then you can construct an object this way: MyClass myObj{ { 1, 2} }; Here's a demo.
63,347,301
63,349,695
Why can a naive abs implementation not be optimized well in C++?
I was looking at how a naive implementation of abs(float) would compile and was quite surprised by the result: float abs(float x) { return x < 0 ? -x : x; } With clang 10.1 at -O3, this results in: .LCPI0_0: .long 2147483648 # float -0 .long 2147483648 # float -0 ...
The IEEE floating point space contains a number of special values, such as both positive and negative 0, positive and negative infinities, and two families of "Not a Number" (NaN). All of these values have well-defined semantics wrt. the < operator, and so the compiler must generate code that deals correctly with all ...
63,347,311
63,348,163
Generate a new integer_sequence by removing duplicates
I implemented a compile time check to check if something is sorted using the code given below: template<typename IntegerSequence> struct is_sorted { static constexpr bool value = true; }; template<typename Integer, Integer Head, Integer Next, Integer... Tail> struct is_sorted<std::integer_sequence<Integer, Head, N...
Also is it possible to remove duplicates while we are performing the sort check, in this case I am fine if we stop removing duplicates as soon as templates detect that sequence is not sorted. Yes, it's possible. Maybe can be done a little simpler, but... using and abusing template specialization... Given an helper cl...
63,347,664
63,347,789
How to obtain a constant expression when std::is_constant_evaluated?
Let's start with the example (godbolt): constexpr int len(int v) { if (std::is_constant_evaluated()) { // static_assert(v > 0); // ERR: 'v' is not a constant expression return v; } else { return 0; } } using A = std::array<int, len(3)>; The problem is, that the static_assert won't ...
Apparently, v isn't realized to be constexpr when std::is_constant_evaluated returns true. But clearly, by the use of len, it actually is. No, it's actually not. Function parameters are not constant expressions. It doesn't matter if you're in the middle of constant evaluation or not. You cannot use v as a constant ex...
63,347,851
63,347,870
Using std::optional<A> as a class member of class A
Why isn't it possible to define a class member of type std::optional<A> in class A? Example: #include <optional> class A { public: A(std::optional<A> optional = {}) : optional_(optional) { } ~A() = default; private: std::optional<A> optional_; }; Compiler error: error: incomplete type 'A' used in type tra...
optional<T> requires that T is a complete type (and therefore has a known size). Until the class A's definition is finished, A is an incomplete type. Hence the error. There is no way to have any type T hold a member variable of type optional<T>, since optional<T> itself has a member variable of type T. You can heap-all...
63,348,314
63,348,703
Understanding Boost.Hana Quick start
I'm going through Boost.Hana's User Manual to learn more about template meta programming and functional programming in C++. As regards the Real world example, I still miss a few bits, all concentrated in the definition of the following function: template<typename Any, typename Default, typename Case, typename ...Rest> ...
I'll try to answer the question about that using line: case_ is a variable of type hana::pair created by hana::make_pair(hana::type_c<T>, f) (the first parameter is a wrapper around a type) hana::first(case_) returns the first item of the pair (the hana::type_c wrapper around the type) +hana::first(case_) uses the una...
63,348,401
63,348,694
Diameter of a tree graph
I'm asking myself what's wrong with my code to find the diameter of a tree: (By diameter of a tree, I mean the greatest distance between two nodes in that tree graph) #include <iostream> #include <vector> #include <algorithm> using namespace std; #define MAXN 1000005 int n,a,b; int dist[MAXN]; vector<int> adj[MAXN]; ve...
You measure the distance between two nodes in a tree by A and B. distanceBetwwen_A_and_B = Distance A -> CommonAncestor(A, B) + Distance B -> CommonAncestor(A, B); So for a given Ancestor Node G it has a maximum radius of: Diameter(G) = Distance_To_Furthest_Child(G->left) + Dist...
63,348,450
63,348,578
Is it possible to initialize variable with same name but different numbers at the end?
In a situation I have to define some variables where I have control on parts of the variable names (like var below). float var1, var2, var3....; But I do not have any control on the numbers that they will take. (This is because these var* I am producing from some other code where everytime I compile, these numbers at ...
If you do know the bounds and you do not mind leaving unused variables, you can play with the preprocessor to generate them. For instance: #include <boost/preprocessor/repetition/repeat.hpp> #define ONE_FLOAT(z, n, x) float var##n; BOOST_PP_REPEAT(100, ONE_FLOAT, x) Note 1: implementing BOOST_PP_REPEAT by hand is ou...
63,348,729
63,348,934
How to implement recursive directories and files listing using std::filesystem?
I want to implement recursive directories and files listing on my own. I do not want to use std::filesystem::recursive_directory_iterator I tried this code: void TraverseDirectory(const std::string& rootDirectory) { //Go thru the root directory for(const auto& entry : std::filesystem::directory_iterator(rootDi...
std::filesystem::path::filename Returns the generic-format filename component of the path. Equivalent to relative_path().empty() ? path() : *--end(). This means, that for actual path /foo/bar/42.txt you get 42.txt return. Now, here in if(entry.is_directory()) { std::cout << "Dir: " << filenameStr << '\n'; Trave...
63,348,732
63,348,894
Does this situation require a delete or making a new variable?
I'm creating some code to "parse" an IP address. Basically, I am working with some legacy code that only accepts IP addresses in the form "AAA.BBB.CCC.DDD" and would like to write in something like "10.2.4.3" and have the code work without needing to type in 010.002.004.003. The IP address is held in a char pointer and...
No, you don't need a delete if you don't do any new. But your program suffers from a different problem: char* parser(char* ip) { char out[16]; //16 is the length of the final IP address with the dots and \0 char at the end //find output char array return out } This returns a dangling pointer. It won't b...
63,349,707
63,349,998
SDL2 Pointers c and c++
How it's possible that we are storing some function in pointer's like win = SDL_CreateWindow("Hello World", posX, posY, width, height, 0); ? If it's not a function so what is it cuz it looks like a function. Second what type of pointer's are these is it pointer to member function ? I mean that SDL_Window *win; SD...
Actually win is not pointer to a function but it is a pointer to structure type SDL_Window. Statement win = SDL_CreateWindow("Hello World", posX, posY, width, height, 0) means that you have calling function SDL_CreateWindow with arguments ("Hello World", posX, posY, width, height, 0) this function as the result of ar...
63,349,893
63,360,803
C++ convert char array of digits and commas to list of integers?
I have a socket setup in C++ that receives a stream of chars in a buffer array char buffer[MAXSIZE]; the characters in buffer can only be digits 0,1,...,9 or a comma ,. I would like to convert an example buffer content such as buffer = {'1','2' , ',' , '3' , ',' , '5','6' , ...}; where the final char position is stor...
If you can use the range-v3 library, you could do this: namespace rs = ranges; namespace rv = ranges::views; auto integers = buffer | rv::split(',') | rv::transform([](auto&& r) { return std::stoi(r | rs::to<std::string>); }) ...
63,349,901
63,350,899
expected primary-expression before ‘struct’
Both GCC 8.3.0 and clang 9.0.1 fail to compile this short example code: #include <cstdlib> template <typename T> struct mystruct { T data; }; int main (const int argc, const char * const * const argv) { int ret = EXIT_SUCCESS; auto elem1 = struct mystruct<bool> { }; // Doesn't compile. auto elem2 = mystruct<...
The type{…} syntax, like type(…), requires a single, non-elaborated type specifier. This can be fairly complicated: auto x=typename A::template B<int>(); // OK It cannot, however, include operators or prefix specifiers: // All bad: auto a=int*{}; auto b=const int(); auto c=struct X{}; // a class definition? auto d=...
63,349,944
63,350,037
STRONGN Strong Number (Special Numbers Series #2) word problem on Code Wars
Strong number is the number that the sum of the factorial of its digits is equal to number itself. For example: 145, since 1! + 4! + 5! = 1 + 24 + 120 = 145 Here is my code, It passes most of the test except one test #include <string> using namespace std; string strong_num (int number ) { int sum = 0; while(nu...
I'm surprised you're passing any test cases at all. For one thing, you are destroying number before you compare it to sum, and for another your logic is flawed. Try this: int factorial (int x) { int result = 1; while (x > 1) { result *= x; x--; } return result; } string strong_num ...