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
61,835,052
61,835,391
Initialize new[] using copy constructor
I believe this is a simple question with probably a not simple answer. Here is the code: template<typename T> T* copy(T* original, int size) { T* result = new T[size]; // At this point the default constructor of all new T objects have been called. for(int i = 0; i < size; ++i) { // This will call t...
You will have to allocate memory by any other means, but keep in mind that size * sizeof(T) can overflow. std::allocator takes care of this. Use std::uninitialized_copy/std::uninitialized_copy_n to perform the copy: template<typename T> T* copy(T* original, int size) { std::allocator<T> alloc; T* result = allo...
61,835,153
61,835,478
How is the string printing characters of the previous testcase even after declaring it again in the while loop of testcase?
#include <bits/stdc++.h> #include <stdio.h> using namespace std; void Fun(char *s) { for(int i=0;s[i]!='\0';i++){ while(s[i]!='\0' && s[i]!='.' ){ cout<<s[i]; i++; } cout<<" "; } } int main() { int t; cin >> t; while (t--) { char s[10000]; ...
The for loop is going to break when it receives a null character. But the null character it is supposed to receive is handled in the while loop. the while loop checks, gets a null character, breaks the loop, then a ' ' is printed, i is incremented and the for loop never gets a chance to get the null character. But eve...
61,835,479
61,835,521
When I input a word, the program is not understanding the word even though the if function puts up the exact same word that was inputted
#include <iostream> #include <iomanip> #include <cmath> #include <fstream> #include <cstdlib> #include <algorithm> using namespace std; int main() { double word; cout<<"write your word"<<endl; cin >> word; if (word == 'hello') cout << "hello world" << endl; } When I input 'hello', it doesn't...
double is for storing floating-point numbers. You should use std::string to store strings. Also '' is for representing characters. You should use "" to represent strings. #include <iostream> #include <iomanip> #include <cmath> #include <fstream> #include <cstdlib> #include <algorithm> #include <string> // add this usi...
61,835,663
61,835,924
Removing starting characters from string using std::string::erase
I am trying to truncate beginning zeros from a string, so I used sequence erase function string& erase (size_t pos = 0, size_t len = npos); This is my implementaion: string str="000010557"; for(char c:str){ cout<<c<<" "<<str<<" "<<"\n";// for debug purpose if(c=='0') ...
Your for loop is incrementing the position from which c is extracted, even if you erase a leading zero. Thus, after two runs of the loop, you have erased the first and third of the leading zeros, then the c value will be the first 1. Here's an attempt at following what happens in your code: Start of first loop: "00...
61,835,889
61,837,909
Undefined reference to `TESTCLASS::TESTCLASS()'
Although I read a few google-results for that error I can't find my problem for this error, not even while trying to reduce everything to its very basic content. That's my testclass.h: class TESTCLASS { public: TESTCLASS(); }; int x; // I added this for testing if the file is included from my main code file x=10; /...
When using subdirectories with the Arduino IDE the subdirectory needs to be named as utility. That's actually it! Having this structure for example (in ../Arduino/libraries/): ./testclass ./testclass/testclass.h ./testclass/testclass.cpp ./testclass/sub ./testclass/sub/sub.h ./testclass/sub/sub.cpp testclass.h: #ifnd...
61,836,679
61,840,286
How to set the size of the window corresponding to the size of the it's background image?
Im am setting some image as main window's background (successfully) and trying to force to it size of the image but the result is some weird form. My code : main.cpp #include "mainwindow.h" #include <QApplication> int main(int argc, char *argv[]){ QApplication a(argc, argv); MainWindow w; ...
it is not clear what you want to do, the code is written meaningless bkgnd = bkgnd.scaled(this->size() ); ..... this->setMaximumSize (bkgnd.height (),bkgnd.width ()); this->setMinimumSize (bkgnd.height (),bkgnd.width ()); here is a simple example , add enum Qt::IgnoreAspectRatio #include "mainwindow.h" #include "ui_ma...
61,836,703
61,838,620
How should I correctly move packaged_task to lambda?
I have been trying to capture packaged_task into lambda, but I've failed. I understand move-semantics at all, also read some modern literature and I was thinking I didn't miss anything. Also I have read Josuttis's move semantics book, and ISO topic about generalized lambda captures and similar case at ISO C++ 14 Langu...
Your lambda is fine. If you move lambda definition to its own line, you will find out that there are no errors in it. Your problem lies in fact that std::function constructor requires its argument to be CopyConstructible, and as your lambda contains a move-only object, it is not CopyConstructible. You can try to implem...
61,836,841
61,890,095
C++: Checking if dynamic de-allocation has worked correctly
I am currently following a book from Springer called "Guide to scientific computing in C++", and one of its exercises regarding pointers says as follows: "Write code that allocates memory dynamically to two vectors of doubles of length 3, assigns values to each of the entries, and then de-allocates the memory. Extend ...
Your code does exactly what it is supposed to, run a long time without crashing your computer due to out_of_memory. The book might be a bit dated as it assumes you can not allocate more than 72.000.000.000 bytes before crashing. You can test it be removing the deletes hence leaking the memory.
61,836,863
61,836,982
Problem with file by using fstream library and print on screen?
I am trying to print the data located in the weapon.obj file, but it's not working. Compiler Error: error: no matching function for call to 'getline(std::ifstream&)'| Code: #include <iostream> #include <fstream> using namespace std; int main() { ofstream render_weapon_OBJ ("weapon.obj"); render_weapon_OBJ ...
You must specify where to read the data and use that for printing. #include <iostream> #include <fstream> #include <string> // add this to use std::string using namespace std; int main() { ofstream render_weapon_OBJ ("weapon.obj"); render_weapon_OBJ << ("Weapon Names"); render_weapon_OBJ.close(); ifstr...
61,836,999
61,837,655
How to represent 6 integer key better than as indices to a 6-dimensional array?
In my program, a state can be uniquely identified by six integers. Each integer, i satisfies 0 <= i <= 10 and each state has an associated value. I am currently using a 6-dimensional array to keep track of each states value. I am storing the state values in an array like so state[11][11][11][11][11][11][11], where each...
If you don't need to have a value in every state you can get away with using a map Concept code, totally untested. constexpr int dimension = 6; using KeyType = std::array<char, dimension>; int32_t Key(const & KeyType keys) { int32_t res = 0; for (auto key : keys) { res <<= 4; res += key; } return res; }...
61,837,254
61,846,145
Pointer to a class method call
I am trying to define a class named RationalNumber. In the constructor I want to simplify the fraction represented by the RationalNumber using a callback function to another function (named simplification), but I receive some errors and I can't figure out what I am missing. The first error is cannot convert from 'void ...
cannot convert from 'void (__cdecl *)(RationalNumber &)' to 'RationalNumber::pointer_to_f' on the line pointer_to_f p = &simplification; Let's see what we have here. This line initializes a variable (p) of type RationalNumber::pointer_to_f, which corresponds with what the attempted conversion is to. On the right-ha...
61,837,552
61,838,023
Function falls completely off the candidate list if it takes a pointer to the class
Why can't I have a non-member function with the same name as a member function, if it also happens to take a pointer to the class? This doesn't compile: struct FooConfig{ int value; }; struct BarConfig{ int value; }; class Api { void configure(const FooConfig& cfg); void configure(const BarConfig& cfg); }; //...
Before overload resolution selects the best viable function, a set of candidate functions is formed, specifically matching the name of the callee. For that, the name lookup procedure is used. Expression configure(this, cfg.value) is an unqualified call inside a class member function scope, and for that, the name lookup...
61,837,645
61,837,749
Is thread safe when I call readonly static members of struce in C++
I have class that I'd like to call it like as enum: struct mac_constant { private: static constexpr int SL_MAX_val = 5; static constexpr std::array<double,SL_MAX_val> r_SL{ 19.8, 40.16, 62.00, 83.84, 105.68 }; static constexpr std::array<size_t,SL_MAX_val> n_TS_SL{ 160, 192, 256, 320, 384 }; public: static c...
The data in the class is constructed in a thread safe manner (magic_statics - C++11), and is static and none of the data it is referring to will be changed during execution of the code. So in this case, the answer is yes. But if the data was calculated, it may start to have thread races, so I would not take this answ...
61,837,647
61,838,024
Direct2D erasing the background with WM_ERASEBKGND?
It seems like I've learn it hard way, if we use Direct2D for painting then one must not use WM_ERASEBKGND to handle background erasing, but I may be wrong on this so here is the problem: I register my drawing window with null brush to let me manually handle background erasure: WNDCLASSEXW wcex; wcex.hbrBackground = nu...
The classic window rendering with GDI is revolving around incremental updates to the single image buffer. Typically redrawing a (partially transparent) window would require securing write access to the image buffer, clipping update region, requesting parent window to draw its background, making this window draw its bac...
61,837,811
61,846,263
How do you link a C++ library from the command line
I am making C++ library that has multiple headers (all headers having a .h, .cpp, and .o file), how do I make the library linkable so that the user can compile it like: g++ main.cpp -o binaries -l libraryName?
how do I make the library linkable Like so: ar ruv libraryName.a foo.o bar.o baz.o This is best achieved by writing a Makefile, which will automate the build process for you. Something like this: all: libraryName.a clean: rm -f *.o # important: use TAB, not spaces for indentation here. SRCS = foo.cpp bar.c...
61,837,942
61,838,621
How to count the number of a char* in a char** variable?
How can you determine the number of elements in a dynamically allocated char**? For instance: #include <iostream> #include <vector> #include "cstring" using namespace std; // here we create a 6 element char** char **func() { std::vector<std::string> vec = {"A", "Dynamically", "Allocated", "List", "of", "Strings"}...
How can you determine the number of elements in a dynamically allocated char**? There are no char* objects "in" a char** variable. char** points to one char* object (or none if null or dangling). Whether that char* is within an array, and how big that array is, is something that cannot be determined from the char** v...
61,838,230
61,838,386
How to check if a template is a class member of another template
I made a function that sorts my vector by member (e.g. students by age or name) so I made a template function template<class ElemType, class ElemMember> void sort(vector<ElemType>& vec, ElemMember member, bool ascending = true) { for(int j = 0; j < vec.size()- 1; ++j) for (int i = 0; i < vec.size() - j - 1;...
Using a pointer to a data member of ElemType, as the parameter of sort, should suffice: template <typename ElemType, typename MemberType> void sort(std::vector<ElemType>& vec, MemberType ElemType::*member, bool ascending = true) // ~~~~~~~~~~~~~~~~~~~~~^ DEMO
61,838,347
61,838,642
Antlr4 C++ visit ambiguous branch
So let's say I have a rule like this: rule : '(' rule ')' | '!' rule '!'; Now in my runtime I have this method: antlrcpp::Any runtimeVisitor::visitRule(tinycParser::RuleContext *ctx) { ... } How can I check whether I am in the fist or in the second case? Might something like this works? if(ctx->rule(0)) visitRu...
You can label your alternatives like this: rule : '(' rule ')' #ParenthesizedRule | '!' rule '!' #ExclamationMarkRule | ... ; Then you can define specific visitor methods for each alternative (i.e. visitParenthesizedRule, visitExclamationMarkRule etc.) instead of visitRule. If you don't want to add any...
61,838,405
61,838,616
C++ Initializing a template array in a contructor initializer list
I have a component class that doesn't have a default constructor and needs an object passed to it instead. I want to have a template class that builds a stack space, arbitrarily sized array of this component. Because it doesn't and really shouldn't have a default constructor, I'm running into issues making it work. Ano...
Use std::array and then you can make a constexpr function that initializes and returns the array: namespace details { template <class T, std::size_t Size, class... Args, std::size_t... I> constexpr auto make_arr_emplace_impl(std::index_sequence<I...>, Args&&... args) -> std::array<T, Size> { return std::array<T...
61,838,736
61,844,351
what is the following oop structure here?
In the code below where is the variable, and where is the variable type? We have here properties of registers being changed. If its an object oriented then we need an object name where we change its properties. In here I don't see where is the type where is the variable name and how exactly we change its inner properti...
This has nothing to do with OOP, it is just a structure member assignment. RCC and GPIOC are defined in stm32f0xx.h: #define RCC ((RCC_TypeDef *) RCC_BASE) and #define GPIOC ((GPIO_TypeDef *) GPIOC_BASE) Where RCC_BASE and GPIOC_BASE are are defined in the same header as abaolute addres...
61,838,812
61,839,345
Different float values in array impact performance by 10x - why?
please check out my code and the quesion below - thanks Code: #include <iostream> #include <chrono> using namespace std; int bufferWriteIndex = 0; float curSample = 0; float damping[5] = { 1, 1, 1, 1, 1 }; float modeDampingTermsExp[5] = { 0.447604, 0.0497871, 0.00247875, 0.00012341, 1.37263e-05 }; float modeDamping...
This is because you are hitting denormal numbers (also see this question). You can get rid of denormals like so: #include <cmath> // [...] for (int i = 0; i < 5; i++) { damping[i] = damping[i] * modeDampingTermsExp2[i]; if (std::fpclassify(damping[i]) == FP_SUBNORMAL) { damping[i] = 0; // Treat denorm...
61,838,857
61,839,014
std::copy causing Run-Time Check Failure #2
The code where the error occurs: typedef unsigned char BYTE; typedef std::vector<BYTE> BUFFER; RequestInfo JsonRequestPacketDeserializer::createRequestInfo(BUFFER& buffer) { RequestType type = static_cast<RequestType>(buffer[0]); uint32_t dataLen = 0; std::copy(&buffer[1], &buffer[4], &dataLen); if ...
buffer[i] is copied into *(&dataLen + i - 1) for i = 1, 2, 3, 4. That causes undefined behavior. You want uint32_t dataLen = buffer[1]; for (std::size_t i = 2; i != 5; ++i) { dataLen = (dataLen << 8) + buffer[i]; } This loop copies 4 single bytes into one variable with 4 byte size where buffer[1] is the most sign...
61,838,971
61,841,468
garbage value after calling a member function of a class
I was trying to call a member of class a from class b but was unsuccessful it works but always gives garbage value for the vector in class a and yes the exception is thrown on the third time while the read loop is only supposed to run only 2 times. b.h #pragma once #include <iostream> #include <fstream> #include <vect...
Non-POD types cannot be directly written or read. For example, the std::string class. The string class has some member data, but commonly, the string content is elsewhere (like in dynamic memory). I would suggest define the << and >> operator for your class to serialize and un-serialize. The Boost::serialization librar...
61,839,104
61,840,423
Why request work in postman but does not work in curl (C++ libcurl)
I'm trying download comments from YouTube through private api but for some reason request to api does not work in curl. It should return JSON with information about comments under video but to me it return nothing. Literally nothing. In postman with same parameters and headers all work perfectly. I think that i'm not c...
In the end it's just been UB. if (currRequestType == KTools::Enums::Curl::RequestType::Post) { curl_easy_setopt(gCurlHandle, CURLOPT_POSTFIELDS, currPostParam.toStdString().c_str()); curl_easy_setopt(gCurlHandle, CURLOPT_POSTFIELDSIZE, currPostParam.size()); } Curl store not string but reference to string. But...
61,839,333
61,841,792
C++ dangling reference to Eigen::Matrix created in function
Would the following example create a dangling reference? (Since the vector<int> is local in the function and the MatrixXi is using a reference to this data). Also considering the Foo constructor takes a reference to the MatrixXi. #include <Eigen/Dense> #include <Eigen/Core> using Eigen::MatrixXi; static Eigen::MatrixX...
Ok, as the status of this thread became a bit confusing, I'll add another answer and detail what I already wrote in the comments. It is ok to return a MatrixXi inside the function CreateMatrix and return it. You perform the creation of the matrix via copying from an Eigen::Map, which is also ok. In your simple example...
61,839,358
61,847,454
Why does zmq pack several messages to one TCP frame?
I send messages using ZMQ_PUSH socket with ZMQ_DONTWAIT flag. Each message separated by 300ms (so I seriously doubt, that my thread scheduling is so off). However from time to time several (up to 7 so far) messages are packed to the same TCP frame yet I don't see any retransmissions or reconnections in tcpdump. Why is ...
Q : "And how can I determine when my message would be sent?" You have zero-chance to know when a message, dispatched to be sent, would finally get down to the wire-level. This is a property of the concept, not a bug. It was explicitly explained in the documentation, since the API v2.0+ ( and will most probably remain...
61,839,502
61,852,626
Can we access the icons used by the BIF_NEWDIALOGSTYLE browse window?
On one of my property sheets I have two CMFCEditBrowseCtrl objects. One of them is for selecting a local folder on the computer. So I have used the following style in OnInitDialog: m_BrowseLocalBackupFolder.EnableFolderBrowseButton(nullptr, BIF_NEWDIALOGSTYLE); The popup window when browsing for the folder looks like ...
You need to change the theme of the tree view using SetWindowTheme API: In order to set it to "Explorer" like view, use this code: SetWindowTheme(hwndTreeView, L"Explorer", NULL);
61,839,629
61,840,706
Pass template object
I have a template class: template <typename T> struct FilesName{ const T filename_A; const T filename_B; FilesName(const T& _filename_A, const T& _filename_B): filename_A(_filename_A), filename_B(_filename_B) { } }; The type T could be std::string, or std::wstring, or otrers string container. I'd like pas...
I also discover following code are working fine: struct Files{ std::ofstream file_A; std::ofstream file_B; template <typename T> Files(const FilesName<T>& _FilesName) : file_A(_FilesName<T>.filename_A), file_B(_FilesName<T>.filename_B) { } };
61,839,889
61,840,050
Referencing a specific index in a vector
I'm trying to reference a certain index within a vector but whenever I add new items to the vector the pointer isn't pointing towards the original value. The example I have is this: std::vector<int> a; a.push_back(1); int* a_1 = &a[0]; a.push_back(2); When I do: int* a_1 = &a[0]; It's referencing the first value whic...
Vector changes the place in memory where items are stored when number of items exceeds current capacity. If you add new item past the capacity, all items are copied to new place. So you are referencing an old place where the item no longer sits. To constantly reference same index, store the index. In this example store...
61,840,370
61,843,641
How to split QTextEdit into pages?
I'm using QTextEdit from C++ Qt5. I want to properly split and show rich text in numerated pages similarly to how it's done in Microsoft Word. I've tried document->setPageSize, however that does not work for me - text is still shown in one continuous page.
AFAIK QTextEdit doesn't support the word-processor-style concept of "pages". Rather, QTextEdit is designed around editing and viewing a continuous document, whose only delineation is at the level of "blocks" (i.e. paragraphs). Note this telling comment in the QTextDocument::print(QPagedPaintDevice *) const method-docu...
61,840,403
61,840,915
Getting constant too big error while using boost library (cpp_int)
As I am trying to work with big integers I installed boost library but when I try to debug I get constant too big error while I think cpp_int can handle it right? could you please take look at my code and error? here is the error: Error C2177 constant too big HW7 C:\Users\hmffa\source\repos\HW7\HW7.cpp 34 Error ...
Change cpp_int p= 30903154482632612361920641803533; to cpp_int p{"30903154482632612361920641803533"};
61,840,685
61,840,787
How to prevent memory leak in generalized linked list?
I've implemented my own linked list data structure. Data is stored inside Node struct. Code is as follows // NODE template <typename T> struct Node { T data; Node<T> *next; Node(T); }; template <typename T> Node<T>::Node(T d) : data(d), next(NULL) {} // LIST #include "node.cpp" template <typename T> cl...
Use std::unique_ptr as the data type for the nodes, eg: List<std::unique_ptr<int[]>> l; When each node is destroyed, its destructor will destroy its unique_ptr data, which will in turn call delete[] on the int* pointer it is holding.
61,841,418
61,860,160
Initializing std::vector with ranges library
I would like to initialize std::vector with a range of consecutive integers without typing all of them, something like a second line, which doesn't compile, in this code snippet: std::vector<int> a{0, 1, 2, 3, 4, 5}; std::vector<int> b{std::ranges::iota_view(0, 5)}; // ERROR! Of course, I would greatly prefer: ...
What you’re looking for is auto b=std::ranges::to<std::vector>(std::ranges::iota_view(0, 5)); Unfortunately, that proposal missed C++20 simply because there wasn’t time to review its wording (after a previous version that added the constructor you tried was found unworkable). Hopefully it’ll be merged—and implemented...
61,841,624
61,841,905
Deducing the type of an integer by its compiletime value
Using C++14, 17 or 20, I am passing two template parameters to a templated class: TSize and MaxSize. TSize is the type of MaxSize. Obviously, both are known at compile time. TSize needs to be big enough to fit MaxSize. template <typename TSize = uint8_t, TSize MaxSize = 15> class Foo {}; How can I automatically deduc...
You can use something like this: template<uintmax_t n> using FittingUIntT = std::conditional_t< n <= UINT8_MAX, uint8_t, std::conditional_t< n <= UINT16_MAX, uint16_t, std::conditional_t< n <= UINT32_MAX, uint32_t, uint64_t >>>; Demo
61,842,282
61,842,657
trying to assign callback variable with SDL for audio
When I try to assign the callback variable in the AudioSpec structure, the compiler doesn't like it when I'm trying to assign a type "void function" to a type SDL_AudioCallback. void mainEngineCW4::myAudioCallback(void* userdata, Uint8* stream, int Glen) { AudioData* audio = (AudioData*)userdata; if (audio->length ==...
The SDL callback signature is a stand-alone function of type void (*)(void* userdata, Uint8* stream, int len). Your callback signature is close but not quite a match: void (mainEngineCW4::*)(void* userdata, Uint8* stream, int len). The main difference is that it is a member function, which is part of its type. In shor...
61,842,794
61,869,146
CMake can't get the value of VCTargetsPath when generating for UWP
I'm trying to use CMake to build a Universal Windows App, but I get the following build error (latest Visual Studio 2019 and Windows 10 SDK are installed): › cmake -B. -H<my source dir> -DCMAKE_SYSTEM_NAME=WindowsStore -DCMAKE_SYSTEM_VERSION=10.0 -- Building for: Visual Studio 16 2019 -- Selecting Windows SDK version 1...
I solved the problem. I did many things, therefore I cannot tell which one exactly solved the problem. But try the following. From VisualStudio Installer app, click Modify and install C++ Universal Windows Platform support for v142 build tools (ARM64) individual component.
61,843,070
61,843,767
C++ own Stack of objects. What is copied at push()?
Well, i implemented a FIFO stack (push,pop) stack in a Class with mem allocated ints. So i asked to myself: if "int" is a datatype, why i cannot push "ADTs" to my own stack. Then i came with this code: #include <iostream> class Person { std::string name; int age; public: Person(std::string pName = "", int ...
To answer your question about copies, this: stack[index--] = person; makes a copy, because the type on both sides of the assignment is of type T. This: stack.push(person); also makes a copy, because you are passing person by value. To avoid this (redundant) copy, declare push as: void push(const T &person)
61,843,292
61,843,529
Singleton ofstram: Files created but did not be written
I create a singleton class to wrap some ofstream struct OutputFiles { public: std::ofstream minus_total, plus_total, HoughMappingMinus_cc, HoughMappingPlus_cc; template <typename T> static void init(OutputFilesName<T>& files_name) { instance_impl(files_name); } static OutputFiles& instance() { ret...
This is a strange way to manage objects. Your OutputFiles::init(fn) invokes instance_impl(fn), a function template specialisation. That specialisation has a static local variable called singleton, instantiated with ctor args fn, to which you return a reference. All good. Then, you do OutputFiles::instance() to get a Ou...
61,843,727
61,844,019
Memory leak after deleting pointer
I have a memory leak and I have no idea why it happens. Please note, I removed most of the code that has nothing to do with the issue and most of it was given in the assignment, so I only wrote the Tetrahedron and the add_triangles(...) function: class Geometry { protected: unsigned int vao, vbo; public: /* Gen...
Tetrahedron inherits from Geometry and you are deleting from a pointer to a Geometry object. The destructor of Tetrahedron is not called because you did not define the destructor of Geometry as virtual. Add a virtual destructor to Geometry to allow the destructor of Tetrahedron to be called in this case. class Geometry...
61,844,095
61,844,468
Insert newline into output stream
Let's suppose we have a terminal, and our program has printed some text: line 1 line 2 line 3 And we seek back to the beginning of line 3. I want to print some text without it overwriting previously printed text (I don't want to use ncurse), so I want it to look like: line 1 line 2 inserted line line 3 If I just prin...
(I don't want to use ncurse) There is no general way to do this. C/C++ streams are basically files and behave the same way: If you want to insert a line in a file, you need to rewrite the file from the point of insertion. The same applies to your input, which could also be coming from a file instead of a keyboard. Th...
61,844,206
61,879,631
Boost Hana Implement a custom Sequence
I'm facing a situation where I usually would create a custom class by inheriting from boost::hana::tuple. For example, by using the following code, template<typename ... args> struct my_nonworking_custom_tuple_t : public boost::hana::tuple<args ...> //not working!!! { using base = boost::hana::tuple<args ...>; ...
Generally you shouldn't need to do this, but here is a guide for implementing your own Sequence as well as fulfilling requirements for other concepts in Boost.Hana. (The latter of which should be useful to end users who are not providing their own implementation of a tuple.) Start with the Minimal Complete Definition (...
61,844,234
61,844,470
What is the correct way to clear a class instance of its recursive pointers to a same class instance
I'm building a reset function to a very simple octree class which goal is to reset all of the octree instances created by this same octree. The octree.h class defines a public array of pointers like this Octree *children[8]; bool subdivided; // true if has children and this is the reset function in octree.cpp void Oct...
What is the correct way to clear a class instance of its recursive pointers to a same class instance It depends on what "clearing" means in the context. Access violation reading location 0x0000000000000000 Which according to the call stack, comes from an insert() function called after the reset reset sets the p...
61,844,341
61,865,223
Google KickStart Round B Bus Routes Problem wrong answer?
I was practicing with google kickstart's round B bus route problem. I actually looked at their analysis and implemented their alternative answer. I'll also paste the problem prompt below my code. https://codingcompetitions.withgoogle.com/kickstart/round/000000000019ffc8/00000000002d83bf And my solution passes the fir...
my guess is using int is not sufficient as D can be up to 10^12 in test set 2 Edited: I verified my guess. You will be able to solve the problem by fixing this bug. And I believe the use of long long is common for coding contests, i.e. take note of the input/output constraints every time.
61,845,402
61,871,504
C# and C++ dll - marshalling strings
I made a test application to pass a C# string to a C++ DLL to return its changed value. Examples taken from MSDN: Marshaling Data with Platform Invoke Strings Sample Part of the class for defining DllImport: public class LibWrap { [DllImport( "PInvokeLib.dll", EntryPoint = "TestStringAsResult", ...
found the answer in the book Adam Nathan .NET and COM: The Complete Interoperability Guide on page 791 in chapter 18 friend gave me this link Another case that requires the use of IntPtr occurs when a function allocates memory and expects the caller to free the memory. This is fairly rare in Win32 APIs, because mo...
61,845,675
61,846,123
C++ : Convention on iterator when doing slicing, especially for accessing to the last element and eventually remove it
I have the following function that is supposed to compute the sum of all elements of a vector : double arraySum(vector<double> const &v) { double initial_sum = 0.0; return accumulate(v.begin(), v.end(), initial_sum); } From antoher side, if I have the following list and I want to delete the last string, I do...
As you can see, in the first example, I used v.end() for the last element of a vector No, you did not. You used v.end() to denote the end of the sequence. That's different from the last element. Ranges in C++ (by convention) are half-open. It's just like when you use a for(int i = 0; i < 10; ++i) loop; the range is ...
61,845,708
61,845,827
Why custom comparator functions are passed in Class or Struct?
I am writing a priority queue that has its own comparator function. Every where I see following implementation and not able to figure out what's the rationale behind defining comparator function in class or struct? struct CompareHeight { bool operator()(pair<int, int> const p1, pair<int, int> const p2) { ...
Why custom comparator functions are passed in Class or Struct? Classes are often used rather than the alternative - function pointer that is - because doing so is potentially faster. A function pointer is inherently a form of runtime polymorphism. It is sometimes impossible, or just too difficult for an optimiser to ...
61,845,787
61,845,843
Adjust array by normalizing // functions
working on this problem and having trouble figuring out what's wrong. The 5 indicates that there are five values in the list, namely 30, 50, 10, 70, and 65. 10 is the smallest value in the list, so is subtracted from each value in the list. Input:5 30 50 10 70 65 My output:20 40 0 70 65 Expected output: 20 40 0 60...
Out-of-range access will happen in GetMinimumInt because its argument is wrong. You won't have to make offset for the array: You should use GetMinimumInt(userVals, MAX_ELEMENTS) instead of GetMinimumInt(&userVals[i], MAX_ELEMENTS). Also int minValFun = listInts[1]; // smallest so far in the function GetMinimumInt shou...
61,845,997
61,846,107
Zedboard zynq-7000 Opencl floating point invalid cast from type 'double*' to type 'double'
I'm new at Xilinx development, and i'm preparing my master degree with zedboard. I'm trying to develop a convolution accelerator with Opencl on Zedboard using Vivado HLS. I created the OpenCL block. #pragma OPENCL EXTENSION cl_khr_fp64 : enable #include <clc.h> __kernel void __attribute__ ((reqd_work_group_size(26,1,1)...
You're trying to cast an int*, a, to a double. This cannot be done as pointers store addresses - integers. You'll need to modify you're code to: volatile double **a_addr = (volatile double**) 0x43C00040; volatile double **c_addr = (volatile double**)0x43C00048; ... void main(){ ... double* a; double* c; a = (double...
61,846,511
61,846,619
Suppressed the virtual mechanism by storing object explicitly as base class?
As you'd expect, I've arrived at a question I can't answer and I can only guess. Runtime polymorphism is the goal, using the virtual mechanism, but the result I'm getting is as if I called the method while suppressing it; like I called the base class method. I can only guess then that I am somehow doing that, the call ...
currentScene is a GameScene. You've declared it as such. It will never be anything but a GameScene. A GameScene is not a TestLevel or a TutorialLevel; it is a GameScene. When you assign a TestLevel or TutorialLevel object to currentScene you are slicing it. Polymorphism in C++ only works with pointers and reference...
61,846,748
61,848,376
Should I use `const T&` instead of `T&&` in my code like stl
I have writing code like: template<bool B, typename IfT, typename ThenT> using conditional_t = std::conditional_t<B, IfT, ThenT>; template <bool B, typename IfT, typename ThenT> constexpr auto conditional_v(IfT&& t1, ThenT&& t2) -> conditional_t<B, IfT, ThenT> { if constexpr (B) { return t1; } else { r...
Should I use const T& instead of T&& in my code like stl? If I understand your question correctly, you should use T&& to enable forwarding: #include <utility> template<bool B, class T, class F> constexpr decltype(auto) conditional_v(T&& t, F&& f) { if constexpr(B) return std::forward<T>(t); else r...
61,846,797
61,846,932
Compiling basic program gives ridiculously long output
The code : #include <bits/stdc++.h> using namespace std; int main() { cout << "this file works"; return 0; } Compiler output was ridiculously long. Some 114000 characters long. This is only a portion of it. Compiler output on compilation : C:/mingw-w64/x86_64-8.1.0-posix-seh-rt_v6-rev0/mingw64/lib/gcc/x86_64...
So, what you are seeing is an error message, not an output. If the file bits/stdc++.h is not a file that you created, then what you need to do is to replace #include <bits/stdc++.h> with #include <iostream> and that's gonna solve it for you.
61,846,955
61,847,479
How to avoid duplication on template function return type?
Is there a way to avoid duplication and improve readability on template functions return type ? Here is an example template <typename FunctionType> std::enable_if_t< !std::is_void_v<std::invoke_result_t<FunctionType, MyClass*>>, std::optional<std::invoke_result_t<FunctionType, MyClass*>> > CallIfValid(MyClass* ...
I have the same problem. In my personal opinion there isn't a good real solution, not for the general case. But there are some mitigations/workarounds you can employ. In your example you can add a default template parameter. Also since you specified the return type, you don't need to repeat the type in the return expre...
61,847,197
61,847,323
sstream string wrong output
I am trying to read a string of three number using sstream but when I try to print them, I am getting a wrong output with four numbers. Code: #include <iostream> #include <sstream> using namespace std; int main() { string a("1 2 3"); istringstream my_stream(a); int n; while(my_stream) { my_...
You are printing the data before checking if readings are successful. while(my_stream) { my_stream >> n; should be while(my_stream >> n) { Related (doesn't seem duplicate because eof() isn't used here): c++ - Why is iostream::eof inside a loop condition (i.e. while (!stream.eof())) considered wrong? -...
61,847,526
61,847,565
C++ overloading the << operator
I am trying to overload the << operator in c++, I have implemented the code properly but I have a few doubts about the overall working of the overloading concept. Why does the ostream object in operator<< function need to be passed by reference? Why cant the return type of the function be 'std::ostream' instead of 's...
Not all operator overloading requires passing by reference. For example if you write a class which encapsulates a 2D point and you make an operator- for two of these, you'd probably take the arguments by value (since they are small and simple types with "value semantics"), and it would return the distance by value (be...
61,847,581
61,847,656
Creating a vector in a template class in C++
I am trying to create a vector inside a template class where the type of the vector depends on the template of the class I am defining it in. My code is as follows : template<class T> class A { vector<T*> vec; vec.resize(100); } When I try to compile it I get the following error message : error: ‘vec’ does not...
This has nothing to do with templates. This non-template code would also be an error class A { vector<int*> vec; vec.resize(100); } because vec.resize(100) is not in a function. I guess you want that code to be called in the constructor, like this class A { vector<int*> vec; A() { vec.resize(10...
61,847,693
61,983,483
SFINAE inside concept template argument
Does SFINAE work inside a concept argument? (maybe it's not called SFINAE here). Example: template <class F> requires std::invocable<F, int> && // <-- is this needed? (!std::same_as<std::invoke_result_t<F, int>, void>) auto foo(F f, int a) -> int Is the above std::invocable<F, int> required? If we ...
SFINAE still works with constraints. A substitution failure results in an atomic constraint (such as (!std::same_as<std::invoke_result_t<F, int>, void>)) being deemed as not satisfied [temp.constr.atomic] 3 To determine if an atomic constraint is satisfied, the parameter mapping and template arguments are first sub...
61,847,736
61,848,235
C++ rationale behind Template template arguments
This is not a question about template template syntax meaning, but rather a question about why this syntax was chosen by C++ standard committee. Lets take this example, (1) template< typename T> Class A { ... } The above one is syntax of a class template syntax with single template argument. I can understand this syn...
It does make sense if you break it down step by step. If we start with a declaration of a templated structure T: template <typename U> struct T; If we have a class B which is a template: template <typename T> struct B; If we replace typename T with our declaration above: template <template <typename U> struct T> stru...
61,847,750
61,847,798
How can I call C++ functions from Java?
I am working on a codebase at my current project where the front end has been coded using Java and the backend using C++. I am basically a C++ guy so not sure how I can invoke a C++ method from java code. Can anyone point to a relevant link or provide some outline steps? I tried googling but apart from the fact that I...
To call c++ functions from java, Create a header file (.h file) for a CPP program. Create CPP file Create a DLL In java code, declare the method as native, load the DLL using System.loadLibrary() method and call the method. Check this out for detailed instructions. Youtube Video : link And these links https://www.j...
61,847,785
61,847,857
Using variables entered in one subprogram in another subprogram in C++
#include <iostream> using namespace std; int display(int a) { cout<<"enter a"<<endl; cin>>a; cout<<a<<" "<<a<<endl; } int display_three_times(int a) { cout<<a<<endl; cout<<a<<endl; cout<<a<<endl; } int main() { float a; display(a); display_three_times(a); return 0; } By ex...
You need to pass the result of "display" into "display_three_times". You can do this by replacing display(a); display_three_times(a); with display_three_times(display(0)); and append return a; to the display function. Some style tips. Why declare a as a float in main when you are only dealing with int? Since displa...
61,847,826
61,847,875
unresolved external symbol _____________ referenced in function _main (OPENGL C++)
So I'm following this tutorial on OpenGL for C++ and followed everything the guy did. I am getting these errors and I don't know how to fix them. Severity Code Description Project File Line Suppression State Error LNK2019 unresolved external symbol _glfwWindowShouldClose referenced in function _main Game...
Warning LNK4272 library machine type 'x64' conflicts with target machine type 'x86' GameEngine Sounds like your library was built in 64-bit but you're building in 32-bit? If you're using Visual Studio you can change this at the top. Otherwise, let us know what platform and IDE you're developing on and please provide a ...
61,848,006
61,848,061
calling a struct member declared in a class
I am trying to place functions inside a struct which is part of a class (here named menu) so I can modify the struct inside of a dedicated setup cpp file (I am trying to do this so I can modify all of the functions I want in my application in a single source file instead of changing stuff in all of my cpp files): // ...
pages is the name of the struct, it's not an object. You need an object of type pages inside menu. Otherwise, you can have static methods inside pages and call those without creating objects. Example (live): #include <iostream> struct S { struct P { void print() { std::cout << "Hell...
61,848,054
61,854,393
Credential Providers V2 - Add code after submit and check user's password
How do I add my code after click submit button and check user password? I add my code in GetSerialization function after successfully calling KerbInteractiveUnlockLogonPack and RetrieveNegotiateAuthPackage. But in this state first run my code and later check user password. I want to first check user password and if tha...
I have found the following line in my code to check username/password pair: bRet = LogonUserExA(lpszUsername, NULL, lpszPassword, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, NULL, NULL, NULL, NULL, NULL); lpszUsername us the full UPN in one of forms domain\user or user@domain. The key constant is LOG...
61,848,520
61,848,581
How can I use decltype to get a pointer without a reference?
I have a function: auto get_values_at_indices(auto* array, Vector<int>* indices) { std::vector<decltype(*array)> ret(indices->size()); for (int i = 0; i < indices->size(); i ++) { int index = indices[i]; ret.push_back(array[index]); } return ret; } I'm calling the function with M...
*array is an lvalue expression, then decltype yields T&, i.e. MyClass*&. b) if the value category of expression is lvalue, then decltype yields T&; You can perform std::remove_reference (or std::decay depending on your intent) on the type, e.g. std::vector<std::remove_reference_t<decltype(*array)>> ret(indices->size(...
61,848,793
61,852,716
C++ auto type deduction when declaring variables without initialisation
I actually really like the automatic type deduction in C++, where I can have an arbitrarily complex return type from a function, but not worry about what the type is when calling the function. In other words, something like: std::vector<std::map<std::string, std::string>> getCollection() { ... } auto myMapArray = getCo...
Concerning your comment: It appears it would be useful to allow type deduction of a variable as if it were something returned from a function, such as with: std::vector<std::map<std::string, std::string>> getCollection() { ... } auto m_collection = asif(getCollection); It appears to me that asif() sounds somehow lik...
61,848,810
61,849,105
Getting MLE(Memory Limit Error) in my following code. Tried solving ROUND C 2019(Problem A- Wiggle Walk) Kickstart question
I AM GETTING MLE ERROR. Please suggest strategies to avoid this error. I am getting the correct answer though. QUESTION - Problem Banny has just bought a new programmable robot. Eager to test his coding skills, he has placed the robot in a grid of squares with R rows (numbered 1 to R from north to south) and C columns...
You are getting MLE because you are exceeding the memory limit. I am assuming that you have made a mistake writing the constraints. I think the limits for the big case is 1 <= N, R, C <= 5*10^4. So in the worst case you are declaring a 2D vector of size 5*10^4 * 5*10^4 which is 25*10^8 which takes approximately 10 GB o...
61,848,985
61,849,181
Error: base class undefined in deriving class Son from baseclass Father
I made two classes Father and Son, split into .h and .cpp. Why do I get the above Error? I have another Solution with basicly the same includes and no error. Sorry if this is trivial but I'm new to c++ and confused why it works in one Solution but not the other. Edit: When I run the program, the Terminal still opens ...
why doesn't it work the way I wrote it? Son.cpp compiles fine, because it includes the declaration of Father from Father.h before the declaration of Son from Son.h. The problem occurs in Main.cpp. Here you only include the declaration of Son from Son.h. The class Father is not known to this compilation unit. Make s...
61,849,034
61,849,121
Understanding C++ heap/stack allocations when passing dereferenced pointer by reference
I am trying to understand what happens with object creation and destruction in this example. #include <iostream> class Person { public: const int name; Person() = delete; Person(int& name) : name(name) { std::cout << "Person " << name << " created" << std::endl; } Person(const int& name) : ...
Add copy-constructor to see the whole picture. Although Family::Family gets the objects by reference, it then copies them into the members mom and dad. So the destructor invocations you observe actually occur when those members get destructed. The original objects are not freed - until the program exits. As for the...
61,849,443
61,849,653
Remove node in linked list with function taking reference to pointer to a node?
Consider an implemented struct Node: template <class T> struct Node { Node<T> * next; T data; // Other functions for adding nodes etc... }; Then a function remove(...) is given, which takes the parameters 1) reference to pointer to node p and 2) the data d to be removed: template <class T> void remove(Node...
Since temp points to p, won't the assigned p=p->next be removed anyhow in delete temp, making this function fail? temp doesn't point to p but to what p points. Note that the pointers are vars having addressees as values and when a pointer on the rhs it returns its value. And the assignment p = p -> next makes the v...
61,849,654
61,853,758
C++ Types of global header functions explained
Currently I want to have a global function inside a header file. I've found three possible ways to implement it (there are probably more). The first one is to have a class which has a public static function: class foo { public: static void bar() { ... } }; The second is to have an inline global functio...
An alternative to the first approach (a static member function in a class) is to use a named namespace: namespace foo { inline void bar () { ... } } If every member of the class foo is static, it might well be better to use the named namespace approach as the latter (namespace foo) does a better job of...
61,849,665
61,849,717
C++ Best way to return value?
I was wondering about a more theoretical than practical question - what's the best way to return a value from a function? I can do something like this std::string foo(void) { std::string buf = "Hello World" + to_string(1); return buf; } Or I can do like this std::string bar(void) { return "Hello World" + to_stri...
It's mostly a matter of style. But there are subtle differences because of copy elision. Since C++17 when returning a prvalue (your case return "Hello World" + to_string(1);) the compiler must do copy elision because/return value optimization. In your case with return buf the compiler can do copy elision/named return v...
61,849,858
61,849,971
Specification of use of overloaded function
template <typename T> class Obj { public: Obj<T>* doThis(); const Obj<T>* doThis() const {// return normal version of doThis()} }; In the example, I want the const version of doThis() to return normal version of doThis(). I don't think it's ok to just put return doThis() in definition of const version of doThis() bec...
As Story Teller mentioned in the comment, don't do this, because this can lead to UB, e.g., in this simple case: const Obj<int> obj; obj.doThis(); // UB since you will have to const_cast<Obj<int>&>(obj). The proper thing is to do it the other way: template <typename T> class Obj { public: Obj<T>* doThis() { ...
61,850,025
61,850,204
Logical negation and assignment operator in C/C++?
Is there a more concise way to write the second line of this function without repeating a reduntantly? void myfunc() { bool a = false; // Assume that this won't alway be hardcoded to false. a = !a; }
The only possible answer is: unfortunately not. The unary operator ! is actually concise enough, and any other trick would lead to unreadable code. Any other shortcut form, for example for binary operators such as + or *: a += 5; b *= 7; mantain the reference to the original meaning of theoperator: multiplication and ...
61,850,030
61,850,149
How to use class member function of an object on different switch case statement?
My class-: For Creating, Displaying Diagonal Matrix class Diagonal { private: int *A; int n; public: Diagonal(){ n=2; A = new int[n]; } Diagonal(int n){ this->n = n; A = new int[n]; } void Create(){ cout<<"Enter the Elements : " for(int i =0...
You can use a unique pointer: #include <iostream> #include <memory> #include <vector> using std::cin; using std::cout; using std::endl; class Diagonal { private: std::vector<int> A; public: Diagonal() : A(2) {}; Diagonal(int n) : A(n) {} void Create() { cout<<"Enter the Elements : "; f...
61,850,237
61,850,311
C++, new vs malloc return value
When I learnt C99 I was told to Always check the return value of malloc to check whether it succeeded or failed, but now I started learning C++ and I was told that there is no need to do this with the keyword new, and you can suppose that it will always work for you. But why is that?
new can still fail and throw an std::bad_alloc exception, and your program needs to may check whether it did, or simply let the exception propagate up. There is also a flag you can pass to new to make it act like malloc and return NULL on error. Take a look at the documentation. Edit Here are two examples: try { cha...
61,850,433
61,902,093
How to implement a wrapper around C 'objects' using smart pointers?
I am using a C library which uses raw pointers from C++. Therefore, I'm looking into wrapping all the pointers to C objects in C++ classes and turning them into smart pointers. I've built a working example: #include <iostream> using namespace std; // the C library is oop: using structs and naming conventions. Like th...
You can use std::unique_ptr for managing lifetime of Animal objects: #include <memory> struct FreeAnimal { void operator()(Animal* a) const noexcept { free_animal(a); } }; using AnimalPtr = std::unique_ptr<Animal, FreeAnimal>; int main() { AnimalPtr party_animal{make_animal(21)}; do_somethin...
61,850,460
61,850,776
Make min priority queue of arrays c++
I want a min priority queue which instead of containing integers, stores arrays. The priority of each element is the first element in the array. priority_queue<array<int, 6>, vector<int>, greater<int>> pq; array<int, 6> arr = {a, b, c, d, e, f}; pq.push(arr); array<int, 6> popArr = pq.pop(); When I do this I get the f...
First of all the type of data structure in priority queue is array<int,6>, so vector<int> should be written as vector<array<int,6>>. Now the third argument is comparator. So lets create a comparator : struct Compare{ bool operator()(array<int,6> a,array<int,6> b){ return a[0]>b[0]; } }; Now declaration looks ...
61,850,684
61,851,388
why is 'Hello' being printed out when it is compared with 'World' in cpp?
I was trying templates in CPP. I could not understand why 'Hello' is being printed when I compare it with 'World'? Below is my code snippet -> #include <iostream> using std::cout; using std::endl; template <typename T> T max(T a, T b){ if(a > b){ return a; } else{return b;} } int main() { cout << "max(3, 5): " << ...
Instead, you can use two templates T and P for the same. #include <iostream> #include <string> using std::cout; using std::endl; using std::string; template <typename T,typename P> T max(T a, P b){ if(a > b){ return a; } else{return b;} } int main() { cout << "max(3, 5): " << max(3, 5) << endl; cout << "max('a', ...
61,850,702
61,850,918
C++: Making a function friend of multiple classes?
Here's a Doubly Linked List class that I wrote: template <class T> class DLL { class Node { T m_data; Node* m_prev; Node* m_next; Node(const T& data) :m_data{ data }, m_prev{ nullptr }, m_next{ nullptr }{} friend class DLL; friend std::ostream& operator<<(std::...
Yes, a function can be a friend of more than one class. But friends are not inherited, so even if operator<< is a friend of DLL<T> and DLL<T> a friend of DLL<T>::Node, it doesn't automatically make operator<< a friend of DLL<T>::Node, hence it can't access the private DLL<T>::Node::m_next. The solution is to declare it...
61,850,784
61,852,733
out of class definition of function template using expression-SFINAE
I'm trying to implement a simple serializer class, which has a Serialize function that dispatches the actual serialization to different overloaded function templates, selected at compile-time using expression-SFINAE with decltype: #ifndef SERIALIZER_H #define SERIALIZER_H #include <string> #include <utility> /**** ba...
The reason the compiler cannot match the definition with the declaration is the following: [basic.lookup.unqual]/p7: A name used in the definition of a class X outside of a complete-class context ([class.mem]) of X shall be declared in one of the following ways: before its use in class X or be a member of a base clas...
61,850,867
61,851,306
Infinite loop scenario in custom throttler (race condition?)
I wrote a custom throttler to handle scenarion when some client (that is making outside calls) is getting backoff exception and needs to sleep before making another API Call. I have a memory dump with a strange scenario: stuck in an infinte loop, although I see no reason for it. This application has many threads, and a...
There is no guarantee that the value of m_isTrhottling in your thread will ever get its true value. In fact, every thread has its own view of the world, so that in the view of the other thread, that writes to m_isThrottling, the value is true, but your third sees a different picture. Locks is one way in which the world...
61,851,153
61,851,218
Add a new element to a list, and return a reference to that element?
How can I add a new element to a list, and get a reference to the element that is created in the list? std::list<My_class> list; My_class new_obj; My_class& newly_created_obj_ref = list.add(new_obj); // <-- this won't compile, but it shows what I'm trying to do
You can write My_class& newly_created_obj_ref = ( list.push_back(new_obj), list.back() ); Here is a demonstrative program #include <iostream> #include <list> int main() { std::list<int> lst; int &rx = (lst.push_back( 10 ), lst.back()); std::cout << rx << '\n'; rx = 20; std::cout << lst.back()...
61,851,236
61,851,275
Pass object to a function without wrapping it into std::ref, while argument is specified as a const reference
I have the following c++ code(just a simple example for a question) #include <iostream> #include <string> #include <vector> double get_first(const std::vector<double>& vec) { return vec[0]; } int main() { std::vector<double> some_vec = {1, 2}; std::cout << get_first(some_vec); } So here parameter of the func...
std::ref is not for that. It is used to convert an existing reference to an object, used where a reference cannot be accepted, like within a std::vector<>. The idea is that references cannot be reassigned or set to null, so stuff in STL containers like moving etc wouldn't work with a raw reference. Most likely it inter...
61,851,329
61,851,393
Why does this code snippet work? How can a nullptr be dereferenced?
#include <iostream> class Singleton { private: static Singleton* s_instance; public: static Singleton& Get() { return *s_instance; } void Hello() { std::cout << "Hey Bro" << std::endl; } }; Singleton* Singleton::s_instance = nullptr; int main() { Singleton::Get().Hello(); ...
It's undefined behaviour, as StoryTeller says. Most probably it "works" because you don't actually use the pointer at the assembly level. Member functiors are static functions which take the this pointer. In your member function Hello(), this is not used because you are not accessing any member variables. So the functi...
61,851,439
61,851,473
Getting two different answers on same input just by different methods of initialization of an array in C++
I was solving a DP problem, Longest Increasing Subsequence, wherein I initialized the dp array by two different methods and got different results for the same input. First method, where I got the wrong answer was: int dp[n] = {1}; Second method, again a wrong answer: int dp[n]; mem...
With int dp[n] = {1}; you initialize the first element to 1, and the rest to zero. With memset(dp, 1, sizeof(dp)); you set all bytes to 1, which means that each element in the array will be 0x01010101. The "correct" way to set all elements of an array to a specific value is to use the algorithm function std::fill or ...
61,851,647
61,851,684
If statement incorrectly reads string, always returns on first condition
I'm writing an error-checking function that takes a string variable, and I need it to be one of "Y", "N", "y", or "n". My problem is that the string variable always gets set to "y", indicating that the if statement doesn't get past the first condition, no matter what input the variable receives. If there is an obvious ...
string == "y" || "Y" doesn't do what you think it does: it compares string against "y", and then ORs the result of that with "Y". Since "Y"' is non-zero, it always evaluates totrue`. The correct code is: string == "y" || string == "Y"
61,851,943
61,852,346
dynamic allocation and value of the class member
Why does value k change, after the second call of check(base)? class Base{ public: int k=0; virtual void print(){ cout<< k<<endl; } }; Base* check(Base* p){ Base* t = new Base; t->k = 4; delete p; return t; } int main(){ Base* base = new Base; cout<< check(base)->k; // first c...
Accessing memory pointed by ptr after delete ptr is UB My guess in your case is that after you invoke delete p (a.k.a. base), Base* t = new Base allocates memory where base used to point at.
61,852,063
61,852,257
How to write the algorithm of Selection Sort for sorting list of elements in descending order using cpp?
I am trying to print the sorted list in a descending order. This code below is giving me the default ascending order i want the way to make it in descending order. You can also check the code the thrownbin #include <iostream> using namespace std; class selection { int siz, *ar; public: void getInput(); void selectSo...
Well your algorithm is checking if one index is greater than the next element and if it is you are swapping it, if you want the largest element at the beginning then if the first index is larger than the second index do nothing else swap them. Alternatively, printing your array starting from the last index and decreasi...
61,852,175
61,852,420
Issue With Type Conversion
I had a question regarding a type conversion error I encountered whilst solving a question (link at the bottom). The only difference between my AC submission and my WA submission is that in the first submission I typecasted to a double rather than a float. I would highly appreciate any clarification on why float give...
You need to understand that calculations involving decimal numbers result in some error if the final number is recurring or has very long fractional part (eg. 1.000000000078). Since, double is of 2x precision it is able to handles these errors (mostly rounding errors). Try to use long double instead in these contest q...
61,852,487
61,852,753
C++ TEXT macro of TCHAR*
I am trying to create a TCHAR* variable by using TCHAR* example = TEXT("example"); but it wont even compile and says: A value of type const wchar_t* cannot be used to initialize an entity of type TCHAR*. What should I do?
You have to add const, because the TEXT() macro returns a pointer to a const wchar_t. const TCHAR* example = TEXT("example"); If the assignment were allowed without the const, you would be able to modify the const wchar_t data through the pointer. See also A value of type "const char*" cannot be used to initialize an ...
61,852,725
61,885,433
Cannot create .exe file in Visual Studio 2019 after updating to may 2020 build
This is similar to this Visual Studio -- does not create exe file but none of those suggestions helped me. When I start project without debugging it shows '"C:\dev\Atcoder\abc_168\A\Debug\A.exe"' is not recognized as an internal or external command, operable program or batch file. Press any key to continue . . ....
The reason is that cmd.exe Being a terminal window relies on input and system Environment variables, in order to perform what you request it to do. it doesn’t know the location of everything and it also does not know when to distinguish between commands or executable names which are separated by whitespace like and or ...
61,852,901
61,853,091
How to initialize std::vector<std::time_t> with n elements in constructor initializer list
I am trying to initialize vector in constructor initializer list like so: Foo::Foo() : vec{42} { // ... } The vector is declared as: std::vector<std::time_t> vec; Problem is that std::time_t is numeric type also, so instead of creating vector with 42 elements as I would like, it creates one element with stor...
When initialized with braced-init-list, the constructor of std::vector taking std::initializer_list is preferred; for vec{42} it would initialize vec as containing 1 element with value 42. You can apply parentheses initializer instead of braced-init-list (which is a C++11 feature). Foo::Foo() : vec(42) // initializ...
61,853,965
61,858,022
How to read a process' memory using code compiled with g++?
I want to read the process memory of notepad.exe and find the string Hello World! inside it (it's typed inside a Notepad window). I want to use g++.exe, not cl.exe, because it's too much of a hassle to try to figure out how to set the proper environment variables to be able to use it from the command line instead of fr...
Here is a better answer than my last, since the previous only searched the executable image which only contains what's in the .exe file and not it's dynamic memory. Compile with: g++ filename.cpp -lpsapi The order of the #includes is important; <Windows.h> must come before <psapi.h>. #include <Windows.h> #include <psap...
61,854,244
61,854,425
Why c++ empty class have no byte alignment?
I recently learned that empty class have size 1 instead of zero.Why it has no byte alignment, in which it's size should be 4 in 32bit environment? What's the address of the next object?
Because C++ simply does not guarantee 4-byte alignment, or word-alignment, of variables. If this is important to you, you can specify an alignment requirement using alignas: struct alignas(4) my_empty_struct {}; and now, the address of a my_empty_struct variable would be a multiple of 4 - and so will its size, apparen...
61,854,346
61,854,786
C++ lvalue references
So recently I revisited references on the type declaration but I didn't quite understand them. Consider this dummy code: int ia = 10; int& ref = ia; Now, my questions are: how do these int& ref work internally, does it mean here that the address of ref is assigned the address of ia and thus equal to &ia if not then ...
C++ standard doesn't specify how reference should be implemented by the compiler. A lot of people think they are just aliases, but in fact, under the hood they are just implemented as const pointers. C++ references are const pointers under the hood. So: int ia = 10; int& ref = ia; ref++; // ia is 11 now might be conve...
61,854,627
67,775,225
RTP packer creation using objective c
I am new in this area. I have been trying to make a demo RTP packet but every time trying to send the packet it is showing UDP packet instead of RTP packet on the wireshark. Please I need to know what I am doing wrong. struct rtp_header { u_int16_t v:2; /* protocol version */ u_int16_t p:1; /* padding flag ...
If you send packets this way, you will only see UDP packets in Wireshark because Wireshark examines whether the packet is only SIP or RTP based on the SIP protocol. That means first you have to send an invite request with a valid SDP body, once Wireshark finds a Sip packet with valid SDP then it stores the incoming RTP...
61,854,897
61,862,324
how to apply a three point triangle gradient in opencv?
Say we have a Delaunay-triangulation like this one: produced from fillConvexPoly on getVoronoiFacetList Inside there are triangles that can be obtained via getTriangleList. I want to draw Delaunay-triangulation like it is a smooth gradient image composed of triangles like this: How to do such thing in opencv?
This is how to do it in Python/OpenCV, but it will be slower than the Python/Wand version that I previously presented, because it has to loop and solve a linear least squares equation at each pixel for the barycentric coordinates. import cv2 import numpy as np # References: # https://stackoverflow.com/questions/3144...
61,855,386
61,855,468
Is c++ still saving a "reference of the original value"?
I'm learning C++ and i have this code: long long unsigned number; cout << "Introduce a non negative number: \n"; cin >> number; cout << "The number is equal to: " << number << endl; cout << number*number; When i introduce a negative value, per example -1 the message display that the number is equal to 1844674407370955...
This is because of modular arithmetic. When you assign -1 to an unsigned number, it gets stored as a number of the form 2^n - 1 (n depends on the archtecture, but is the largest possible positive number of that type). All operations on values of this type follow the same modular arithmetic. So when you multiply 2 -1s,...
61,855,809
61,855,883
How to add a "new tab" on an existing QTabWidget using a QPushButton
I am trying to add a "new tab" on an existing QTabWidget using a QPushButton as shown below: The problem I have is that as I push the button nothing happens and no "new tab" is added. I set all the proper connection and slots but something is preventing me from adding it to the QTabWidget. Basically nothing happens a...
connect the clicked signal of the button to the addTab function/slot of the tabwidget (or to an intermediate function/lambda that calls addTab on the correct destination object). For example: connect(ui->addTabBtn, &QPushButton::clicked, this, [&] { ui->tabWidget->addTab(new QLabel("+"), QString("+")); }); Or somethin...
61,855,881
61,989,242
Trouble using FIFOQueue in Tensorflow C++
I have had some success using this programming format in tensorflow with other ops, but I am unable to get the FIFOQueue to work properly. The following code will compile and run, but there is never any data placed on the queue. vector<Tensor> outputs; Scope root = Scope::NewRootScope(); auto queue = FIFOQueue(root, ...
I was actually pretty close, but there was some misunderstanding of the nature of the call. Each of the operations in the graph start from queue, so repeated calls to session->Run requesting the appropriate output are what is needed to effect the action of the queue. A slightly more detailed example follows. It push...
61,855,929
61,856,137
Taking a non-const reference of DenseBase<Derived> and fill it inside a function does not work
I am writing a function to sort dense matrices or arrays in Eigen and also return the indices of the arrangement. The function is the following: template<typename Derived1, typename Derived2> typename Derived1::PlainObject sort(const DenseBase<Derived1> &x, DenseBase<Derived2> &indices) { typename Derived1::PlainOb...
You need z to be a reference to indices.derived(), instead of a copy: typename Derived2::PlainObject & z = indices.derived(); Make sure that derived() returns a reference as well.