question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
68,380,558
68,380,734
How to determine the time complexity of the nested loop?
I know that first loop is of O(n) and since second is nested loop it is going to be O(n * something). I know that nested loop will be iterating n time and decrementing each time. But how to decide it's time complexity? int a = 0; for (i = 0; i < N; i++) { for (j = N; j > i; j--) { a = a + i + j; } }
technically the time complexity of that algorithm, or number of instructions run, is going to be in the order of: Sum(N-i) for i=0 to i=N since the inner loop is run N times each time running just. each iteration running 1 count less. that sum expanded looks like this: N + N - 1 + N - 2 + .... 2, 1, 0 which is the ...
68,380,603
68,381,479
Closed connection but `asio::ip::tcp::socket::write_some` returns Success first call
Consider the following code (Boost 1.76 / Asio 1.18.2): #include <chrono> #include <iostream> #include <thread> #include <boost/asio.hpp> namespace asio = boost::asio; int main() { boost::system::error_code ec; asio::io_service ios; asio::ip::tcp::endpoint ep; asio::ip::tcp::acceptor acc(ios); acc.open(ep...
TCP will detect the error eventually, when write_some returns the data has been accepted into the OS TCP stack it doesn't wait until the data has been delivered and acknowledged. When the OS detects an error (e.g. a connection reset, or a timeout waiting for an ACK) it has no way to communicate that error back through ...
68,380,704
68,382,879
boost::interprocess how to implement a simple thread safe job queue for worker processes
I'm attempting to create a basic system for taking jobs from a queue between processes with boost interprocess communications on Windows. When a worker process is free, it will take a job from the shared queue area. The code is loosely copied from examples in the documentation. I have a child process that attempts to t...
The internal data of the shared Jobs must be pointer-free to work with multiple processes. But it is not because it contains std::queue . The pointers inside will not work across multiple processes.
68,380,800
68,380,878
When I should add the word "class" creating pointer in C++?
In what cases it could be invalid to write Type *p = nullptr; whereas only class Type *p = nullptr; is satisfying?
You need it when the type Type is shadowed by the name of a variable: class Type{}; int main() { int Type = 42; //Type * p = nullptr; // error: 'p' was not declared in this scope class Type* p = nullptr; } However, as pointed out by Ayxan Haqverdili, ::Type* p = nullptr; works as well and has the added b...
68,381,529
68,399,152
Bug in gcc wstring_convert?
I use MinGW 8.1.0 64-bit. This code snippet: #include <clocale> #if __has_include(<codecvt>) #include <codecvt> #endif #include <cstdlib> #include <locale> #include <string> #include <wchar.h> #include <iostream> int main() { auto utf8_decode = [](const std::string &str) -> std::wstring { std::wstring_conver...
Looks like this is indeed a bug in MinGW libstdc++.dll; codecvt incorrectly chooses big endian so = (0x3d) becomes 㴀 (0x3d00). Proposed workaround - manually force little-endian by using codecvt_utf8<wchar_t, 0x10ffff, std::little_endian>
68,381,652
68,383,042
How can I handle the enum so that it cannot be seen from Main.cpp?
This is my main file: #include "MyHeader.h" int main(void) { MyClass Test1; Test1.set_a_thing(); return 0; } This is the Header file: #ifndef MY_CLASS_H_ #define MY_CLASS_H_ class MyClass { public: MyClass(); ~MyClass(); enum A_few_Things { yes, no, sometimes, dont_know }; enum MyClass:...
Thanks to all of you and especially to @Eljay You put me on the right path. The enum MyClass::A_few_Things set_a_thing(); doesn't need to return anything. Inside the function, a_few_things is set. #ifndef MY_CLASS_H_ #define MY_CLASS_H_ class MyClass { public: MyClass(); ~MyClass(); void set_a_thing(); ...
68,381,698
68,383,632
Auto-dependency generation in Makefile: undefined reference to `main' (mixing conda channels)
I would like to add dependencies to a Makefile of mine such that every time a header is modified the correspondent translation unit is recompiled. Currently only changes to source files are considered. I followed this example quite closely. Below you can find a MWE, which outputs undefined reference to `main'. As soon ...
I do this: ifneq (,$(wildcard ${DEPDIR}/*} include ${DEPDIR}/* endif And compile with: DEPFLAGS = -MT $@ -MMD -MP -MF ${DEPDIR}/$*.Td I think your approach is going to have problems. I don't know what happens on a clean compile, but your DEPFILES won't exist yet.
68,381,712
68,381,863
How does QList<QString>, QList<QByteArray> in Qt6 retrieve data?
I have used Qt 5.15 for some months to do some basic stuff. In Qt5, it's known that QList, and QVector are 2 different containers: QList will store its raw data continuously in memory (as long as the size of each element is <= sizeof(void*)); otherwise, it will store a continuous chunk of pointers pointing to the actu...
QByteArray and QString themselves won't contain any data, just a pointer to a dynamically allocated array (try running sizeof(QByteArray) and sizeof(QString), you'll get a small constant size for both). All instances of a the same class in C++ have the same size so in an array of objects accessing an index is just a ca...
68,382,269
68,382,387
How to rewrite an register in binary file only if different?
I need write a byte in binary file, but only if this is diferent (something looked like EEPROM.update(a) from Arduino IDE). I think there is some function that does this, but now I can't find it/I'm not sure that exists. So far I have do this: FILE *fp = fopen("file.dat", "r+"); fseek(fp, (long) address, SEEK_SET); fre...
The fread advances the file pointer, so your fwrite doesn't overwrite the byte at offset address, but rather the following byte. You need to fseek back to offset address again before writing. Also there is a v in your sample code which isn't defined. Probably it should be &val or something like that.
68,382,518
68,382,681
Why does coroutine_handle's operator bool return true after destruction?
I am new to C++20 coroutines and surprised to know that coroutine_handle::operator bool returns true after destruction? Sample program: #include <coroutine> #include <iostream> struct ReturnObject { struct promise_type { void return_void() {} ReturnObject get_return_object() { return {}; } std::suspend_n...
Because coroutine handle fundamentally just holds an address. You can almost think of it as a "coroutine view", it doesn't own the coroutine. destroy exists if the coroutine wouldn't exit normally via standard control flow e.g. generators. operator bool for a std::coroutine_handle is defined as being equivalent to retu...
68,383,021
68,383,637
Adding a new instance of an array to a vector
This is a continuation of my previous question: Nested vector<float> and reference manipulation. I got the loops and all working, but I'm trying to add new instances of arrays to a total vector. Here's one example of what I mean: array<float, 3> monster1 = { 10.5, 8.5, 1.0 }; // ... vector<array<float, 3>*> pinkys = { ...
As mentioned in a comment you cannot insert elements to a container you are iterating with a range based for loop. That is because the range based for loop stops when it reaches pinkys.end() but that iterator gets invalidated once you call pinkys.push_back(). It is not clear why you are iterating pinkys in the first pl...
68,383,796
68,390,286
pybind11 interpreter use bundled python executable
I am using the pybind11 interpreter within a c++ application. I don't build with CMake but qmake due to legacy reasons, unfortunately. Hence, I am struggling to understand how to properly setup the pybind11 interpreter. The c++ application will ship with a bundled python 3.7 (so on Mac the app bundle will ship with the...
I have to set PYTHONHOME to MyApp.app/Contents/Frameworks/Python.framework/Versions/3.7 and PYTHONPATH to MyApp.app/Contents/Frameworks/Python.framework/Versions/3.7/lib/python3.7 In Qt I do that by calling qputenv before py::scoped_interpreter guard{};
68,384,017
68,454,982
Debugging GPU operation
I have a profile on VTune and it shows something running on the GPU (the line highlighted with the pale blue dot in the attached screenshot). How can I debug what in my codebase is running on there? To clarify: when that highlighted line is expanded, it's the nvoglv64.dll process eating up all that time, which is the ...
nvoglv64. dll is a file that is associated with the Nvidia based video card drivers which is the software driver for NVIDIA Graphics GPU installed on the PC. All GPU analyses using VTune Profiler are supported on Intel® processors with 9th generation of Intel HD or Iris Graphics (formerly Skylake) or newer. In order to...
68,384,044
68,384,424
why does the element before being entered already have a value?
I'm learning about C++ and when I was learning about Class, I ran into a problem. I try cout my element before entering the value, but the element already has a value. I can't understand why? class cusTomer { char abc[30]; public: void input(); void output(); }; void cusTomer::input(){ cout<<"abc: "; ff...
but the element already has a value. An integer always has a value. There is no concept of valueless integer in C++. If you haven't initialised an integer, then that value is indeterminate. If you read an indeterminate value, then the behaviour of the program is undefined. You should never read an indeterminate value...
68,384,269
68,384,468
Why does Eigen matrix calculations return zero when std::thread is used for multi threading?
I am trying to implement multi threading to distribute certain cpu intensive operations to different threads. However any Eigen declarations always returns zero when multi threading is used. Following is an example code that demonstrates this issue #include "../Eigen/Core" #include "../Eigen/LU" #include "../Eigen/Spa...
You have to apply std::ref to all matrices a, b and c when constructing thread. Without this, std::thread makes a copy passed arguments and operates on them, changing the copy of c matrix instead original c matrix defined in main. std::thread thread_multi(Multiply_3x3, std::ref(a), std::ref(b), std::ref(c)); thread...
68,384,419
68,384,492
Why std::clamp changed how comparison is done in C++20?
There is interesting note on C++ reference for first overload of std::clamp(one that does not take custom comparator). Uses operator< (until C++20) std::less<> (since C++20) to compare the values. All I found on cppreference is this (about std::less), but that seems borderline useless motivation since "most" (all) im...
This is just a wording clarification, it doesn't change any of the meaning of the algorithm.
68,385,071
68,388,776
GTest parametrized test unpack Values arguments from array or similar
Having a simple parametrized test with GTest, like for eg: class Example :public ::testing::TestWithParam<std::tuple<int, int>> { }; TEST_P(LeapYearMultipleParametersTests, ChecksIfLeapYear) { int a = std::get<0>(GetParam()); int b = std::get<1>(GetParam()); ASSERT_EQ(a, b); } INSTANTIATE_TEST_CASE_P( ...
Key to your issue is to use ::testing::ValuesIn instead of ::testing::Values. Cause in your case you are passing container and not a bunch of values. Complete answer will looks like this: class Example : public ::testing::TestWithParam<std::tuple<int, int>> { }; TEST_P(Example, ChecksIfLeapYear) { int a = std::get...
68,385,607
68,385,652
How to create multiple pthreads with a for loop?
This should be a simple task, but I just can't get it to work. The following code should be fairly self explanatory, I'm trying to create 4 threads that each print a different string from the array I defined in printMessage. #include <pthread.h> #include <iostream> using namespace std; void *printMessage(void *arg) ...
You are defining int index as a local variable inside of the loop body, so it will go out of scope after pthread_create() exits, thus printMessage() is exhibiting undefined behavior by accessing invalid memory (the memory is likely being reused on each loop iteration). You need to either: move the index value into an ...
68,385,888
68,414,877
Why does looping through and visualizing point clouds lag the PCL visualizer?
Here's the problem. I have an vector of point clouds pointers that I want to visualize one at a time. What I have is a visualizer that looks at the first spot in the vector and waits for keyboard inputs to change what is being visualized. For example, 'n' will give the visualizer the next element in the vector and 'b' ...
Figured it out... So it turns out that the m key is bound to something in vtk. I looked through the pcl source code and I couldn't find any functionality bound to m so I'm at a loss for why exactly it was the m key specifically slowing down the visualizer. I simply moved my keybind off m and now it works perfectly. Pre...
68,385,899
68,386,145
Is there a way to combine several enums into one?
I have two enums: enum class YellowFruits { Banana, Lemon }; enum class RedFruits { Apple, Peach }; I want to combine these two into one enum: enum class Fruits { //YellowFruits and RedFruits }; So that it works like this: enum class Fruits { Banana, Lemon, Apple, Peach }; But I c...
It's not an enum class, but using C++20's using enum declaration, you can make a struct/class that combines the enums under one name. That would look like enum class YellowFruits { Banana, Lemon }; enum class RedFruits { Apple, Peach }; struct Fruits { using enum YellowFruits; using enum RedFr...
68,386,091
68,388,505
QML QT backend and GUI design - doesn't update the object
I have simple object with collection which is created and managed under C++ code and I want to let user view it and modify it from GUI (QML - presentation of the collection and add/remove commands), but lifetime and business logic should be managed by backend (C++) class QtModel : public QAbstractListModel { Q_OBJECT...
You are not sending RowsInserted signals from the test function, so QML cannot know when to update. Please adjust like so: void QtModel::test(){ beginInsertRows({}, collection_.size(), collection_.size() + 1); collection_.push_back(std::make_shared<Data>("test")); endInsertRows(); }
68,386,297
68,386,364
Declaring an Auto Function is causing an undefined error
So I tried using an auto function for a Reader file and when I declare it in its own .cpp file and .h file I receive the error: 'Reader': a function that returns 'auto' cannot be used before it is defined But the function works perfectly in the .cpp file where main function is declared. Reader.cpp auto Reader(std::st...
You get the error because, when compiling main.cpp, the compiler cannot see the inferred return type of Reader() in reader.cpp so it doesn't know what it is. Solution: declare the return type of Reader() explicitly.
68,387,316
68,387,346
Ofstream not creating txt file
I am using Devcpp 5.11 whenever i erase the '.txt' code creating a file but i cant create a text file #include <iostream> #include <locale.h> #include <windows.h> #include <fstream> using namespace std; int main(){ ofstream newFile("file.txt"); newFile.open("file.txt"); newFile << "Hello, world!"; ...
Your code generally looks correct. When you supply a file name to the ofstream constructor it calls open() for you. You then need to check if the open() operation was successful with is_open(). If is_open() returns false then perhaps your program doesn’t have sufficient permissions to write a file in the working direct...
68,387,737
68,387,759
insert vector into unordered set after declaration c++
I'm looking for a way to insert a vector of elements into an unordered set that I have already declared. Say I have code as follows: unordered_set<string> us; vector<string> v{"green", "dog", "keys"}; Here, us has already been declared. How can I populate us with the elements in vector v with one command (i.e. without...
Use an iterator with insert(). us.insert(v.cbegin(), v.cend()); No need for the vector as long as the sequence conforms to the input iterator concept and returns strings. An array, other set, vector, etc. are all fine.
68,388,186
68,388,370
wrong output for inf=INT_MAX
Below code is for Bellman Ford algorithm and it gives wrong output when I use const int INF=INT_MAX but correct output when I use const int INF=1e9 in line number 3. Any idea why? Code: #include"bits/stdc++.h" using namespace std; const int INF=1e9; int main() { int n,m; cin>>n>>m; vector<vector<int>> edges...
Signed integer overflow here w+dist[u]. The simple fix: dist[v] = static_cast<int>(min(static_cast<long long>(dist[v]), static_cast<long long>(w) + dist[u]));
68,388,204
68,388,418
using predefined structs in c++ in functions
so i am trying to build a game and i have the following code: // Vector2 is just a struct that represents a vector is 2D space. // predefining these structs struct SILO; struct ICBM; struct MISSILE; struct ICBM{ Vector2 launch; Vector2 target; Vector2 pos; int Velocity; ICBM(){ // Imp...
You could use a SILO* in your MISSILE constructor, instead a copy of the whole object?! MISSILE(Vector2 t, SILO* origin){ launch = (Vector2) {origin->Object.x, origin->Object.y};
68,388,301
68,388,868
How to auto create a build log file for c++ project
How to set the make file or my project so that during the build process it automatically creates a log file from the output of compiler errors and messages for c or c++ projects.
Its just i/o redirection and you can do it in many different ways. Append each error after compiling that file in makefile. @gcc -c file1.c 2>> error.log As Martin york has said, make | tee log These are just some ways I can think of now. Do go through this guide for learning on I/O redirection.
68,388,818
68,394,122
Visual Studio Image type is not allowed
I'm trying to change image based on a click (Visual Studio C++). My code: private: System::Void FirstChannelButton_Click_1(System::Object^ sender, System::EventArgs^ e) { FirstChannelButton->Image = Image.FromFile("C:\Users\Username\source\repos\Project\ChOne.png"); } Really the same thing that the person tried to...
FromFile is a static method and C++ /CLI syntax requires to use :: for static method calls. So in this case the call should look next: FirstChannelButton->Image = Image::FromFile("...")
68,389,100
68,389,199
Which code is more efficient in memory/time complexity
It's said that when we pass an array to a function then only copy of that array is passed to the function. If we modify the array inside that function then original array would also be affected. So will case 1 take equal memory or it would consume significantly higher memory when compared to case 2 ? //Case 1:- int sum...
You're passing a std::vector, not an Array. The first case will take a copy of that vector (copying all elements to a new instance of std::vector<int>), while the second will just take a reference to the original vector. It's quite obvious that the second case will be more efficient (both performance and memory wise) t...
68,389,169
68,389,306
how to try and catch for preprocessor directives like "#include"
is there a method to try and catch for an #include directive since #include is processor directives and try catch method is done during compilation it wont work is there any workaround for it? I need to check if a file can be included else include another file.
__has_include function along with using #if and #elif would do that. #if defined __has_include # if __has_include (<stdatomic.h>) # include <stdatomic.h> # endif #endif Source: https://gcc.gnu.org/onlinedocs/cpp/_005f_005fhas_005finclude.html
68,389,730
68,393,045
Windows DLL function behaviour is different if DLL is moved to different location
I'm attempting to debug some very opaque issues with DLLs in Unreal on a CI machine (see Unreal: Diagnosing why Windows cannot load a DLL for more information). glu32.dll seems to be the DLL at which the Unreal process falls over, and as Windows Server doesn't contain all the graphics-related DLLs that normal Windows 1...
This is an example of why one shall not mess around with system DLLs. The DLL in question, like many Microsoft DLLs, uses MUI (Multilingual User Interface). If you look at its resources, it has no resources except a MUI type resource, pointing to a folder containing the corresponding .mui file, which contains its actua...
68,389,793
68,390,214
Is it safe to send a pointer to a CriticalSection Function? C++
I have some statics I use to check if a thread is running, and if the program wants to / can close. Normally I would create a seperate function for each variable like so: static CCriticalSection crit_sec; static bool static_thread_a_closed = false; static bool static_thread_b_closed = fals...
The pointers are fine. However, there is a good chance that static_thread_a_closed will not be read a second time because C doesn't, by default, know that static_thread_a_closed can change in the while loop. Adding volatile keywords lets the compiler know that variables can be changed by interrupts/other threads/other ...
68,389,907
68,390,530
Does the memory of an object with no reference get cleared automatically?
I know, this is a stupid question, but I have a few classes that extend another class, and I have a variable (Test* currentTest) in which I have one instance of one of the classes is saved. It always changes what is in the variable, and after a few changes, the entire program just crashes (either restarting or just fre...
You are leaking memory until you run out of memory. Every new should have a delete. If we look only at the update method and ignore all the rest, you should delete the old currentTest before you assign a new one: void TestA::update() { Serial.println("Running A"); a++; if(a >= 5) { delete currentTest; cur...
68,390,057
68,391,095
Is it legal to return address of local coroutine variable in C++?
If I return address of a local coroutine variable, e.g. via the promise, is it guaranteed to work by C++ standard? Consider an example (based on https://www.scs.stanford.edu/~dm/blog/c++-coroutines.html): #include <coroutine> #include <iostream> struct ReturnObject { struct promise_type { unsigned * value_ = nul...
Yes, this is legal. The local variables of counter are stored in a dynamically allocated object that h owns. The usual caveats of the possibility of use-after-free are there, i.e. promise dangles after h.destroy().
68,390,259
68,396,324
Sample random variates from a Normal Inverse Gaussian (NIG) distribution
How do I sample random variates from a Normal Inverse Gaussian (NIG) distribution? I need to generate 100 numbers from the NIG distribution. I use boost::math::inverse_gaussian but it does not have an operator() member function like std::normal_distribution Edit: Hörmann, W., Leydold have been doing some research into ...
I don't find the inverse Gaussian distribution in Boost.Random. You can use the so-called inverse transform sampling technique. That is, you take the inverse cdf (i.e. the quantile function) of the inverse Gaussian distribution, and you apply it to a sample of uniformly random numbers in (0,1). Something like that: boo...
68,390,360
68,392,349
Correct use of QDomElement::removeAttributeNS()?
What is the correct use of QDomElement::removeAttributeNS()? Given this (incomplete) example input XML <node xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="{company URL}"/> How can I remove attribute noNamespaceSchemaLocation? I have tried QDomElement root = doc.documentElement();...
You need to turn namespace processing on when setting content for the QDomDocument. Some overloads of QDomDocument::setContent() don't have this option and don't perform any namespace processing.
68,390,410
68,479,911
"Pure virtual variable" OR: how to force derived class to init a static member variable?
I have a singleton class Light and derived types SpecialLight and NormalLight. Both derived classes need to initialize the static member variable "Colors" with some specific content, while the base class should remain non-instantiable. How can I make my base class (Light) not instantiable (pure virtual), while forcing ...
As I understand it, you are trying to express the following invariant: Any class derived from Light is known to have a const static member Colors of type Color[]. Now you're essentially correct that virtual associates stuff to the runtime type of an object, and if you were able to have this "stuff" include not only m...
68,390,664
68,390,887
In C++ how to put a variable inside an array?
#include <iostream> #include <cmath> using namespace std; bool narcissistic(int value) { cout << "value is:" << value << endl; int digitNumber = (log10(value) + 1); cout << "Digit Number:" << digitNumber << endl; int sum = 0; int arr[5]; for (int i = 0; i <= digitNumber - 1; i++) { c...
You probably want something like this: #include <iostream> #include <cmath> #include <vector> using namespace std; bool narcissistic(int value) { cout << "value is:" << value << endl; int digitNumber = (log10(value) + 1); cout << "Digit Number:" << digitNumber << endl; int sum = 0; std::vector<int> arr(digi...
68,390,998
68,392,453
OpenCV reading too few pixels per row from camera
I am trying to fetch a video stream from a camera connected to the serial camera interface on my Raspberry pi 4. To read the video stream I'm using OpenCV and I have set the resolution to the maximum supported as listed by pi@raspberrypi:~ $ ffmpeg -f v4l2 -list_formats all -i /dev/video0 The output from this can be s...
The Raspberry Pi camera has a basic block size of 32x16 which means all image sizes are padded up till the width is a multiple of 32 pixels and the height is a multiple of 16 pixels. In your case, 4056x3040 would become 4064x3040. That actually makes your camera 12MP, so you must have the newer Raspberry Pi High Qualit...
68,391,229
68,391,893
How to create a type with expanded argument list of template<typename... Args> function?
In general, I have a poor idea of how to create such a type: template<typename... Args> using TWrapper = void *(*)(void *target, Args... func_args); I understand why this is throwing errors, but I don't know what to do about it ... I am developing a class with content something like this: template<typename TFunc> //TF...
If you limit you class to take function pointer, you might do: template<typename TFunc> //TFunc is a type of user's function class CallManager; template<typename R, typename... Args> class CallManager<R (*)(Args...)> { using TFunc = R (*)(Args...); using TWrapper = void *(CallManager::*)(void *const, Args...);...
68,391,250
68,391,310
Why there are Random numbers in non initialized array but not in non initialized members of half initialized array in C++?
Why in example 1 code it assigns 0s in non initialized items of array, but in example 2 assigns random numbers in completely non initialized array? Why it dont assign 0s to completely non initialized array as well? Example 1: int ar[5] ={0,1}; for (int i =0; i< 5; i++){ cout << ar[i] << " "; } // output: 0 1 0 0 0 ...
They're two different initializations. The case 2, int ar[5]; performs default initialization, as the effect all the elements are initialized to indeterminate values. The case 1, int ar[5] ={0,1}; performs aggregate initialization, as the effect the 1st and 2nd element are initialized as 0 and 1, the remaining elements...
68,391,273
68,391,454
C++ Math Weird After 65536
This is my first question asked so I am not sure exactly what to say. Basically, I wrote a program to find the diagonal of a rectangular prism with the inputs for length, width, and height being whole numbers ranging from 1 - 100,000. (The output of this function would only be stated in the console if it was a whole nu...
Welcome to the wonders of Overflow. So, here's what's happening: You're using int, which stores values in a 4 byte (32 bit) variable. When you multiply two numbers stored in X bits you may need to store the result in 2*X bits. In this case, 65536 is, in binary, 0000 0000 0000 0001 0000 0000 0000 0000 (in hex, 0x 0001 0...
68,391,332
68,395,237
Render to targets. Some have MSAA, some don't
I have 6 textures. Some were initialized via :- void glTexImage2DMultisample( GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); Some (e.g. for stroke / defer shading / special effect) were initialized via :- glTexImage2D( ... );...
In a single FBO, images are either all multisampled or all not multisampled. To do otherwise (even if the MS images have a sample count of 1) will lead to a framebuffer completeness error. Not only must all images either be multisampled or non-multisampled, all images must also have the same sample count (the sample co...
68,391,376
68,394,349
Vector element Destructor not called with reserve
I have this class: class aa { public: int i = 0; ~aa(){ std::cout << "killin in the name of" << std::endl; } }; And I want to make a vector of this class. First I thought o reserving the needed size: int main() { std::vector<aa> vec; vec.reserve(2); vec[0] = *(new aa()); vec[1] = *(new aa...
A std::vector already does this memory management for you. When you use an std::vector with simple classes like this, you do not need any new or delete calls. reserve Under the hood, reserve is just making sure that a chunk of memory is preallocated to hold the specified number of member variables. resize Under the hoo...
68,392,244
68,392,279
Is there a way for a member function to know if the object is an rvalue or lvalue?
My usecase is I have a class X which has a member function that returns a modified copy of X. Some of these member functions might be stacked like this X X_before{init}; X X_after = X_before.op_1().op_2().op_3(); In the above code op_1 would create a copy. Now what I am thinking is that there's really no reason why op...
Since C++11 we have ref-qualified member functions, with that overload resolution could select the appropriate overloading based on the object to be called on is lvalue or rvalue. #include <iostream> struct S { void f() & { std::cout << "lvalue\n"; } void f() &&{ std::cout << "rvalue\n"; } }; int main(){ ...
68,392,258
68,394,734
C++/CUDA: unresolved external symbol "enum cudaError ..."
There are quite a lot similar posts concerning this topic here on SO, however so far I couldn't find a solution to my issue. I want to add CUDA functionality to an existing C++ project (Window, Visual Studio 2019). Here is what I did so far (based on what I gathered googling around). Solution Explorer -> Right-Click o...
Here is what was missing: For all CUDA files do: Right-Click -> Properties In Configuration Properties -> General -> Item Type choose CUDA C/C++ This is the reason that no *.obj files where created and the linker couldn't link them.
68,392,310
68,392,419
clang: Use QHash<K,T> instead of QMap<K,T> when K is a pointer
There is a warning Use QHash<K,T> instead of QMap<K,T> when K is a pointer [clazy-qmap-with-pointer-key] produced by clang. But I couldn't google out an explanation on why QHash is preferable... (In my case I have less than 100 pointers). Are there any clarifications about that warning?
You are using Clazy, that is a tool (actually a compiler plugin) that helps clang to "diggest" qt semantics better when compiling... clazy has some rules, and the one you are violating is the Level 0: qmap-with-pointer-key they document the reason as following: QMap has the particularity of sorting it's keys, but so...
68,392,581
68,392,698
Return a struct pointer within a class
so I wrote a class and one of the functions returns a struct, both function and struct are contained within the class's private section. It's something similar to this: template <typename T> class myClass { private: struct myStruct { ... T item; ... }; myStruct* func(myStruct*, mySt...
You have two problems. One is covered by Where and why do I have to put the “template” and “typename” keywords? (and the answer from 463035818_is_not_a_number) The other is that with template <typename T> inline myClass<T>::myStruct* func(myStruct* a, myStruct* b) { ... }; you declare and define func as a non-member f...
68,392,683
68,395,000
Shouldn't the iterator types of Boost's small_vector satisfy the std::contiguous_iterator concept?
It is possible to construct a std::span from a std::vector (as the prototype for a contiguous container), both via the range constructor and an explicit pair of iterators: #include <span> #include <vector> std::vector<int> owning; std::span<int> view1{owning.begin(), owning.end()}; // works std::span<int> view2{owning...
std::contiguous_iterator has specific requirements in C++20 which were not part of any pre-C++20 interface. Since those interfaces did not exist pre-C++20 (particularly the contiguous_iterator_tag), they couldn't be used by small_vector<T>::iterator. Of course one can add such an interface, conditioned on the existence...
68,392,702
68,392,872
Can't include standard libs in cmake_pch.h
I am trying to generate a precompiled header in cmake that contains my regularly used standard libs. When I run cmake there is no errors but when I build it says it can't find the headers in cmake_pch.h. Here is the snippet of my cmake script that adds the precompiled header: target_precompile_headers(fae-core PRIVATE ...
You have added C++ headers to your target_precompile_headers command but also added a C source to your target. This cannot work as the C compiler does not understand how to include C++ standard headers. See the error message: [ 12%] Building C object core/CMakeFiles/fae-core.dir/cmake_pch.h.gch Either remove the C++ he...
68,392,977
68,393,409
C++ MFC, Get GUI Control using a ID variable
I was wondering if it is possible to get a MFC GUI Control with a variable acting as its ID. I have several controls I would like to change at once i.e. IDC_btn30, IDC_btn29 etc so this would be far more code efficient if possible. int days = 31; std::string id = "IDC_btn" + days; GetDlgItem(id)->EnableWindow(FALSE)...
The way I've done this is by creating a header file that gives a fixed mapping of a range of control IDs to an increasing sequence of integers: #define IDC_BUTTON1 2001 #define IDC_BUTTON2 2002 #define IDC_BUTTON3 2003 #define IDC_BUTTON4 2004 etc. The .rc file then needs to be set to include that header. In Visua...
68,393,256
68,393,348
Is it possible to initialize a data member as const based on a bool passed in as argument in the constructor?
I have a class that takes in a boolean called fixed as an argument. I want it to initialize the data member position as const if fixed is true. Is this possible at all? class PhysicsVertex { public: PhysicsVertex(olc::vf2d position, const bool fixed = false) : position(position), fixed(fixed) { }...
If your information about fixed parameter is needed at compile time then you can use templates #include <type_traits> struct vf2d { }; template <bool fixed> class PhysicsVertex { public: PhysicsVertex() : position() { } typename std::conditional<fixed, const vf2d, vf2d>::type position; }; void...
68,393,486
68,393,782
Boost::interprocess message queue compatible with windows?
Windows 10 MSCV 19.25.28614.0 Boost 1.72.0 While attempting to initalise a basic message queue taken from sample code in the docs: message_queue mq (create_only //only create , "message_queue" //name , 100 //max message number ...
I'm an idiot. Make sure you add: message_queue::remove("message_queue"); Before you attempt to create one: message_queue mq (create_only //only create , "message_queue" //name , 100 //max message number , sizeof(int) ...
68,393,734
68,393,827
lifetime of pthread_t in constructor of class
I'm reading the source code of a project, which is developed with C++98 on Linux. There is such a piece of code: class Test { public: Test(); static void func(void *arg) { pthread_detach(pthread_self()); Test *obj = (Test*)arg; // do something } }; Test::Test() { pthread_t tid; ...
When you call pthread_create, it saves the ID of the thread in tid. It doesn't save the address of tid. It just puts the ID there before it returns. So there is no problem. However, if this bothers you, you should call pthread_detach(tid) in Test::Test instead of pthread_detach(pthread_self()) inside the thread. It is...
68,393,845
68,408,942
Click on button for several QMessageBox in Qtest
I'm creating a test for my GUI application. At a certain point of the test, I want to click on a button which asks for user's confirmation and then, confirmation for each file I have to delete. So, on the test, to press that button I'm doing: QTest::mouseClick(m_widget->removeButton, Qt::LeftButton); But now, for the ...
We resolved a similar issue by adding a layer of abstraction over the message boxes. We have a global object with functions to 'display' message boxes and dialogs as follows: struct QtFuncs { typedef std::function<int(QMessageBox*)> MessageBoxExec; MessageBoxExec messageBoxExec = [](QMessageBox* mb) { return mb...
68,394,057
68,419,110
#include <cmath> stopped working in C++20?
Summarize the problem: My goal is to generate odd numbers up to a limit, store them in a vector then output the square of them. Describe what you've tried: So far, I used the #include < cmath > at the start before int main(), then I used a couple of if statements to check whether the limit is zero, if so I output an er...
I've written up a working version of what you want to do. I urge you to figure it out yourself first, that's the best way to learn, and then check your version against what I've got here. Note that this is certainly not the best way to do it. But I wrote it in a way that should be easy to understand. In programming the...
68,396,870
68,402,073
Why is there a copy when creating an rvalue and passing it to a function?
To better understand copy elision I wrote a test app that did a simple action in copy and move constructors/assignment operators and counted the times it was copied or moved. I noticed however that there was a copy when I created an rvalue and passed it directly rather than creating a lvalue then passing it in. I'm tr...
The additional moves seen in the output are caused by std::function<void(Bar)>. Change the definition of Foo to struct Foo { Bar bar; void setter(Bar a) { bar = a; } void setter2(Bar a) { bar = std::move(a); } }; and the output becomes base line mv_count = 0 cp_count = 0 in-place then copy mv_count = 0 ...
68,396,902
68,397,025
Why pointer object do not get deleted by itself as other objects got deleted at the end of program in C++?
Why didn't pointer object point in below example get deleted at the end of program by itself, as other object abc got deleted? But for pointer object I had to delete it myself, why is that? #include<iostream> #include<string> using namespace std; class A { private: string name; public: A(){ cout << "c...
A pointer is a reference to a memory address containing data (here, your A instance, point). new create objects on the heap, which must be managed manually, and return a raw pointer (point). Raw pointer must be freed manually (using delete). In your example, the pointer point is deleted, but not the memory its referrin...
68,396,962
68,397,071
How to split strings in C++ like in python?
so in python you can split strings like this: string = "Hello world!" str1 , str2 = string.split(" ") print(str1);print(str2) and it prints: Hello world! How can i do the same in C++? This wasn't useful Parse (split) a string in C++ using string delimiter (standard C++) , i need them splited so i can acces them sep...
If your tokenizer is always a white space (" ") and you might not tokenize the string with other characters (e.g. s.split(',')), you can use string stream: #include <iostream> #include <string> #include <stringstream> int main() { std::string my_string = " Hello world! "; std::string str1, str2; std::st...
68,396,993
68,399,372
How to relocate an element in one array in C++
I took this interview question and I failed, so I'm here to not fail again! I have an array of int with size 16 and a 5 < givenIndex < 10. I have to take the element in this index a print every possible array (there are 16) by moving the element at givenIndex through every position in array and pushing rest of elements...
If the expectation is to just print the elements of array in the given order: Keep the track of current index of array element to be print, say indx - If the position of current element processing is equal to row number then print the element at givenIndex. If indx is equal to givenIndex skip it and print indx + 1 ele...
68,397,197
68,397,949
Can I set OpenGL camera to look at positive z?
Since OpenGL camera basically looking at negative z direction, int front = 0, right = 0; // Press W and move backward?! front += glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS ? -1 : 0; front += glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS ? 1 : 0; // Press D to move right makes sense! right += glfwGetKey(window, GLFW_...
OpenGL doesn't have a camera. It just renders whatever happens to fall into the viewing volume in clip space. The "camera" is just either a completely abstract mental model, or some higher-level abstraction around some transformation math you add on top. As such, you completely define what a "camera" is and where it lo...
68,397,664
68,398,044
Is copy elision mandatory (if allowed at all) in the ternary operator?
Please consider the following C++17 code: #include <iostream> #include <optional> struct S { S(int) { std::cout << "S() "; } S(const S &) { std::cout << "S(const S &) "; } S(S &&) = delete; ~S() { std::cout << "~S() "; } }; int main() { [[maybe_unused]] std::optional<S> v = true ? std::optional<S...
The conditional operator is complicated and we have to read the standard carefully to understand it. See [expr.cond]. p4: "Otherwise, if the second and third operand have different types and either has (possibly cv-qualified) class type [...] an attempt is made to form an implicit conversion sequence from each of those...
68,397,734
68,398,037
OpenGL disappearing element after changing lookatmatrix
The vertices of my cube are defined to be at float vertices[180] = { -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5...
The projection matrix is the identity matrix. Therefore the near plane is -1 and the far plane is 1. The distance between the camera and the center of the cube is 2. Therefore the cube is clipped by the far plane. Change the position of the camera viewMatrix_ = glm::lookAt(glm::vec3(0, 0.0f, 2.0f), glm::vec3(0.0, 0.0, ...
68,398,136
68,398,315
to_string() C++ Time Complexity
I wrote a code to convert integer to string values in C++. I wanted to know the time complexity of my code. int n; cin>>n; cout<<to_string(n); Can anyone tell me the exact time complexity of the to_string() function in C++?
It depends of implementation of to_string in the specific library. We can try to compute approximate complexity of such algorithm O([log10(n)]) where [] is upper bound of number Actually log(10)+1 is number of digits in the number and we will spend about constant time for each digit. Note: adopt [log10(1)] as 1. to_str...
68,398,368
68,400,628
Does get_global_id include offset?
If I run kernel by calling clEnqueueNDRangeKernel with global work item offset, does get_global_id return offsetted value or I should offset it manualy? size_t offset[1] = { some value}; clEnqueueNDRangeKernel(..., &offset[0], ...); The right way will be: int id = get_global_id(0) or int id = get_global_id(0) + get_...
Yes, get_global_id(0) does include the offset specified in clEnqueueNDRangeKernel. For example, if you set the kernel offset to 50 and kernel range to 100, get_global_id(0) will count from 50 to 149.
68,398,444
68,398,722
Using template on a QWidget constructor
I have created a QWidget class that should take a template pointer as an input. Doing so with a method works fine, however when I try to use it on the QWidget's constructor I get an error. Here's the code: #ifndef GADGET_H #define GADGET_H #include <QObject> struct P2D { Q_GADGET Q_PROPERTY(P2D p2d READ getP...
From comments: Did you implement this function in your .cpp file? I haven't. But... Hmm... you should know that the only way to get rid of the issues is defining the functions body. So, if you need it to be generic, define the body in the header as well (and the compiler will handle the rest); Something like: templat...
68,399,042
68,423,126
Constant Time std::unordered_map<size_t, size_t> and personal hashmap implementation
I implemented my own hashmap and I wanted to benchmark it vs std::unordered_map. I use functions like the following to measure the nanoseconds it takes to do setting, successful gets, and unsuccessful gets: size_t umap_put_speed(std::unordered_map<size_t, size_t> &umap, size_t key, size_t value){ auto t1 = high_res...
While this isn't a solution per se, it is how I ended up getting some results that I was more happy with. I changed two things. First, instead of measuring individual insertions, lookups, and removals, I measured the time it took to chain K operations together. This gave me a much clearer picture of how much faster/slo...
68,399,190
68,399,231
Does std::string::resize(smaller_than_capacity) guarantee existing iterators are still valid?
According to cppref, std::vector::resize explicitly guarantees: Vector capacity is never reduced when resizing to smaller size because that would invalidate all iterators, rather than only the ones that would be invalidated by the equivalent sequence of pop_back() calls. However, I cannot find any similar guarantee f...
Such requirement does not exist in Standard. See 21.3.3.2: References, pointers, and iterators referring to the elements of a basic_­string sequence may be invalidated by the following uses of that basic_­string object: (4.1) Passing as an argument to any standard library function taking a reference to non-const bas...
68,399,328
68,414,019
Similar to Computing the Exact Offset in CGAL, can I compute the "exact buffer" of a polyline?
Is there any already built and ready to use C++ algorithms out there similar to CGAL's offset_2 function but instead of computing the Minkowski sum of a circle and a polygon, the Minkowski sum of a circle and a polyline is computed (i.e., the buffer of the polyline)? In application this is what I would like to do: Inp...
So, following from my suggested solution, the Minkowski sum of a polyline and a circle of radius r is the union of circles or radius r at each vertex and rectangles of width r about each line segment. Following this, I used the Boolean Set-Operations on General Polygons and the example therein, which conveniently takes...
68,399,757
68,401,156
what is a good way to efficiently store a list of c++ objects from different classes using Flatbuffers?
I have a list of c++ objects derived from different classes. I would like to use Flatbuffers to persist/restore them. An obvious way to do this is with a union, but i do not want to waste bytes or use a vector of pointers to a superclass (assuming this is an option in Flatbuffers). Another way is to store the concatena...
As per Mr van Oortmerssen, creator of Flatbuffers, it is possible to create a union of tables, where each table corresponds to an object class, then reference that union in each object in the list. Example at https://github.com/batwicket/flatbuffers_list_test.
68,399,816
68,399,933
C++ class member: Why does class member return different value from second access?
I'm new to C++, and wrote NumberStack class in stack.cpp as follows, but the result is different from what I expected, So I need your help: #include <iostream> class LinkedListNode { public: int value; LinkedListNode* next; LinkedListNode(int initialValue) { value = initialValu...
There are three changes that you need to make: Initialize node's `next' in the constructor Initialize head to nullptr Allocate nodes dynamically Here is how: LinkedListNode(int v, LinkedListNode* n = nullptr): value(v), next(n) {} Then call head = new LinkedListNode(initialValue, head); I would also give NumberStac...
68,399,831
68,400,017
invalid pointer conversion C++
I'm happy to post my first question here . so i was play a little bit with pointers to understand the concept and i found this error error: invalid conversion from ‘int*’ to ‘int’ [-fpermissive] here is the code : #include <iostream> using namespace std; int main(){ int* pa,pb,pc,a,b,c; pa = &a; cin ...
A common recomendation is to declare one variable per line (see for example ES.10: Declare one name (only) per declaration), because * belongs to the variables, not the type and this can be confusing. Your int* pa,pb,pc,a,b,c; is actually int* pa; int pb; int pc; int a; int b; int c; But you wanted: int* pa; int* pb;...
68,399,914
68,400,375
QT infinite view on model
I am looking for a way to create an infinite view on a model that is not initialized completely. I would like to create something similar to an Excel spreadsheet, and all I came in was to start with an initialized model (e.g. 100x100 empty cells, maybe working on a database that has empty values), and then just dynamic...
Well, your table will never be truly infinite unless you implement some indexing with numbers with infinite digit count and in that case, you will probably not be able to use Qt classes. But I think you should choose some big enough number to define the maximum. It can be a really large number... if you are on a 64-bit...
68,400,219
68,400,632
How to do AVX-512 integer increment only if element is non zero
I have to add a value to the elements of an AVX register if and only if the value of the element is non-zero. Below is the code that I have, but it seems like I have to go to a lot of extra trouble and like there should be a better way to do this. The commented out loop is the plain c++ expression of what I want to do...
So you want to increment every non-zero element in a vector? (You're not actually summing the elements in one vector, just doing vertical addition). It sounds like your real problem is turning an integer array into a mask, according to elements being non-zero. AVX-512 has instructions for this, e.g. compare vs. 0, or...
68,400,327
68,400,959
Initializing a variable with function-style cast in C++
int main(){ int a = 5; // copy initialization. int b(a); // direct initialization. int *c = new int(a); // also direct initialization, on heap. int d = int(a); // functional cast, also direct initialization? // or copy initialization? return 0; } I have 2 questions on this: 1 - It's not clear...
Your analysis is missing some steps. int *c = new int(a); This performs direct initialization of a dynamically-allocated int instance. The new operator evaluates to a pointer prvalue (type = int*) which is the address of this new int object. c is copy-initialized from the pointer prvalue. int d = int(a); Th...
68,400,414
68,409,954
Vertex buffer not clearing properly
Context I'm a beginner in 3D graphics and I'm starting out with Vulkan, which I already know it's not recommended save it please, currently working on a university project to develop the base of a 3D computer graphics engine based on the Vulkan API. The problem Example of running the app to render the classic 2D triang...
A comment by user369070 ended up drawing my attention to the function I use to read OBJ files which made me realize that this function wasn't cleaning a data structure I use to store the vertices of the object chosen to be drawn before passing them to the vertex buffer. I just had to add vertices = {}; at the top of th...
68,400,844
68,400,857
How to get the index of an element of a std::vector from the reference to one of it's items?
How would you elegantly (and in a modern C++ way) write a function that returns the index of a vector element, taking as argument this vector, and a reference to one of its elements ? Exceptions handling would be appreciated. #include <vector> template <class T> std::size_t GetIndexFromRef(std::vector<T> &vec, T &item...
This does the trick: template <class T> std::size_t GetIndexFromRef(std::vector<T> const &vec, T const &item) { T const *data = vec.data(); if(std::less<T const *>{}(&item, data) || std::greater_equal<T const *>{}(&item, data + vec.size())) throw std::out_of_range{"The given object is not part of the v...
68,401,401
68,407,013
Constrained CRTP Premature Rejection
I'm trying to implement a derived class inheriting from a base template, with the derived class as its template parameter (the example below hopefully clears things up): template <class T> struct S { T f() {return T();} }; struct D : public S<D> { }; This compiles and works well on gcc, clang, and msvc as well. N...
You can check the requirement in the default constructor of the base class #include <type_traits> template<class Derived> class Base { public: Base() { static_assert(std::is_base_of_v<Base<Derived>, Derived>); } }; class Derived : public Base<Derived> { }; This must also be checked in any other u...
68,401,812
68,401,960
free memory for matrix in NTL (Number Theory Library)
everyone! I'm using NTL inside the SGX enclave. When I run the application, I got the issue about out of memory. Then I checked the memory, I guess it's due to the heavy use of the NTL matrix. The basic use of matrix in NTL: Mat<size_t> mtemp; mtemp.SetDims(num_row, num_col); In NTL matrix.cpp, I didn't find any funct...
The kill() function should do that. Assuming Mat::~Mat() is implemented to release memory. template<class T> void Mat<T>::kill() { // This allocates an object with absolute minimum size (probably zero). Mat<T> tmp; // Now you swap the zero size matrix with your current matrix // memory. this->swap...
68,401,856
68,402,287
BCB Journal off line
Newbie here, I used to go to BCB Journal for assistance but always found stackoverflow a very good source of information and answers to lots of questions I had. But does anyone know what happened to bcb journal, it went of line a few weeks back without any notice. Also, the indy project seems to be lost as well, not fi...
But does anyone know what happened to bcb journal, it went of line a few weeks back without any notice. The C++Builder Journal ceased publication in January 2016, but its website and forums have stayed online since. However, the entire site went offline a couple of months ago without any warning. I tried contacting ...
68,401,922
68,402,111
How to "cut" vector in c++ like python syntax
In python if I have some iterable can I do something like this: v = v[n:k] // for i in v[3:]: "do something" and now in C++ I want to this: vector<int> v = {1,2,3,4,5,6,7,8} v = v[3:5]; Or something like this: for(auto n: v[2:end]) "do something"; I tried to find the syntax for this problem but haven't...
Prior to C++20, you can always do: for(auto i : std::vector(v.begin() + 2, v.begin() + 5)) { foo(i); } However it is not recommended as it creates a new vector by copying all elements needed. It would be better to just do a iterator based for loop: for(auto it = v.begin() + 2; it != v.begin() + 5; ++it) { foo...
68,402,093
68,552,372
Can you index a PCAP file without loading it all into memory?
I have to look at PCAPs that are quite large, around 40GB. What I'm doing right now is using PCAP++ to parse the PCAPs one at a time and process the data inside them. That data is placed into a buffer for it to be viewed. To save memory, I throw out the old data as you continue through the PCAP. This allows me to only ...
So I figured it out and short answer is no. PCAP++ doesn't support any functionality that could index, or mimic indexing, on a pcap file. I switched back to libpcap, (this also should work in windows with winpcap but I haven't tested it yet) in order to use a different library to help sort out what needed to be done. T...
68,402,149
68,402,177
Browse words within a line in C++ after getline
Is it possible to get each words of a line extracted with getline? for example, with this example as a "test.txt" file: 18407111 2018-07-05 00:04:02 MHAM EIDW 42 S1REB RYR5GW 3726 JNEIE 837B Datum RYR IFR Undefined 1 1 2018-07-05 00:15:38 2018-07-05 00:22:56 111 extended 0.0 113416.9 479798.5 -0...
Just use stringstream and read the word. while (getline(file,line)) { std::istringstream ss(line); std::string word; while (ss >> word) { std::cout << "This is the word: " << word << "\n"; } } but you can just while (file >> word) straight anyway.
68,402,250
68,402,352
How to use function definitions to open, read, and close a file
We are asked to open a text file that contains a sentence and go through all the letters and whitespace in the file and count how many of each ascii character there are. When I had all my information in the main function it worked fine. I just can't figure out how to call them all successfully in the main. The output s...
The problem is with your openFile() function. It creates a local ifstream only, it does not open an ifstream that is accessible to the other functions. Try this instead: #include <iostream> #include <fstream> #include <string> #include <cctype> using namespace std; //prototypes void openFile(ifstream &in); void r...
68,402,688
68,402,765
How do I get away with getting these garbage numbers
Here, I'm trying to make a program that basically gets the input from the user (from 0~100) and multiply that input by 123456789 without using long, double and float. So, I made some for loops, but I ended up getting garbage numbers ''' int n; std::cin >> n; int arr_1[9] = { 9,8,7,6,5,4,3,2,1 }; int arr_2[10]; //stor...
You have some problems with your long multiplication algorithm. For one thing, if you look at what you're doing with carries, you're writing the carry to arr_2[i+1], and then the next time through the loop you're overwriting it with whatever you calculate. (In fixing this, you're likely go to run into the problem that ...
68,402,850
68,402,880
C++17 unique_ptr lambda capture by value is ok, but not by reference
I have make a program showing that passing by value is fine but passing by reference will trigger SEGMENT FAULT. Currently, there are two unique_ptr maker functions as new_unique_ptr and new_unique_ptr2 as follows #include <functional> #include <memory> using namespace std; template <class T, class Deleter> unique_pt...
In new_unique_ptr the lambda is capturing the function parameter d by-reference; d will be destroyed when new_unique_ptr returns, left the captured reference dangled. After that when the std::unique_ptr gets destroyed, the deleter is called on the dangling reference which leads to UB.
68,403,008
68,404,454
How to use accumulate function to sum a row of values in a variable array?
I've been working on a program where I need to be able to sum rows in a two-dimensional array whose number of columns are variables. I should also add that the rows are "split" into two parts (part A, and part B) whose sizes depend on user input. I can obviously sum a row just using a for loop, but I wanted a more eleg...
The two first argument of accumulate are iterators that the function will use to iterate over the range, but you are passing actual element of the array Iterator in C++ is a concept that requires certain operations to be valid on your object, as defined per the standard. For instance, pointer types usually match the Le...
68,403,073
68,404,340
c++ winsock accept thrown exception
I’m using UE4 4.26.2 github source code,windows 10 1909,visual studio 2019. code: // 32-bit unsigned integer typedef unsigned int uint32; // 64-bit unsigned integer typedef unsigned long long uint64; template<typename T32BITS, typename T64BITS> struct SelectIntPointerType<T32BITS, T64BITS, 8> { // Select t...
The socket docs on accept: The argument sockfd is a socket that has been created with socket(2), bound to a local address with bind(2), and is listening for connections after a listen(2). So the first argument must just be a socket descriptor. You are casting that socket to a pointer, add 1 to the address which compl...
68,403,242
68,403,267
Why std::atomic<T> Template don't provide sub_fetch() member function?
ERROR: type should be string, got "\nhttps://en.cppreference.com/w/cpp/atomic/atomic\nstd::atomic member function can only get the value before modification,\nbut I want to know how to get the value after modification in a atomic way\nand why std::atomic Template don't provide those function like sub_fetch()?\n"
It does. It's called operator-=. std::atomic<int> i(5); int f = i -= 5; std::cout << f << "\n"; // 0 -= is the way you would write this operation for a non-atomic object, so std::atomic uses the same operator. The fetch_* operations are the breaks from the norm because normal values don't have these operations, but at...
68,404,071
68,404,325
std::atomic: Does the memory barrier hold up when task loops around?
So say I have this construct where two Tasks run at the same time (pseudo code): int a, b, c; std::atomic<bool> flag; TaskA() { while (1) { a = 5; b = 2; c = 3; flag.store(true, std::memory_order_release); } } TaskB() { while (1) { flag.load(std::memory_order_acquir...
No amount of barriers can help you avoid data-race UB if you begin another write of the non-atomic variables right after the release-store. It will always be possible (and likely) for some non-atomic writes to a,b, and c to be "happening" while your reader is reading those variables, therefore in the C abstract machine...
68,404,534
68,404,599
Function does not return value when it should
I wrote the following code for binary search int binarySearch(int input[], int start, int end, int element) { if(start<=end) { int mid = (start+end)/2; if(input[mid]==element) { cout<<"mid will be returned\n"; return mid; } else if(inpu...
You have to put a return before your recursive calls int binarySearch(int input[], int start, int end, int element) { if(start<=end) { int mid = (start+end)/2; if(input[mid]==element) { cout<<"mid will be returned\n"; return mid; } else...
68,404,667
68,452,301
Webservice call using IXMLHttpRequest undesired response Text
Using IXMLHttpRequest to fetch the data from the webservice.(actually, java servlets file). Using below code to send request and get response from webservice IXMLHTTPRequestPtr pIXMLHTTPRequest = NULL; CoInitialize(nullptr); CATUnicodeString usBuffer; CATTry { hr = pIXMLHTTPRequest.CreateInstance("Msxml2.XMLHTTP.6....
Header should be passed in this way. This solved the issue. CATListOfCATUnicodeString lsusHeaderName; CATListOfCATUnicodeString lsusHeaderValue; lsusHeaderName.Append("Content-Type"); lsusHeaderValue.Append("application/x-www-form-urlencoded"); lsusHeaderName.Append("Login-ticket"); lsusHeaderValue.Append(usLo...
68,404,699
68,404,830
std::string::erase is deleting all the characters following the iterator instead of only the iterator
I am trying to erase a character from a string. I have tried the code below: size_t it = s.find(char(i+97)); //dont mind the i, it is just the int in a for loop. s.erase(it); Here is a test case: Input: "cccaabababaccbc" Output: "ccc" Any ideas on why this is happening?
When you pass in an index, to erase, it goes till the end of the string. Change it to s.erase(it,1). The second parameter indicates the number of characters to remove. I suggest not naming the variable it, that name is typically used for iterator types. If you pass an iterator to erase, then only that character is remo...
68,404,839
68,404,917
Is it legal to make a copy of initilizer_list in lambda?
Please consider this simplified C++14 program: #include <vector> #include <iostream> int main() { auto l12 = {1,2}; auto copy = []( auto v ) { return v; }; std::vector<int> v{ copy( l12 ) }; std::cout << v[0] << ' ' << v[1] << '\n'; } GCC here issues the warning: warning: returning local 'initializer_...
It is well-formed, and there is no UB. auto l12 extends the lifetime of the temporary array, and keeps it alive until the end of main. auto v and the return value of the lambda don't extend anything, but it's not a problem as long as l12 is alive. But in general, I wouldn't recommend using std::initializer_list for an...
68,405,531
68,405,821
Get rid of nested for loops with std::ranges
Let I have a code: for (auto& a : x.as) { for (auto& b : a.bs) { for (auto& c : b.cs) { for (auto& d : c.ds) { if (d.e == ..) { return ... } } } } } as, bs, cs, ds - std::vecto...
With join and transform views, you might do: for (auto& e : x.as | std::views::transform(&A::bs) | std::views::join | std::views::transform(&B::cs) | std::views::join | std::views::transform(&C::ds) | std::views::join | std::views::transform(&D::e)) { // ....
68,405,599
68,405,656
Why does string concatenation fail when resize is used in cpp?
I came across a scenario where string concatenation is failing in C++. But I don't see a reason for it to fail. Code sample is as below: int main() { std::string a; std::string b = "bbbbbbb"; a.resize(10); for (int i = 0; i <= 5; i++) { a[i] = 'a'; } a = a+b; printf("\n%s\n", a....
In addition to the off-by-one error, after concatenation, the contents of a in main are: aaaaa\0\0\0\0\0bbbbb So: five 'a' bytes, then five zero bytes, then five 'b' bytes. The string is fifteen bytes long. printf, like other C functions, doesn't know about this size, and instead takes the length of the string to be u...
68,405,651
68,426,422
Problem using mutiple image2d across diferent shaders
Im new to opengl and im having problems using multiple image2d objects across two compute shaders invocations. I create the textures like this: GLuint light_texture[3]; glGenTextures(3, light_texture); for (int i = 0; i < 3; i++) { glActiveTexture(GL_TEXTURE1 + i); glBindTexture(GL_TEXTURE_2D, light_texture[i])...
Solved it by changing the way the textures are created: GLuint color_textures[3]; glGenTextures(3,color_textures); for (int i = 0; i < 3; i++) { glBindTexture(GL_TEXTURE_2D, color_textures[i]); glTexStorage2D(GL_TEXTURE_2D, 1, GL_R32UI,TEXTURE_WIDTH,TEXTURE_HEIGHT); glBindImageTexture(i+1, color_textures[i]...
68,405,764
68,440,622
app.exec() does not return on window close
I have a simple Qt application in Visual Studio: int main(int argc, char* argv[]){ QApplication app(argc, argv); Myclass* c = new MyClass; c->show(); int ret = app.exec(); return ret; } but my application does not return when I close the windows (in debug mode, app.exec() does not return). The process and sub process...
If the class that instantiate MarbleWidget class have a QMainWindow(parent) can be added void MyClass::closeEvent(QCloseEvent *e){delete c;} If there are no QMainWindows or QDialBox add in the main: app.closeAllWindows() and in the destructor: QApplication::quit();
68,406,059
68,406,121
c++ if several operator is defined in a class as virtual, does child need to override them all in order to compile?
I have the following classes, class Base { public: virtual void operator()(string a) {} virtual void operator()(int a) {} }; class Child: public Base { private: std::vector<double> child_vec; public: void operator()(string a) override { cout << a << endl; } }; int main() { Child child...
The problem is the operator() defined in Child hides operator()s defined in Base. You can introduce them into Child via using. class Child: public Base { private: std::vector<double> child_vec; public: using Base::operator(); void operator()(string a) override { cout << a << endl; } }; In your ...
68,406,605
68,410,524
How to overwrite a portion of a binary file using C++?
I have a binary file, and let's say at byte 11 to byte 14, representing an integer = 100. Now I want to replace that integer value = 200 instead of the existing one. How can I do that using C++? Thanks T.
Google is your friend. Searching for "C++ binary files" will give you some useful pages, such as: This useful link In short, you can do something like this: int main() { int x; streampos pos; ifstream infile; infile.open("silly.dat", ios::binary | ios::in); infile.seekp(243, ios::beg); // move 243 bytes...