question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
65,973,148
65,973,325
C++ memory overcommit Linux
I am currently coding a server application that basically processes workloads for clients. Based on the actual workload, the server could use huge amounts of memory. Target Platforms are Windows and Linux, the code is written in c++. However, i am not very familiar with linux programming and during some testing today i...
So, i was wondering if i could turn off overcommit for my process and child threads. I already found an old question here Link (at stackoverflow) that answers this as no, but realizing that this is a 10 year old answer i was wondering if that might have changed? No, you still cannot change overcommit settings per-pro...
65,973,701
65,974,440
Why beast/boost response says, "cannot convert from initializer list" to...?
I'm using an example given in boost/beast prepare_payload() http::response<http::string_body> res{http::verb::post, "/"}; res.set(http::field::user_agent, "Beast"); res.body() = Respon.dump(4); res.prepare_payload(); 2 things i've changed, name of constant, and data put in body(). (Respon is Json, Respon.dump(4) i...
You're initializing a response as if it were a request. A response doesn't have a http verb or request path; A response constructor can initialize the message and fields, thought it's more conventional to initialize them after construction, and pass the status/version in the constructor: Live On Coliru #include <boost/...
65,973,826
65,974,042
C++ 20: Can concepts interface a method?
To preface this, I wanted an interface, and figured that C++20 had an interface mechanic. I have never used C++20, and found concepts about 2 hours ago. So the mistake here could be something really simple. Suppose I have an imperative 3rd party library I would like to abstract away because imperative code is messy....
Your concept has wrong syntax, it should be: template<typename Context> concept ExtensibleContext = requires(Context & context, const char *s, bool b, void *p, uint32_t n) { context.addExtension(s, b, p, n); };
65,974,210
65,974,266
Using uninitialized memory for variable ans
I am trying to solve a problem from the CodeForces. The problem name is Sereja and Dima. I have a written code that keeps giving me 2 errors. 1st one is using uninitialized memory ans. 2nd is using uninitialized memory ans[ BYTE:0]. I am using Microsoft Visual Studio 2019. Any kind of help or suggestions would be appre...
The compiler already told you what to do. What value are you supposing to be in ans If you haven't intialized It? Do you expect It to be 0? Then initialize: int ans[2] = {0}; or use vector that already initializes to 0 by default: vector<int> ans(2); Remember that x += y; is equivalent to x = x + y; and, If that the fi...
65,974,501
65,974,568
Why my factory pattern return error while compiling?
I want to implement simle factory pattern but when I try compile code i get error like: error: undefined reference to `vtable for Interface' error: undefined reference to `typeinfo for Interface' class Interface{ public: virtual void set(const std::string &data); virtual void get(const std::string &data); v...
Your interface is not correct. You didn't implemented your function and they are not pure virtual. I think you meant them to be pure virtual: class Interface{ public: virtual void set(const std::string &data) = 0; virtual void get(const std::string &data) = 0; virtual void show() = 0; virtual ~Interface...
65,974,539
65,974,584
Why does my compiled .exe of C++ file shows an error that does not ordinarily appear?
Today, I just created a typing meteorite project. I thought it would be great to simply call system("py -3.8 wait.py 0.1"); in C++ to wait for 0.1 seconds. It was successful in normal execution in visual studio code, but when I execute the compiled .exe file, it repeatedly shows that the file wait.py does not exist, wh...
Use a absolute path for call wait.py ! For example: system("py -3.8 C:\Users\wait.py 0.1");
65,974,573
65,986,976
not working Passing instance of class by reference in qt c++ lambda Signal&Slots
This code in Profile3.cpp i just want to pass the instance kitchenData of Kitchen_Data class reference not by value but it prints that error: undefined reference to `Profile3::Kitchen_DoubleClicked(Kitchen_Data&)' Profile3::Profile3(QWidget *parent) : QWidget(parent), ui(new Ui::Profile3) { ui->setupUi(this...
As mentioned in the comments, passing a reference to a local variable in the lambda is a bad idea. The instance kitchenData will already be out of scope/destroyed by the time you access it from within the Kitchen_DoubleClicked slot. To make it survive long enough to be used by the slot, you need to either dynamically a...
65,974,701
65,995,812
lib error in visual studio, most likely cause _ATL_MIN_CRT
I am trying to compile a program that uses SDL in Visual Studio Community 2019. I keep getting the error LIBCMTD.lib(exe_main.obj): error LNK2019: unresolved external symbol main referenced in function "int _cdecl invokemain(void)" (?invokemain@@YAHXZ). I looked online for this error and found out that the most likely ...
Make sure both SDL2.lib AND SDL2main.lib are included included. Then include shell32.lib. After that add int argc, char* argv[] to the main function.
65,974,970
65,974,996
Getting several WM_PAINT message with one dispatch
I'm getting several WM_PAINT messages/events in the message handler for my window while I resize it, even though I only translate+dispatch a single message. Is this normal? Why is this happening? (I was expecting to get one WM_PAINT message per dispatch, and never more than that) Window loop: while (true) // only for t...
The answer is simple: Starting the resize enters into a nested message-loop, one you didn't instrument. Thus, you get posted messages delivered which the outer loop, which you wrote yourself, never knew about. That the WM_PAINT message is generally generated for an empty message-queue if there was any invalidation, ins...
65,975,068
65,976,362
Quicktime 7 API for Windows - couldNotResolveDataRef
I'm trying to use the Quicktime 7 API for Windows (I know) because eventually I'm going to try to change the audio channel layout flags in Quicktime files, but right now I'm simply trying to create a "Movie" object. I'm very familiar with languages like Python and JavaScript, but very new to C++. Despite that, I'm able...
For anyone interested. I finally got it to work with this code. #include <iostream> #include <Movies.h> #include <QTML.h> int main() { std::string mystring = "D:\\CodingProjects\\_ffmpeg\\test.mov"; OSErr initerr = InitializeQTML(0L); OSErr entererr = EnterMovies(); CFStringRef inPath = CFStringCreat...
65,975,550
65,976,919
cmake post-process static library target
I am using cmake to create my static libraries with something along the lines of add_library(library library.cpp) install(TARGETS library DESTINATION lib) which creates liblibrary.a which is what I want. However I would like to bundle that with a library, let's say vendor/proprietary.a by doing something custom like t...
This is, disappointingly, quite hard. We managed to do it on the Halide team, but only because it was a hard requirement from a corporate client. To other readers without such constraints, I say this: here be dragons. Use CMake's usual targets and dependencies and let it put all the static libraries on the end-product'...
65,975,629
65,976,272
Does RDTSCP increment monotonically across multi-cores?
I'm confused whether rdtscp monotonically increments in a multi-core environment. According to the document: __rdtscp, rdtscp seems a processor-based instruction and can prevent reordering of instructions around the call. The processor monotonically increments the time-stamp counter MSR every clock cycle and resets it...
On most systems yes, if you create synchronization between threads to make sure that one actually does run after the other1. Otherwise all bets are off; starting one thread before another does not ensure that its code executes first. Footnote 1: e.g. having one spin-wait until it sees an atomic store done by the other...
65,975,821
65,975,908
Given a string formed only with 4 different letters, how many permutations of it exist with no two consecutive letters?
Given a string S, formed with the letters A, B, C, D, each occurring at most 10 times in S How many permutations of S do not contain 2 consecutive letters? For example given A: 3 times, B: 1 time, C: 1, D: 0 ABACA is valid AABAC is invalid I've tried inclusion exclusion but my model haven't been able to produce a goo...
It's dynamic programming Creating each permutation from the scratch, so you are adding a letter at a time at the end of the string Suppose you just have used letter 'A', the next letter can't be 'A', and you have 1 letter 'A' less than before, So you continue with this process until you run out of letters Let be f(proh...
65,975,823
65,975,849
Nested loop for triangular matrix in C++
Please can someone explain why I am getting 7 at the last iteration of the loops instead of 6? It this a problem of my loops structure or the compilator needs an additional information? #include <iostream> using namespace std; int main() { int p = 4; int i, j, k; for(i=0; i<(p-1); i++){ for(j=(i+1); j<p...
Basic algebra with integer division using: i = 2 j = 3 Let's compute your line of code: k = i * (p - (i+1)/2) + j - i Breaking it down: k = i * (p - (i+1)/2) + j - i k = 2 * (4 - (2+1)/2) + 3 - 2 k = 2 * (4 - 3/2) + 3 - 2 k = 2 * (4 - 1) + 3 - 2 k = 2 * 3 + 1 k = 6 + 1 k = 7 For what's it's worth, each +1 incre...
65,975,868
65,976,204
Make a variable const in cpp then give its address to a pointer but dereferencing not mutate the variable why?
making a variable const in cpp then give its address to a pointer and change its value by dereferecing but I still gets the value that I stored initially. code snippet const int a = 5; // then // a = 7; not possible // bypassing const using pointers int *ap = (int *)&a; *ap = 10; cout << *ap ...
Any program that modifies a variable or member declared const has behaviour no longer defined by the C++ standard. This is known as UB. Common symptoms of UB are crashing, "it seems to work", wierd inconsistent state, and even time travel where the future UB changes behaviour before it happens in your code. A good C++...
65,975,966
65,976,005
How to solve no output problem when I use vectors of vector to implement a graph data structure?
#include <iostream> #include <vector> using namespace std; class Graph{ int v; vector<vector<int> > adj; public: Graph(int v){ this->v = v; } void addEdge(int x, int y){ adj[x].push_back(y); adj[y].push_back(x); } ...
Graph(int v) { this->v = v; adj.resize(v); //do this } You have declared adj but adj[x] in addEdge() won't work because you are trying to access something for which memory hasn't been allocated. So, vector subscript will be out of range. Now it prints: 0 --> 1 2 1 --> 0 2 --> 0
65,976,105
68,355,170
How data is moving across filters through pins in OBS-Studio virtual camera on windows?
I liked OBS-Studio's virtual camera feature. I tried to understand its working but could not understand properly. I only understood that it is built using DirectShow. Project contains OutputFilter, OutputPin, CaptureFilter and CapturePin class OutputFilter : public IBaseFilter { // ... friend class OutputPin; ...
They are using a shared memory server. Basically, they have a rendering filter that copies the incoming bitmaps into the shared memory. And then they have a capture filter that reads the bitmaps from the shared memory. You can see some of their code here: win-dshow
65,976,147
65,976,188
What's the meaning of WM_KEYFIRST and WM_KEYDOWN (both 0x0100)? And why it's 4 hex digits long?
What's the meaning of #define WM_KEYFIRST 0x0100 #define WM_KEYDOWN 0x0100 #define WM_KEYUP 0x0101 ? Those are lines 1038, 1039 and 1040 in winuser.h library. Why those values and why WM_KEYFIRST and WM_KEYDOWN both are related to the same value 0x0100? What's the purpose of making two names to the same value? And wh...
The WM_KEYFIRST to WM_KEYLAST defines the range of keyboard-related messages. This is easier to remember than hardcoding the range to something like WM_KEYDOWN to WM_UNICHAR, and also more portable, since for example WM_KEYLAST was not WM_UNICHAR before Windows XP. For an example, the following will filter the keyboard...
65,976,252
65,976,448
Retrieving and displaying even number
So I am trying to get my even numbers to appear and tell me the result of the user input. Not sure why my function is an error in my main when I tried to just have it output in my even function won't print. Unsure why? also curious should I lock and make my array constant? It isn't changing but might feel like I have t...
Your EvenElements() requires three arguments and you're passing only one and therefore, your code as it is will not compile. Try the following (read the comments for the last 3 lines): #include <iostream> #include <string> using namespace std; // putting our voids first to declare be declare and run first void fillUp...
65,976,441
65,978,654
How to correctly manage initialisation in constructor?
I'm writing a simple wrapper in C++ around GLFW and OpenGL, as an exercice. I have a class Window and a class Renderer. The Window class owns a Renderer member. Window sets the GLFW context in its constructor and run the main loop, and call for its Renderer member to draw. Renderer sets the buffers in its constructor, ...
I suggest that you create a separate class, call it GLFWInit that does the GLFW initialization and calls glfwTerminate() in its destructor. Then you have two options: Embed an object of type GLFWInit in your Window class. Place the member early, but at the least before the m_renderer member. Derive your Window class ...
65,976,778
65,977,480
How to create the top object with yaml-cpp?
I am trying to create a config file for my application using yaml-cpp, I am able to create map by YAML::Emitter emitter; emitter << YAML::BeginMap; emitter << YAML::Key << "Autoplay" << YAML::Value << "false"; emitter << YAML::EndMap; std::ofstream ofout(file); ofout << emitter.c_str(); which ...
What you want to achieve is a map containing two keys Foo and Bar. Each of these containing a map as a value. The code below show you how you can achieve that: // gcc -o example example.cpp -lyaml-cpp #include <yaml-cpp/yaml.h> #include <fstream> int main() { std::string file{"example.yaml"}; YAML::Emitter emitte...
65,977,100
65,977,395
Segfault while inserting node at mid of a linked list in c++
I am creating a simple singly linked list and trying to insert a node at start, mid and end of the list. But my 'insertAtMid' is not working properly and its crashes the program with error; "Exception occurred. Segmentation fault." Here is the whole program : /* Write a program that creates a singly linked list unt...
According to your instance of code, you are counting the number of nodes and you are moving the head pointer till the end of the list. Before the below statement gets executed, the head will be at currently pointing the last node. while((middle --) > 1) { head = head->next; } As soon as thi...
65,977,120
65,978,375
How to use LocalAlloc and LocalReAlloc correctly
I am going to learn how to use LocalAlloc and also LocalReAlloc of the Win32 API. I written the following code, but it gives me exceptions. I don't know what is wrong with the following code. #include <Windows.h> #include <iostream> namespace code { namespace memory { void allocation() { ...
There are several issues with your code. A complete lack of error handling. If LocalReAlloc() fails, you are leaking the memory allocated by LocalAlloc(). The second CopyMemory() is exceeding the bounds of the string literal being copied. And you are not ensuring the reallocated memory is null terminated for the follow...
65,977,217
65,977,254
Passing an object as an argument to a function in C++
I have this simple program that gets the two lines (objects) with their coefficients, and returns 2 if they cross each other, 1 if they are parallel, and 0 if they are the same line. #include <iostream> using namespace std; struct line { float a; float b; } line1, line2; int lineRelation = (line l...
You didn't declare your function correctly: int lineRelation = (line line1, line line2) { That's not the right way to declare a function. Look at main as a viable example. While we're at it, make sure to pass your objects by reference for efficiency. Else the code makes a needless temp copy. Better: int lineRelation(c...
65,977,376
65,977,497
Process foreign language in C++
Hello I want to process Arabic language in my C++ code. My code int main() { wchar_t s[] = "ﺳﺄﻟﺘﻚِ ﺏﺎﻠﻠﻫ - ﻳﺎ ﻥﻭﺭ ﻊﻴﻨﻳ -\nﺏﺩﻮﻨﻳ ﻫﻞ ﻒﻳ ﺍﻟﺤﻴﺎﺓِ ﺣﻴﺎﺓ ؟\nﺖﻋﺎﻠ"; for (auto ch : s) { cout << ch; } } I received an error error: int-array initialized from non-wide string Also I tried wstring int main() {...
You could do it like this: wchar_t s[] =L"ﺳﺄﻟﺘﻚِ ﺏﺎﻠﻠﻫ - ﻳﺎ ﻥﻭﺭ ﻊﻴﻨﻳ -\nﺏﺩﻮﻨﻳ ﻫﻞ ﻒﻳ ﺍﻟﺤﻴﺎﺓِ ﺣﻴﺎﺓ ؟\nﺖﻋﺎﻠ"; The whole program is here : #include <iostream> int main() { wchar_t s[] =L"ﺳﺄﻟﺘﻚِ ﺏﺎﻠﻠﻫ - ﻳﺎ ﻥﻭﺭ ﻊﻴﻨﻳ -\nﺏﺩﻮﻨﻳ ﻫﻞ ﻒﻳ ﺍﻟﺤﻴﺎﺓِ ﺣﻴﺎﺓ ؟\nﺖﻋﺎﻠ"; for (auto ch : s) { std::cout << ch; } } The o...
65,977,688
74,210,081
ranges::views::group_by-like function applying predicate to consecutive elements?
In the following small example I was trying to group elements by the difference between consecutive elements being 1. As the output shows, however, group_by's predicate is evaluated between the current element and the first element of the group being processed. #include <iostream> #include <range/v3/view/group_by.hpp> ...
group_by has been deprecated in favor of chunk_by, which does exactly what you want: Given a source range and a binary predicate, return a range of ranges where each range contains contiguous elements from the source range such that the following condition holds: for each element in the range apart from the first, whe...
65,978,418
65,985,836
Error "The specified file was not found" when compiling c++ on notepad++
I'm trying to compile c++ on notepad++ using the nppexec plugin and somehow, i get the "The specified file was not found" error. This is the script i'm using npp_save cd "$(CURRENT_DIRECTORY)" g++ "$(FILE_NAME)" -o $(NAME_PART) -march=native -O3 NPP_RUN $(NAME_PART) I installed MinGW ver 0.602 and i double checked the ...
The source could be the file name. Check the file's name again for spaces, special characters, things like that, it might fix your problem
65,979,065
65,979,164
unable to assign value to a struct attribute. C++
I am trying to implement a linked list in C++. I have the following code class LinkedList { private: struct node { int data; node* next; }* head; node* mkNode(int data, node* next){ node* n; n->data = data; n->next = next; return n; } pu...
node* mkNode(int data, node* next) { node* n; n->data = data; n->next = next; return n; } pointer 'n' to 'node' is not initialized. Try to initialize it with struct node memory. node* n = new struct node;
65,979,405
65,979,981
Arduino/C++ An array of pointers with reference
I have an array: #define SELECT_KEY 1 char *menu_main[] = { "Individual", "OFF", "ON", "Initialise", "Scan", "Read"}; char *individ_sub_menu[] = { "item1", "Item2" }; char *inview_menu = &menu_main; int selectPos = 0; int getKeyPress() { //for purpose of this example retur...
Those two arrays have two different types: char *menu_main[] = { "Individual", "OFF", "ON", "Initialise", "Scan", "Read"}; char *individ_sub_menu[] = { "item1", "Item2" }; menu_main got type char *[6] and individ_sub_menu got type char *[2]. You can't pass both through same interface unless you erase that array type, ...
65,979,436
65,992,548
error use of undeclared identifier 'mainwindow' semantic issue in QtCreator
I just create new Qt Widgets Application. I open the mainwindow.cpp and it's like mainwindow.cpp doesnt see the "mainwindow.h" while i was on editor. But compiler works fine. How do i fix this semantic issues? I added 'QT += widgets' to .pro file. It doesnt work. These are actually default files. --mainwindow.h-- --ma...
I fixed this bug by unchecking Help/Plugins/C++/ClangCodeModel and restart QtCreator.
65,979,494
65,979,736
Nodejs addons error at GetReturnValue().Set()
void Method(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); const String::Utf8Value prefix(isolate, args[0]); const int difficulty = args[1].As<Number>()->Value(); const string solvedPow = solve(string(*prefix).c_str(), difficulty); cout << solvedPow << endl; ...
V8's String::NewFromUtf8 takes const char * as it's data parameter. In your case solvedPow appears to be std::string. These are incompatible types. You can get a const char * from std::string using c_str(): args.GetReturnValue().Set(String::NewFromUtf8(isolate, solvedPow.c_str()).ToLocalChecked());
65,979,582
65,979,639
Linker error: undefined reference to function from header file
I did try to find my specific issue, but the closest I found was this question where the issue was with global variables. I need make a lexer header file along with it's cpp file to use in main.cpp. here are the two lexer files: // lexer.hpp #ifndef LEXER_HPP #define LEXER_HPP // Some include files, not really relevant...
Do this TokenList interpreter::lex::tokenizeString(std::string tokStr) { /* Stuff*/ } or this namespace interpreter { namespace lex { TokenList tokenizeString(std::string tokStr) { /* Stuff*/ } } } Although you've said using namespace interpreter::lex; that doesn't mean that newly defined name...
65,979,902
65,984,974
How i can to generate landscape in UE4 without UI? (by code)
Good day. I have a problem with landscape generation not through UI. Can you tell me how I can do it? I tried to find information in the official manuals, to find a certain method, but I did not find anything and got confused. Is there such a method in UE4 to generate a landscape?
There is no runtime generation of Landscape capabilities in Unreal Engine 4 out of the Box. You must implement this feature yourself. There are multiple Plugins on the Marketplace that help you achieve this. One such example is linked below. Voxel Terrain Plugin
65,979,942
65,979,979
Simple c++ calculator -> error: request for member 'compare' in details.std
I've some experience with java but this is my first time tring to write some c++ code. I've started with a simple calculator but am getting the error "error: request for member 'compare' in details.std". It's probably an easy fix but if you could lend a hand it would be appreciated. #include <iostream> #include<string>...
details is string (std::basic_string<char>), so details[i] is char. char doesn't have members. It is one of integer types, so the comparision should be details[i] == ' ', not details[i].compare(" ") == 0.
65,980,361
65,980,506
C++ compiler throws error on dynamic array with default values
Mac g++ throws a compilation error with this code: #include <iostream> using namespace std; int main(int argc, char ** argv) { int * p = new int[5] {1,2,3}; return 0; } I tried an online compiler and it compiles and runs without errors. Is there something wrong with mac compiler? Can I do something to change...
There's no fundamental reason not to allow a more complicated initializer it's just that C++03 didn't have a grammar construct for it. In the next version of C++, you will be able to do something like this. int* p = new int[5] {0, 1, 2, 3, 4}; You can try adding -std=c++11 to your command line and that should be workin...
65,980,473
65,980,563
How can I simplify the codes without affect the output?
I am having my C++ classes and I have done the assignment which is second code at first but then it will appear weird output while default case like Invalid Vehicle Code RM6.95265e-308. Then I change it to the first code which is working well but too long. Any ideas to simplify it? #include <iostream> using namespace s...
The reason of weird output is during default case No value is assigned to vRate so the compiler assigns a garbage value so u ended up with some weird ouptut to over come this error assign the vRate = 0 while declaring so you will overcome this error. And there is a z in second code which is a typo. The corrected code i...
65,980,719
65,980,773
What is the difference between the following two code snippets?
DFS 1: bool dfs(int source, int color, int dist) { vis[source] = true; if (source == dist) return true; for (auto x : adj[source]) { int new_node = x.first; if (!vis[new_node]) { int new_color = x.second; if (new_color == color) return dfs(new...
The version with return dfs(new_node, new_color, dist); will always return from the function after that call, whether that returned value is true or false. However, the if (dfs(new_node, new_color, dist)) return true; will make the recursive call but only exit the for loop (by returning) if that call returns true. If i...
65,980,942
65,990,001
Count integers in an array where the set bits are a subset of a given mask
Given a mask and a value, the mask covers the value if all bits from the value fall into the mask. For example: mask: 0b011010 value: 0b010010 true or mask: 0b011010 value: 0b010110 false For int arr[arr_size], I need to calculate how many elements of the array are covered by the given mask. My code: int count = ...
AVX1 is useless for this, it only does floating point stuff and you have integers there. Here’s AVX2 port of your code. #include <immintrin.h> #include <assert.h> // Compute horizontal sum of all int32 lanes of the vector inline int horizontalSum( const __m256i v ) { // Add 8 scalars into 4, by extracting lower/hi...
65,981,409
65,981,764
Is comparing addresses of dynamically allocated objects allowed in C++20 constant expression?
C++20 allows heap allocation in constexpr functions as long as the memory does not leak. However GCC and Clang disagree on whether comparing the addresses of two dynamically allocated objects is a constant expression or not. The following snippet can be compiled with Clang but not gcc. constexpr bool foo() { int* a...
This is a gcc bug (#85428). There's nothing in [expr.const]/5 that would cause evaluation of a == b to fail to be a constant expression. The only one there in which there is any question would be the one about undefined behavior. So we could go look at [expr.eq] to see what that says about pointer comparison: If at le...
65,982,150
65,982,424
Correct way to delete a vector of pointers in C++
Given the next snipped: vector<cv::Mat> list; // Hold the pointer values (not the pointers) for (int index = 0; index < item_count; index++) { jobject bitmap = env->GetObjectArrayElement(listBitmaps, index); // BitmapUtils::toMat returns a cv::Mat* which has been created with "new cv::Mat()" cv::Mat* mat ...
"Is next the correct way to delete the vector object pointers?" No, it's not. If sources has type vector<cv::Mat *> you have to delete the pointers with for (auto entry : sources) { delete entry; } The vector vector<cv::Mat> list; has automatic storage duration. It will be automatically destroyed at the end of its...
65,982,943
65,983,286
How many elements can be inserted in an array of size 5?
If I declare an array in C/C++ like this int arr[5]; and then a loop to insert elements in it like this for(int i=0; i<5; i++){ arr[i] = i+1; } And when I print those elements like this for(int i=0; i<5; i++){ printf("%d ", arr[i]); } elements get printed as usual i.e 1 2 3 4 5 But if those loops are run one ...
Simply because C does not check array bounds. Reading and writing beyond array bounds is an undefined behavior in C, and it returns an exception in other languages (IndexOutOfBoundsException in Java, for example). In your case trying to read arr[i] will just display whatever value is stored in the next 4 bytes of memor...
65,982,984
66,053,804
Include nested class in C++ public header
I have a public header that has class X. X has a private member of nested type U::V. As I understand, normally, you just forward declare the types but I cant forward declare nested type. U::V is in a private header so I cannot #include them from a public header. What do I do to have X know of class U::V? Summary of my ...
I just realized this happens because I got an incomplete class definition, not because it's a nested class. Thanks, everyone.
65,983,504
65,983,637
Why can't putc() be implemented as a macro in C++? (Or can it?)
Reading en.cppreference.com on fputc()/putc(), I stumbled upon the following statement: In C, putc() may be implemented as a macro, which is disallowed in C++. Is this true? If so, where (in the C++ standard) is this stated? Possibly related: https://stackoverflow.com/questions/10712423
putc is specified as a function in the C standard: 7.19.7.8 The putc function The C standard permits any C standard library function to be implemented as a macro (a real function implementation still needs to be provided, but if a macro is defined in the header, that's what will be used): 7.1.4 Use of library functi...
65,983,541
65,983,710
Is there a way to "translate" types in C++?
Depending on the type of a variable I would like to call a templated function (which is given). The problem is, the expected types for the template won't fit directly. Example: If the type of my variable is int, then I would like to call the function foo<classA>(). If the type is double I would like to call foo<classB>...
My Question is: Is there a way to "translate" types? Of course. C++ has had this since forever. template <typename T> struct my_translator; template<> struct my_translator<int> { using type = classA; } And now you can write: typename my_translator<int>::type and get classA. This works with C++98 even, I think....
65,983,681
65,983,849
C++ vector of class objects and dynamic memory allocation
This is a simplified version of what I want to do, it crushes when push_back is called, specifically when the destructor is called. If I delete the body of the destructor it works, but I want to be sure that it is deleted. Instead of calloc/free I tried new/delete with the same result. What do I do wrong here? #include...
Here's a working code: https://godbolt.org/z/ex9oMG. #include <cstdlib> #include <vector> using namespace std; class Buffer { public: float *DATA; Buffer(int length) {DATA = (float*) calloc (length,sizeof(float));}; Buffer(const Buffer &buffer) = delete; Buffer(Buffer&& buffer) { DATA = buff...
65,983,827
65,983,992
C++ / SDL2 - Ball bouncing/glitching together
I was trying to write some ball bouncing program in C++ using SDL2. I had a hard time getting the velocity exchange correct, but it works pretty neat so far. The only problem I have right now is that the balls are sometimes glitching/stucking together and after some seconds they release themself again. That is my upda...
The proper fix The main problem is that you are letting the balls overlap each other, then update their velocities. However, if the next time step is shorter than the previous one, it can be that after updating their positions, they are still overlapping. Then you think they are colliding again, and update their veloci...
65,984,024
65,984,931
How Do I Enable Error Throwing In PlatformIO? (I'm getting g++ errors.)
I am trying to throw errors in my Arduino Ethernet code (if (error) throw error) and handle (really ignore: catch(Error error) {}) them. Sadly, I get errors like: src\main.cpp: In function 'void loop()': src\main.cpp:29:35: error: exception handling disabled, use -fexceptions to enable } catch (Error error) { ...
I suppose the AVR architecture (avr-g++). As you can see in its FAQ, it's not supported: Exceptions are not supported. Since exceptions are enabled by default in the C++ frontend, they explicitly need to be turned off using -fno-exceptions in the compiler options. Failing this, the linker will complain about an undefi...
65,985,501
65,985,935
How to convert const char* to uint16_t octal (C/C++)
I need to convert values with leading zero to octal. Because 12 (14 octal) is different from 012 (10 octal) The function I will call requires a variable of type uint16_t and the value to be converted is received dynamically and can be stored in a String or const char*. String node = "012"; // received dynamically const...
unsigned strToInt(const char *str, int base) { const char digits[] = "01234567890ABCDEF"; unsigned result = 0; while(*str) { result *= base; result += strchr(digits, *str++) - digits; } return result; }
65,985,773
65,985,848
What does std::geometric_distribution do for probability 0?
The geometric distribution is degenerate when given a probability parameter 0. C++ includes such a distribution. Does it define the behavior when the probability is 0? On my machine under gcc the following code outputs 9223372036854775808 (i.e. 1ULL << 63): #include <random> #include <iostream> int main() { std::m...
According to the Latest C++ Standard, geometric_distribution requires that p is greater than zero and less than 1. explicit geometric_distribution(double p); 2 Preconditions: 0 < p < 1. 3 Remarks: p corresponds to the parameter of the distribution. If you violate this precondition by passing 0 for p, you simply have ...
65,985,793
65,985,840
Why does an explicitly-defaulted constructor give a 'function definition not found' warning in VS2019?
I'm working on a C++17 project compiled in VS2019. I have a class where I want to use an explicitly-defaulted constructor: class UserCredentials { public: UserCredentials() = default; }; With the code above, Visual Studio is giving me a green squigly underline warning: Function definition for 'UserCredentials' no...
Intellisense uses a different compiler than the one used to compile code into an executable. The Intellisense compiler has a problem with your code. This may be a bug in Intellisense, or something about your code that it doesn't understand. Your code itself is fine.
65,985,819
65,985,978
How to create multiple caller functions by another function
I'm trying to create a function call stack like this, but so that it goes to caller_1_100: void callee(void) { // prints out final call stack } void caller_1_3(void) { callee(); } void caller_1_2(void) { caller_1_3(); } void caller_1_1(void) { caller_1_2(); } I know I could use a recursive function to do this, but...
You could use a function template with a specialization for your base case. For example: template <size_t I> void caller_1() { caller_1<I + 1>(); } template <> void caller_1<100>() { callee(); } Keep in mind that since templates are resolved at compile time any decent optimizing compiler will almost certainl...
65,985,930
65,986,018
Specify template argument by subclassing
When I inherit from a templated class and provide the argument during the inheritence, how do I have to handle functions from the parent class, which use the template argument? For example with this class as the parent: template<typename T> class Parent { public: virtual T someFunction(const T& data); }; and I try...
When you write Parent<char>, the compiler effectively generates a class definition as if you had substituted char into the template text. That is, behind the scenes it's as if the parent class of CharVersion is the following template instantiation: class Parent_char { public: virtual char someFunction(const char& d...
65,986,265
65,986,337
Mbed wrong long int parsing
#include <stdio.h> int main() { const char* s = "Number: 420604953084"; long number; sscanf(s, "Number: %ld", &number); printf("Result: %ld", number); return 0; } This code, compiled on desktop with c++11 (or, for example here) returns correctly: Result: 420604...
If your the long type is 4 Bytes on your compiler. I think it's reasonable to get and error. Please try unsigned long long and the format code "lld".
65,986,508
65,986,857
Is it possible to streamline a given set of operators to any arbitrary set of classes?
Consider the following set of classes and the relationship of their operators: We can implement them in two distinct ways. The first where the operators are defined within the class, and the latter where they are defined outside of the class... template<typename T> struct A { T value; T& operator+(const A<T>& ...
What about using CRTP inheritance? #include <iostream> template <typename T> struct base_op { auto operator+ (T const & o) const { return static_cast<T&>(*this).value + o.value; } }; template<typename T> struct A : public base_op<A<T>> { T value; }; template<typename T> struct B : public base_op<B<T>> { ...
65,986,906
65,986,933
C++ const char* with string literal in method call
If I have a C++ function that takes a string parameter: void somefunc(const std::string &s) { std::cout << ": " << s << std::endl; } If I then have something like: const char *s = "This is a test..."; somefunc(s + "test"); I get an error: error: invalid operands of types ‘const char*’ and ‘const char [5]’ to binary...
Pointers (const char*) can't be added by operator+. You can make either operand to std::string, to concatenate strings. somefunc(std::string(s) + "test"); somefunc(s + std::string("test")); Or use std::string literal. using namespace std::string_literals; somefun(s + "test"s); // ^^^^^^^ <- std::string, not ...
65,987,410
65,987,670
why the function cleanup_str must be qualified with 'static' key word?
I am new programmer of c++. I have encountered a proble and I cannot understand this. Could you please help me figure out it? This is an example of the book,<c++ primer>. class TextQuery { public: using line_no = std::vector<std::string>::size_type; TextQuery(std::ifstream &); QueryResult query(const std::s...
const method has a contract - it does not change internal state of an instance of the class. Technically it is implemented the way that hidden parameter this has type const TextQuery * - pointer to constant (non modifiable) object of TextQuery. To follow that contract you cannot call non constant method, it may modify ...
65,987,453
65,987,511
Creating dynamic 2D array c++
From what I know, declaring a dynamic array is: int *array = new int[x]; My question is, how can I declare a dynamic 2D array? For example: int *array = new int[constant][dynamic]; And from what I found out is the number of rows can't be dynamic. Are there any ways to do it?
One easy technique that I use in these kind of situations is that I create a struct for storing the 1D array, and create an array of those 1D arrays. struct BaseArray { BaseArray() = default; BaseArray(int count) : pArray(new int[count]) {} ~BaseArray() { delete[] pArray; } int* pArray = nullptr; }; i...
65,987,989
65,988,162
How to pass a variadic template function?
I have a function defined like this: template<int... rests> static std::enable_if_t<sizeof...(rests) == 0, void> getter(pokers_rep& rep, poker_index& out) { } template<int index, int... rests> static void getter(pokers_rep& rep, poker_index& out) { out |= rep.indices<index>(); getter<rests...>(rep, out); } and...
I don't know how you would be able to do it exactly like this, but given that getter looks like a free function (although apparently a static one), you could move it into a struct: struct SpecificGetImplementation { template <typename Arguments> static void getter(Arguments); // beware that static means something...
65,988,004
65,988,238
how exactly input and output file streams work in c++
I came across the following observation while working with input and output file streams and I am confused. Can anyone tell me why this happens: I saved a txt file on my desktop by the name hello which contains the following text: Hello my name is xyz Next, I ran the following code: #include <iostream> #includ...
If you want to know how streams work in C++ then you need a reference work (and maybe a tutorial as well), obviously its much more complicated than can be explained here. The reason for what you found is the rule that if you switch from reading to writing (or vice versa) you must execute a positioning or flushing opera...
65,988,197
65,988,378
How to create a proper vector of substruct instances?
I'm trying to make a very basic tokenizer/lexer. To do this, I'm making a main struct called Token that all types of tokens will inherit from, such as IntToken and PlusToken. Every new type of token will include a type variable as a string, and a to_string function, which returns a representation like: Token(PLUS) or T...
You are giving your derived classes their own type member variables. Instead you should be setting the type that belongs to the base class inside the derived-class constructors.
65,988,304
65,988,705
When will the actual v-table be accessed?
Background I know how the compiler generates the virtual address table (v-table). So to make things simple for me to explain, lets take this simple example, class Entity { public: Entity() {} virtual void Initialize() {} }; class Player : public Entity { public: Player() {} virtual void Initialize()...
Compilers are free to do whatever they want. They can implement everything without vtables, so take all the below with a grain of salt. Player player = {}; player.Initialize(); When you define an object with class type, the compiler knows that the static type is equal to the dynamic type. So it is likely to call the r...
65,988,547
66,003,778
Which DLL exports the NtGdiBeginGdiRendering function and how?
I am trying to locate the NtGdiBeginGdiRendering function in Windows. Which DLL exports this function? Which mechanism adds the NtGdi prefix and to what purpose? What is the difference between calling NtGdiBeginGdiRendering and BeginGdiRendering (difference in functionality and in calling convention and used modules to...
With help from RoQuOTriX, I discovered that this function is exported from gdi32.dll. What was confusing is that gdi32.dll doesn't use the NtGdi prefix. It just exports it as BeginGdiRendering.
65,988,708
65,988,798
I need to print this cout statement at the end "This is not an option" and return back to the beginning to bring up the menu
#include<iostream> #include<fstream> #include<iomanip> #include<cstdlib> #include<ctime> using namespace std; int main() { // Variable declarations unsigned seed = time(0); srand(seed); int answer = 0; int number1 = rand() % 500 + 1; int number2 = rand() % 500 + 1; int useranswer = 0; int option; cout << " ...
add a while or do-while loop. like this. while (true) { cout << " Math Tutor Menu" << endl; cout << "------------------------------" << endl; ... ... else{ cout << "That is not a choice." <<endl; } } If I were you I would have used switch-case instead of if-else.
65,988,904
65,989,085
How to measure execution time of thread in macos?
Is there any way to measure execution time of thread under macos? I know that there is getrusage function, but it is supposed only to measure process time (Under linux there is extension to measure thread time, but unfortunately I work under MacOs). I need to measure time of thread (the sum of processed time in user an...
You can pass RUSAGE_THREAD for the first parameter to getrusage. Edit: Looks like Mac supports only RUSAGE_SELF and RUSAGE_CHILDREN. CLOCK_THREAD_CPUTIME_ID is another option, which tracks CPU time for a calling thread. Note that this is CPU time and not wall clock time, i.e for example any time spent sleeping won't be...
65,989,283
65,991,900
Create a single mask to check if bits are set, unset or accept either
Given a value, I want to check if some of its bits are set and some of them unset at the same time, while I don't care about the value of others. I can do this with two bit masks, one for set bits one for unset bits like so: #include <iostream> bool checkMask(uint8_t value, uint8_t setmask, uint8_t unsetmask) { re...
Some mostly generic possibilities based off of @KamilCuk comment #include <iostream> #include <utility> #include <array> #include <bitset> #include <string> constexpr uint8_t BYTE_BITS = 8; template <typename D> class BitMask { public: constexpr BitMask(const D setmask, const D unsetmask) : m_setmask...
65,989,436
65,989,671
Where can I find the GCC 9 implementation of std::chrono::system_clock::now()?
The chrono system header (/usr/include/c++/9/chrono) declares, but does not define, the static now() functions of its clocks. I also do not see an include that looks relevant. Where are these functions implemented?
Where are these functions implemented? In your C++ standard library implementation. GNU compiler is shipped with GNU C++ library - libstdc++. Inside gcc source tree, you may find libstdc++-v3/chrono.cc file with the implementation of chrono::now() function.
65,989,969
71,338,252
UE4 AddDynamic macro doesn't work on 4.26
I am stuck with this error: C:\Users\Konrad\Documents\Unreal Projects\ClassicArcade\Source\ClassicArcade\Floor.cpp(22) : error C2664: "void TSparseDynamicDelegate<FComponentBeginOverlapSignature_MCSignature,UPrimitiveComponent,FComponentBeginOverlapSignatureInfoGetter>::__Internal_AddDynamic(UserClass ,void (__cdecl A...
Header: UFUNCTION() void OnOverlap(class UPrimitiveComponent* Comp, class AActor* OtherActor, class UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult); Implementation: void AFloor::OnOverlap(UPrimitiveComponent*, class AActor* OtherActor, UPrimitiveComponent*,...
65,990,306
65,990,839
Why is initialization of variable with constexpr evaluated at runtime instead of at compile time
As my understanding, the keyword constexpr is telling the compiler that the evaluation of expression can happen at compile time. Specifically, constexpr on a variable means that the value of the variable can be evaluated at compile time, whereas constexpr on a function means that this function may be invoked and evalua...
By inspecting the generated assembly, we can confirm that in both cases G++ 7.5 computed the fib(32) value at compile time: movl $2178309, %esi The reason G++ evaluates constexpr context so fast is due to memoization which it performs when evaluating constexpr and template contexts. Memoization completely kills...
65,990,338
66,004,507
Starting a Tomcat 8.5 localhost through C++? What is the best practice?
I am attempting to create a small C++ Visual Studio Forms (via CPPCLR_WinformsProjekt) application that is essentially a browser but it also starts a local Tomcat 8.5 server with a WAR file in its web apps folder and redirects you to the localhost page. I am working on Windows. My question precisely is - what is the be...
[I am assuming you are under Windows, but on Unix-es similar ways are available.] In a C++ program you can execute all commands that a shell can, so the easiest way to start Tomcat would be to use CreateProcess to execute catalina.bat (or startup.bat). The is also the most easily configurable way: a user can adapt sete...
65,990,346
65,990,407
C++ force compiler error if template resolution fails
Based on this question I have the following templated method: ... template <typename T> const T& get() const { if constexpr ( std::is_same_v<T, C1> ) return this->c1; else if constexpr( std::is_same_v<T, C2> ) return this->c2; else throw std::logic_error("Tried to lookup from invalid ty...
You can add static_assert as template<class T> struct dependent_false : std::false_type {}; template <typename T> const T& get() const { if constexpr ( std::is_same_v<T, C1> ) return this->c1; else if constexpr( std::is_same_v<T, C2> ) return this->c2; else static_assert(dependent_fals...
65,990,389
65,991,497
Reading from text file error : Segmentation fault (core dumped)
I have a (10*5) matrix and two variable values typed in a text file. Matrix elements are tab separated. For example: I want to read the matrix and two other variable values from the text file and printout. I have to use valarray for matrix. I tried in following way, but it shows "Segmentation fault (core dumped)". Any ...
Change matrix table{std::valarray<double>{0.0, 10}, 10}; into matrix table(std::valarray<double>(0.0, 10), 10); to get the correct constructor. You now get one of the other constructors (possibly the initializer_list or indirect_array ctor I think).
65,991,229
65,991,340
Why are vectors' size static and we still can add more values?
I'm a complete beginner to C++ but I have some basics knowledge in programming (Python mainly) and I'm trying to learn C++. As the question implies, vectors have static sizes (at least what I've read in my learning material) but we still can add more values to what the size authorize. I wrote a simple code to know what...
What is fixed is sizeof( vector<int> ) A vector can contain varying number of elements, but that elements are stored on the heap, hence do not contribute to the vectors sizeof. The number of elements is v.size() (and that can change). You create a vector with 10 elements: vector<int> v(10); But then you attempt to a...
65,991,264
65,992,656
C++ coroutines: Is it valid to call `handle.destroy` from the final suspend point?
Is it valid to call handle.destroy() from within the final suspension of a C++ coroutine? From my understanding, this should be fine because the coroutine is currently suspended and it won't be resumed again. Still, AddressSanitizer reports a heap-use-after-free for the following code snippet: #include <experimental/co...
It's perfectly valid if you're 100% sure nobody will use the coroutine promise afterwards. calling coroutine_handle::destroy is equivalent to calling the coroutine promise destructor. If this is the case, then why to do it like this to begin with? just return std::suspend_never from final_suspend std::suspend_never fin...
65,991,424
65,991,682
Which conditional statement is faster than the other (width*height*depth == 0) OR (width ==0 || height == 0 || depth == 0)
When describing 3-dimensional objects in an algorithm where computation speed is important, which of the following conditional expressions is faster? class Box { unsigned int width, height, depth; public: bool isNull(){ return (width*height*depth == 0); //OR return (width ==0 || height =...
It depends on your compiler, you can check compiled assembly for both of them and compare. You can as well time 2 options. Second one looks much better though. Note that if any of the values will be non-zero, rest will short circuit and will not be executed. Be sure to put the one that has the highest probability of be...
65,991,571
65,991,610
Can C++ pass empty pointer to a function?
For example, I want to declare pointer to array and to don't wanna initialize it. Then, I want pass it to a function and initialize it exactly in function. How can I do it in C++? void F(int *B, const int& N) { B = new int[N]; for (int i = 0; i < N; ++i) B[i] = i; } int main() { int N = 4; int *B = nu...
The pointer you pass is a copy of the original pointer. When you modify B in F, B i main() remains the same. You need to pass the pointer by reference or pass a pointer to the pointer: void F(int*& B, const int& N) { B = new int[N]; for (int i = 0; i < N; ++i) B[i] = i; } int main() { int N = 4; int *...
65,991,580
65,991,965
How to get output in other spoken languages other than English?
I want to make an calculator in a spoken language another than English e.g. Hindi. I tried to make one using '''cout''' function but it gave me unexpected errors. Please Tell what should I do Code Sample cout<<name<<", "<<"कृपया ऑपरेटर दर्ज करें--> "; cin>>op; switch (op) { case '+': cout<<name<<", "<<"कृपया प...
For Display output in Hindi or any none language, we Firstly need to set UTF encoding to output encoding #include <string> #include <iostream> #include <Windows.h> int main() { std::string test = u8"Greek: αβγδ; German: Übergrößenträger"; SetConsoleOutputCP(65001); std::cout << test; }
65,992,083
65,993,458
Template specialization depending on a unknown typedef
In C++ I want to specialize a templated function. So far so good. The problem is that the type that specialize my template depends on a typedef to which I don't have access. Purpose explication The user must first define a typedef for the class Surface_mesh by specifying some types in the template. typedef CGAL::Surfac...
In CGAL Face_index is - except for the case when the documentation is created - just a typedef for SM_Face_idex (typedef SM_Face_index Face_index;) and the same for all surface meshes. So theoretically you could just do: template <typename T> std::string foo(void) { return "Default foo() called"; } template <> std...
65,993,407
65,993,481
Syntax error for template struct instantiation inside assert statement
For the following template struct defined in a header: #include <unordered_set> namespace Utilities::ContainerHelpers { template <template <class> class TContainer, class TVal> struct is_unique { bool operator()(TContainer<TVal> const& container) const { std::unordered_set<TVal,...
assert, as every macro, does not understand C++, it treats every comma , as arguments separator: assert(is_unique< std::vector, TelemDetail >{}(session_details)); // ( first arg , second arg ) // But preprocessor macro "understands" () - so just add...
65,993,529
65,993,577
OpenMP returning wrong result
The code below should use 4 threads to calculate the summation of all numbers between 0 and 1000. It should return 499500 but it is returning different values at each execution. #include <omp.h> #include <iostream> using namespace std; int main (int argc, char *argv[]) { int nthreads, i, tid; float to...
What is happening in your code is that you have multiple threads concurrently modifying the value of the variable total. To solve this issue, you can use OpenMP reduction clause, which from the OpenMP standard one can read: The reduction clause can be used to perform some forms of recurrence calculations (...) in para...
65,993,679
65,994,546
c++ make failing on forward declaration - running in docker
I'm compiling the following library using docker: https://github.com/hot-stuff/libhotstuff using the following script: FROM alpine:latest RUN apk update RUN apk add --no-cache git gcc g++ make cmake libuv-dev openssl-dev gmp-dev libsodium-dev autoconf RUN git clone https://github.com/hot-stuff/libhotstuff.git && cd lib...
c++ make failing on forward declaration - running in docker The linked source file util.h does not #include <sys/time.h> which is needed for struct timeval. Indeed, the identifier has incomplete type. Technically C source includes would be better to incalude inside extern "C", so do at line 28: #ifdef __cplusplus ...
65,993,690
65,995,607
Accepted using Vectors but Rejected using Arrays in HELP BOB problem on CODECHEF C++
reference problem https://www.codechef.com/problems/HBOB02 here in this problem i solved it using below code but firstly i used arrays instead of vector but there i got wrong answer. why so ???? #include <bits/stdc++.h> #define mod 1000000007 using namespace std; int main() { ios_base::sync_with_stdio(false); ...
Variable-length arrays are not part of the C++ standard, but some compilers provide them as an extension. If they get too large, the program breaks. However, you don't even need to store all those numbers. Since you're apparently into "competitive" programming, here is a solution that uses only a tiny fraction of your ...
65,993,940
65,994,241
error: no matching function for call to 'std::vector<float>::push_back(std::vector<float>&) const'
I am trying to copy map (m) values into a vector (v) The map is declared this way: const map<int, vector<float> >& m = ....; I tried this: const vector<float>& v; for(auto elem : m) v.push_back(elem.second); I get this error: error: no matching function for call to 'std::vector::push_back(std::vector&) const'
The purpose of what you are doing is a little unclear but if you'd like to make a vector<float> to hold all the values in all the vectors in the map, you could do that, but you can't push_back a vector<float> directly, which is one of the reasons why you get the error: error: no matching function for call to 'std::vect...
65,993,982
65,996,879
Is it valid to set a member variable of Singleton Class directly?
I wonder the following code is valid, or not. In main function, the 'testValue' of the member on 'testClass' will be set. If printed by calling 'showTestValue()' method, the variable must be updated? Or the variable may be not updated in some cases ? #include <stdio.h> #include <stdlib.h> class testClass { public: ...
A Singleton can be defined as: Singleton is a creational design pattern that lets you ensure that a class has only one instance, while providing a global access point to this instance. Refactoring Guru It defines instantiation of the class, not the usage. So, technically it's ok to access and modify values. That does...
65,994,262
65,994,335
Extracting Columns From a Vector Matrix to store in an Array
Problem Explanation Edit: Solution is added to the bottom in case anyone needs it Let's Say I have a matrix with following data 1 3 2 1 7 9 5 8 9 1 3 8 6 9 4 1 3 2 4 0 4 5 7 4 3 5 6 4 6 5 7 4 I want to define a size_of_chunks variable that will store the number of chunks for example if I set size_of_chunks=2 then th...
Don't specify a size for the vector in the constructor and use push_back, because that way you end up with a vector twice as big as it should be. Do one or the other. In this case presumably it should be std::vector<int> temp; That is, start the vector at size zero and increase it's size using push_back.
65,994,361
65,994,402
There is no output, What is the wrong with my code?
I am trying to store the reverse of a text stored in (x) in another variable (y), but there is no output! #include <iostream> #include <string> using namespace std; int main() { int i=0, j=0; string x,y; cin>> x; for (char c: x) i++; for (int j=0; j<i; j=j+1) y[j]=x[i-j-1]; cout <<y; re...
What do you think the size of y is? You never change it's size, so the size stays at zero and this code y[j]=x[i-j-1]; is an error because you cannot use [] on a string that has size zero. Using [] on a string never changes it's size, and it's an error to use [] with an index that doesn't exist for the string. Try thi...
65,994,512
65,994,576
What does C++ if-Statement with double parantheses do?
I have stumbled upon an if statement where the condition is actually an assignment and I don't really understand what it does. Now, I found a similar Question with extensive answers but I still don't quite understand, what my snippet does: if ((x = !x)) /* some code */ The similar question I found is this one: htt...
It does the same thing as if(x = !x) does. However, because it is very easy to accidentally use = in place of ==, compilers will warn you when you're using an assignment inside of an if statement. That warning doesn't get displayed if the assignment expression is inside of a second set of parenthesis. So that's the poi...
65,994,857
65,995,005
Is there a built in way to do non floating point decimal operations in c++?
I think the title describes what I want well enough, but is there a way to do arithmetic on numbers with decimals without using floats?
Is there a built in way to do non floating point decimal operations in c++? No, there are no fixed point arithmetic types built in C++. Only built in arithmetic types are integers, and floating point. There are no classes for representing fixed point types in the standard library either.
65,994,915
65,995,801
send pcl point cloud over tcp in c++
I am new to data serialization in c++, I searched for examples but I was not really successful. My goal is to be able to send and receive a pcl point cloud over tcp in c++. I am familiar with ROS, but now I cannot use it in the server. I have to send point cloud through ethernet to a client machine, where I am free to ...
C++ does not provide a standard method to serialize and deserialize data. You can implement this yourself for simple cases. For more complex cases you can use a library, such as protocol buffers or Boost serialization. You can also use a text-based format "on the wire", such as XML or JSON.
65,994,964
65,995,050
how can i declare a Class in C++
I want do declare the class Person before the main method but it gives me an error that the class Person is undefined The main method is making the Object Person but I don't know how I can declare it like I do with methods. //main Function int main() { Person person = Person("Majd", 18, 177); //Error "Person class ...
If you delcare the class above main: class Person; then you will be able to do Person * person = 0; or Person * person = some_other_person; but without being told that there are constructors to link against it will not be possible to actually create a person here, or use one. You could just move the entire class defini...
65,995,066
65,995,170
Wrong use of pointers to index elements
I want to iterate through an array of length 3 and input then output all of the items, which are integers. I have two codes, the first of which works without any issues while the second one fails. Kindly tell what is the problem: CODE 1: #include<iostream> using namespace std; int main(){ int arr[3]; for(int& elemen...
Can you spot the difference? // works cin >> element cout << element // doesn't work cin >> &arr[0] cout << arr[0] The unary operator & is the addressof operator. When you apply the addressof operator on the element of the array, you get a pointer to the element. When you pass that pointer to the stream extraction...
65,995,125
65,995,244
CardDeck constructor
Im trying to make a class CardDeck with the constructor vector<Card> CardDeck My Card class looks like this Card.h file: enum Suit{clubs = 0, diamonds, hearts, spades}; enum Rank{two = 2, three, four, five, six, seven, eight, nine, ten, jack, queen, king, ace}; class Card{ private: Suit s; Ran...
Since your using an enum you can use integers to get it done, for (int i = 0; i < 4; i++) // Suit for(int j = 2; j < 15; j++) // Rank cards.push_back(Card{static_cast<Suit>(i), static_cast<Rank>(j)}); If you don't know how enums work, they are just like const integers. They just have a name which mak...
65,995,134
65,997,564
Reading multiple files with QFile
I want to read multiple files. I get en error in QFile because it reads only one file at once. How can I solve this problem? And how can I iterate my files and use them. QStringList fileNames; fileNames = QFileDialog::getOpenFileNames(this, tr("choose"), "up.sakla", tr("choosen(*.up)")); if (fileNames.isEmpty(...
I understand that you have some files within a folder and you would like to read a list of files (the ones that you selected through the QFileDialog) Here is the complete code: #include <QApplication> #include <QFileDialog> #include <QDebug> int main(int argc, char *argv[]) { QApplication app(argc, argv); ...
65,995,145
66,031,801
C++ effective approach to container for one-time lookup but multiple traverses and accesses
When building the array/vector from elements in my problem, I need to check if they are not already inserted, i.e., not allow duplicates. Instead of using array/vector I can use set/map/unordered_map. However, I want to maintain the insertion order which makes set/map unusable and after I fill this container with data,...
Does this make any sense or is there a more convenient and effective way? That generally made a lot of sense, and will scale optimally, though for the problem as described you'd only need an unordered_set to track already-inserted elements, rather than an unordered_map with some arbitrary/irrelevant values (e.g. true...
65,995,259
66,004,779
Understanding an odd looking C++ for loop?
I have just encountered some code and I'm not sure why it is done that way. Note that this is quite old code, so for (auto i : x) is not an option. The code is: INT_PTR i,c; for(i=0,c=m_array.GetSize();i<c;i++) { // Do stuff, i & c are not changed inside the loop } Where as I would have done (well I would have used ...
Once upon a time in some compilers long forgotten the first way was the only way in C. In older dialects, including original ones , functions would be defined like this: int foo(a, p) int a; char *p; { } and declared like this: int foo(int , char ) ; int foo2(); // unknown arguments int foo3(void); // no arguments...
65,995,339
65,995,613
Can I re-use a complex class like std::vector after std::move?
I'm creating a game, and trying to learn move semantics/r-value references. I have a class that adds an Event into a vector every frame. After 60 frames, I want to move all the accumulated events into a new class (called Step), which will be stored in another vector. I want this process to repeat, so after the Event ve...
Your code always copy the Events vector, so Events = std::vector(); will simply erase the copied-from elements. Why does it copy and not a move? Let's take a look at the Step constructor: // that's a copy -----v Step(std::vector<Event>&& InEvents) : Events {InEvents} {} Indeed, the expression (...
65,995,909
65,996,071
Defined constant for max sequential integer that can be stored in a float?
Is there a defined constant in the C++ standard, for largest sequential integer that can be stored in a float without approximation? (and also double, and long double?) Is this directly related to the number of mantissa bits/significand bits? If so, would the max sequential integer be exactly (1 << mantissaBitCount) - ...
Is there a defined constant in the C++ standard, for the mantissa bit count for float, double, and long double? Yes. They are in the std::numeric_limits template. There are also macros for these inherited from the C standard library. Is [max sequential integer] directly related to the number of mantissa bits/signifi...
65,996,205
66,007,103
Variable initialized in a for-loop contains a value, won't increment
I am working on a function for an STM32 Micro-controller that sends a string of a given length through a uart port. To handle uart communication, I have created a Serial class that has a transmission and receive buffer that are popped and transmitted in an interrupt handler. The function I am currently working on is ac...
It sounds like the compiler has optimized away your loop control variables. If you have a high level of optimization enabled then the loop could be unrolled or if you are calling the function from the same file where it is defined then it could be inlined allowing to eliminate the loop control variables. You haven't ac...
65,996,643
65,997,077
deleted function 'virtual Classname::~Classname()' overriding non-deleted function VIRTUAL DESTRUCTOR
I am trying to find the problem in this code, it does not compile in C++14. The original problem was to make this compile 'without editing Object or modifying drawObject()'s prototype': #include <iostream> class Object { virtual ~Object() {} }; class Line : public Object { public: virtual void draw() {std::co...
A private destructor means a class cannot be a base class. A base class destructor is implicitly used by both constructors (in case initialization throws exceptions) and destructor of a deriving class. So there is absolutely no way for you to derive Line from Object. Best you can do is make Line unrelated to Object cla...
65,996,779
65,996,989
Storing arguments and function and using them in another function
Welcome, this is very rare use-case question. So, here is what I'm trying to do - lets say I have a variadic template function which takes T ...args and a function type FuncT funcName, so here is what we have so far: template<typename FuncT, typename ...T> void myFunction(FuncT (*funcName), T ...args); Now, I want to ...
Use std::apply. It is new in c++17. If you cannot, write your own. In c++14, make an index sequence the same length as your tuple. Then func(std::get<Is>(std::forward<Tup>(tup))...). In c++11 do the same thing but write your own index sequence.
65,996,896
65,997,606
Why does this quicksort appear to be faster than std::sort?
Why does it appear that this quicksort algorithm is faster than std::sort? I've checked to make sure it's actually sorting the array. I've also replaced both sorting calls with hollow for loops of the same number of iterations to test the timing benchmark and everything checked out there. I'm also wondering what adjust...
Visual Studio's std::sort has some overhead and some optimizations that your program does not. Your program is based on Lomuto partition scheme, while std::sort is a single pivot, 3 partition Hoare like quicksort + insertion sort for small partitions. The 3 partitions are elements < pivot, elements == pivot, elements >...