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
67,130,318
67,130,843
Function return type overloading C++
i've read that you can only overload functions by argument type and not by return type. Recently i tried to learn how to use the <filesystem>. Here i found that the current_path(); function has a return type of path, but if you call it like this current_path(path('path/to/a/directory')); it changes your CWD and returns...
You cannot overload based on return type alone. In a nutshell, the compiler figures out what overload to call based on the arguments. Hence, you cannot distinguish two overloads based only on return type: int f() { return 42; } double f() { return 3.14; } // error redeclaration of f() f(); // calls what functi...
67,130,459
67,133,533
How to represent C++ private inheritance in an UML diagram?
In C++, one can create a sub-class via public, protected, or private inheritance. What's the notation to indicate that in a UML class diagram? I'm thinking about putting a label on the arrow but not sure if that's common practice.
What is private inheritance in C++? Private inheritance in C++, such as: class B1 { public: void test(); ... }; class D1 : private B1 { public: void demo() { test(); } ... }; means that every instance of D1 is an instance of B1, but that is hidden for the outside world. This strange construct aims at impl...
67,131,289
67,138,237
How do you load MPV Lua scripts with the C Plugin?
After realizing it is nearly impossible to find help on getting keybindings to work with the C plugin in MPV (Possible to allow key bindings with MPV C API when no video (GUI) is being shown?), I decided to learn some Lua to help with the cause. Problem is, the docs aren't very clear on how to add Lua scripts with the ...
After playing around more with the mpv_set_property_string command, I discovered that you have to specify the FULL path to the Lua file, it by defaults searches for the file in the directory it is being played in, so if I tried to play it in /home/ it will search for /home/test.lua, so to get it to work I had to do che...
67,131,373
67,133,023
How to resize a dynamically allocated array inside a class?
I have a private array inside a class, allocated dynamically. As I insert more and more items, I need to resize the array at some point. The question is how to do that correctly? The code below ends in an error: munmap_chunk(): invalid pointer while inserting a third item. #include <string> #include <cstring> #include ...
What the commenters said, plus the fact that you can replace your memcpy with a call to std::copy to get the correct behaviour: std::copy (array, array + arraySize, tmpArray); Don't forget to #include <algorithm>.
67,131,547
67,143,681
No such file or directorycollect2.exe: error: ld returned 1 exit status
I am getting this error; I tried to resolve it but I was not able to. To check the issue, I have first tried it in VS-CODE then on DEV-CPP but both show the same error which is basically not regarding my program. But I am getting that: #include<iostream> using namespace std; int main() { cout<<"Running"; return...
Today I have resolved this problem by resetting my PC. If there is another way, please tell me. I had done so because None of my program was running neither Java nor CPP.
67,131,867
67,132,323
How do I stop Visual Studio 2019 from automatically inserting asterisk during a block comment in C++?
When using Visual Studio 2019, when I hit enter within a block comment in a C++ file it adds a leading * . I've found a solution to this problem for C# at How do I stop Visual Studio from automatically inserting asterisk during a block comment? but the same option is not present for C++ and changing the C# option doesn...
In VS2019, click menu Tools\Options In the search field up to the left, type comment style In the tree view that appears under the search field, you should see a few nodes, Select the bottom node in the Text Editor/C/C++ tree (currently named General). To the right, you'll have a checkbox: [x] Insert existing comment ...
67,131,969
67,132,435
How to pass an object data member to a lambda function in C++?
Let's say I have the following non-working code (just for illustration purposes): class fruit { public: std::string apple; std::string banana; std::String orange; }; class grocery { public: std::vector<fruit> g_items; std::string total_weight; }; std::vector<grocery> shopping; a...
Change the lambda to take in a pointer-to-member, eg: class fruit { public: std::string apple; std::string banana; std::string orange; }; class grocery { public: std::vector<fruit> g_items; std::string total_weight; }; std::vector<grocery> shopping; ... auto check_item = [&](std::string (fru...
67,131,980
67,132,098
warning: 'auto' type specifier is a C++11 extension
I have a very simple C++ code statement auto a = 12;. When I am compiling it with g++ in Linux using -std=c++98 option I am getting an error as expected error: ‘a’ does not name a type But when I am compiling the same code with the same option in MacOS I am getting just a warning, but the code get's compiled fine. warn...
On MacOS, you're using clang, not gcc. (If I recall correctly, MacOS provides "gcc" and "g++" as symlinks to "clang" and "clang++", respectively, so that scripts that assume gcc don't break.) The two compilers just treat this case differently. Yes, a compiler that conforms to the 1998 ISO C standard, as both gcc and cl...
67,132,069
67,145,986
Converting an Eigen::VectorXd to an std::vector<double>
As the title says, I am trying to convert an Eigen::VectorXd to an std::vector. The vector is obtained by diagonalizing a matrix and then taking the first eigenvector of the process. #include <iostream> #include <vector> #include <cmath> #include <iomanip> #include <Eigen/Dense> using namespace std; using namespace Ei...
You are using a constructor syntax for the std::vector vec although the vector was already declared. That doesn't work. There are two efficient possibilities to copy the content of an Eigen::VectorXd into a std::vector<double>. You can either construct a new std::vector vec2, like this: vector<double> vec2(firstEvector...
67,132,351
67,132,944
Create an instance template
I write a code to implement a circular list using a template: template <class T> class CircularList { //implement } int main() { CircularList<string>* letters = new CircularList<>(); } But I have an error when I create an instance in the main class, what is the right syntax to write...
You have a problem here: new CircularList<>() <> you did not specify template type So your solution is: new CircularList<std::string> ();
67,132,985
67,133,299
Cost of converting a pointer to a vector into a reference
I am trying to access the elements of vector by using a pointer to it. I found that you can do something similar to the following: std::vector<char> vector= { 'a', 'b','c','d' }; std::vector<char>* vecPointer = &vector; std::vector<char>& vecReference = *vecPointer; char value = vecReference[2]; However, I am concerne...
Let's go line by line. std::vector<char> vector= { 'a', 'b', 'c', 'd' }; This seems like a cost you just have to pay, but for completeness, this is O(n) to copy the elements plus one memory allocation (which may be somewhat expensive). If you always have 4 elements, use std::array to avoid the memory allocation cost....
67,133,064
67,133,156
What does a cast from byte buffer to a struct do?
I am trying to understand the following code. PLOADED_IMAGE ReadRemoteImage(HANDLE hProcess, LPCVOID lpImageBaseAddress) { BYTE* lpBuffer = new BYTE[BUFFER_SIZE]; BOOL bSuccess = ReadProcessMemory ( hProcess, lpImageBaseAddress, lpBuffer, BUFFER_SIZE, 0 ); if (!bSuccess) return 0; ...
Following Microsoftian convention, the type PIMAGE_DOS_HEADER is a typedef defining a pointer to a IMAGE_DOS_HEADER struct. Therefore, PIMAGE_DOS_HEADER pDOSHeader = (PIMAGE_DOS_HEADER)lpBuffer; is casting the BYTE * pointer lpBuffer to the more-specifically-typed IMAGE_DOS_HEADER * variable pDOSHeader, presumably in ...
67,133,169
67,204,101
How to set fixed (const) fps using avcodec and libx264
I'm using this project https://github.com/apc-llc/moviemaker-cpp I'm wondering how can I set fixed framerate on my video for now it results like 33.6 38.1 35.3 when I enter 30FPS as c->framerate I tried everything found on the net but no chance. What I tried : at https://github.com/apc-llc/moviemaker-cpp/blob/319be2784...
Thanks to Solution is : What you're looking for is fixed gop and fps! to achieve that just set stream avg_frame_rate and tune to zerolatency, that's all. It works!
67,133,248
67,187,923
Direct leak in SDLNet_TCP_Open
Edit: This leak does not happen on Linux, so perhaps this is a MacOS Big Sur issue? Building the following code with the following flags produces a Direct leak. Is this a false positive or an actual leak in SDL Net? Flags: -g -O0 -fsanitize=address,undefined -fno-omit-frame-pointer -fno-sanitize=vptr Code: if (SDL_Ini...
Testing on Linux, it looks like there is no leak. This may be an issue with MacOS Big Sur itself, or something unrelated that happened to be reported as a leak when using SDLNet.
67,133,510
67,136,739
QMetaObject::invokeMethod does not call slot
I have a public signal called UpdateScreenshots in the workspacemanager class that takes screenshots of some widgets. It then returns these screenshots in a struct I've defined. This call is made from a thread as taking screenshots can apparently only be done on the main thread. However, this invokemethod call is not w...
First, make sure you have this declaration at the bottom of the InfoStruct header: Q_DECLARE_METATYPE(Vms::GuiWidgets::VmsWorkspaceManager::InfoStruct) Then, on top of your main function, have this call: int main(int argc, char *argv[]) { qRegisterMetaType<Vms::GuiWidgets::VmsWorkspaceManager::InfoStruct>("Vms::Gu...
67,133,535
67,133,813
using getline to read from file in c++
I am writing a program right now and I am currently trying to read an input from a file and put the members into variables. It is giving me an error when I am trying to use getline. Here is the line from the text file I am trying to read from. pontoon,Crest,Carribean RS 230 SLC,1,Suzuki,115,Blue,26,134595.00,135945.00...
The compiler error is referring to the C getline() function in <stdio.h> that is for reading a line as a char* string from a C FILE* stream. You are using a C++ std::ifstream instead, which that version of getline() does not support. Also, there is no version of the C++ std::getline() function that reads a line from a...
67,133,581
67,133,639
check if type has certain value types and the keyword value_type itself using c++20
I have following code #include <type_traits> template<typename T, typename U, typename Tout> requires std::is_integral< typename T::value_type > && std::is_floating_point< typename U::value_type > && std::is_floating_point< typename Tout::value_type > class test { test() =default; }; int main(int argc, char cons...
You have several some typos in the code you posted. Cleaned up, the following does what you're looking for: template<typename T, typename U, typename Tout> requires std::is_integral_v<typename T::value_type> && std::is_floating_point_v<typename U::value_type> && std::is_floating_point_v<typename Tout::val...
67,133,883
67,134,148
std::thread runs A LOT slower than std::future
I have some simple rendering program with a Mainloop that runs at about 8000 fps on one thread (it does nothing except draw a background) and I wanted to see if another thread rendering would upset the current context without changing it (it didn't to my surprise). I achieved this with this simple code here, m_Thread =...
The std::async can be implemented in different ways. For example there can be a pre-allocated pool of threads, and each time you use the std::async in a loop you just reuse a "hot" thread from the pool. The std::thread creates a new system thread object each time you use it. That may be a significant overhead to compar...
67,133,957
67,134,107
Why use C++ container "array" rather than traditional C array?
Popular opinion is that C++ array is safer with almost equal efficiency. Except for checking whether the index is out of range and not allowing implicit type cast to pointer, are there any other features? Besides, why implicit type cast of traditional C array is regarded as a bad way? I'm not very good at C++(also at E...
The main benefit is that a std::array is a first-class object in C++, which means you can do all the things with it that you can do with any other "normal" C++ object. A traditional C array, on the other hand, is not a first-class object, which means a lot of things won't work: #include <array> // Works! std::array<in...
67,134,088
67,480,187
Application crash with Qt5qml when building with VS2019
I have an application compiled with VS2013 and Qt 5.9.6 and it is working fine. Now I want to upgrade the Qt version to 5.15.2 and compile it with VS2019.The build is successful, I can run the application but it always crashes at the Qt5Qml module. I've debugging for a long time but still don't know why. Maybe 5.15.2i...
after a long time debugging with this pain in the ass. I finally found the solution to this. (But I do not clearly understand why it works :) ). I just want to post my answer here so if anyone has faced this issue like me can find a solution. As you can see I have a function called ExpressionEvaluator::evaluate, this f...
67,134,140
67,134,289
C++ Initiating object with array in constructor
I am trying to initiate an object with an array. Is there a way to do it with pointers or should i find another way to do this. EDIT: I want to write this code with dynamic memory allocation, I know vector is better way to solve this. #include <iostream> template <class t> class die { private: int sideCount; t...
The C++ solution: template <class t> class die { private: int sideCount; t* valueOfSides; public: die(int side, t arr[]) { sideCount = side; valueOfSides = new T[side] for (int counter = 0; counter < side; counter++) { //always initialize variables valueOfSides[i] = arr[...
67,134,350
67,134,420
What is the best way to count in every call in c++
I surfed on the internet and found different ways of counting a number in every function call. 1. Using Functor class count_number { private: int number; public: count_number(): number{1} {} void operator()() { std::cout << "Number " << number++ << '\n'; } }; ... count_number counter; coun...
What are the pros and cons pro: Works pre-C++11. A named class supports more complex use cases not available to lambdas. Doesn't use static state. con: Lots of boilerplate. pro: Less boilerplate than 1. Doesn't use static state. con: Doesn't work pre-C++11. Not as flexible as a named class. pro: Simple. Wo...
67,135,580
67,135,719
Why I can't use the std::map[ ] to add a string, but std::map.at() works?
My problem is why the s += t.getM()[0]; in the example code raise main.cpp:44:20: error: passing ‘const std::map >’ as ‘this’ argument discards qualifiers [-fpermissive] I checked the cppreference and it says both return a reference. In addition, why both operator[] and .at() work for std::vector? Example code is here...
std::map::operator[] only works for a non-const std::map. The documentation on std::map::operator[] explains this pretty well. Here's an excerpt from the beginning of the page: Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist. As yo...
67,135,609
67,142,091
reinterpret_cast a template class to const version
AFAIK, a template class with template argument <Type> is completely distinct from <const Type>. template<typename T> struct Wrapper { T obj = T{}; //other code }; Now I can't pass Wrapper<int>& to a function that needs Wrapper<const int>&. void someFunc(Wrapper<const int>& wrapper); //... Wrapper<int> wrapper; s...
There is a number of optimizations that can be different between the const and non-const cases, meaning both the memory layout of the class (e.g. since const objects does not need to actually exist) and the usage of the class can be different. In other words: Using reinterpret_cast for this can result in unexpected beh...
67,135,637
67,136,242
string to UTF-8 conversion in C++
I have a string Test\xc2\xae represented in Hex as 0x54 0x65 0x73 0x74 0x5c 0x78 0x63 0x32 0x5c 0x78 0x61 0x65. The character set \xc2\xae in this string is nothing but the UTF-8 Encoding of ® (registered trademark). I want to write a c++ function which can convert \xc2 (in Hex 0x5c 0x78 0x63 0x32) character set to hex...
As far as I understand your question, I think that you try to convert each \x?? sequence (four chars), where ?? is a sequence of two hexadecimal digits, to a unique char with the value which was expressed in hexadecimal. If you don't have to use huge libraries dedicated to this, maybe this trivial algorithm could do th...
67,136,148
67,136,161
C++: Why is the sum 0 in this for loop?
I am currently learning C++ with a book and one question was: What does the following for loop do? What is the final value of sum? int sum = 0; for (int i = -100; i <= 100; ++i) sum += i; To know what the final value of sum is, I put in the code in my editor, with everything else it needs to work (main and header) a...
Start with a simpler but equivalent example: int sum = 0; for (int i = -2; i <= 2; ++i) sum += i; You should be able to see it is equivalent to: sum += -2; sum += -1; sum += 0; sum += 1; sum += 2; And clearly the final sum is zero. Incidentally, an optimizing compiler can understand that entire operation and realiz...
67,136,315
67,136,434
Can't use public nested class as private method parameter
In the following code: class Outer { private: void f_private(Outer::Inner in); // Wrong public: class Inner {}; void f_public(Outer::Inner in); // OK }; f_private() cannot use nested class Outer::Inner as parameter type. But it's ok to do so in f_public(). Can someone explain to me in what rule this...
The problem is not that it's public or private, it's the order. This may seem strange, with other class members this is not a problem, but consider that in this case you are declaring a new user defined type, because of that you must declare it before you use it: class Outer { public: class Inner {}; void f...
67,136,318
67,136,471
Wrong output on c++ arrays
I am fairly new to C++ so this question may seem very basic(dumb!). I am trying to return an array of (int i, int j) which is a position(coordinates). Here is my code: int* Unblocker(int d1[2],int d2[2]) { int unblocker_position[2]; int distance; distance = abs(d1[0]-d2[0])+ abs(d1[1]-d2[1]); switch (distance) { case 1...
If you want to return a pointer to a local variable you need to store the variable in the heap. To do so you have to use the new operator. int *Unblocker(int d1[2], int d2[2]) { int *unblocker_position = new int[2]; int distance; distance = abs(d1[0] - d2[0]) + abs(d1[1] - d2[1]); switch (distance) ...
67,136,326
67,137,826
Cannot Assign multimap iterator private multimap member begin in const member function
I am trying to iterate through a multimap, which is a private member of my class, in a public member function so I can traverse the multimap and print the elements. I know that if I make the print function below non-const it works, but I cannot fully understand why it doesn't work with the const. I'm assuming that assi...
If you want to get an iterator in a const function then you can't use iterator, but have to use const_iterator instead. So you would have to change the mit type: typedef mm::const_iterator mit; Here it's compiling and running: https://godbolt.org/z/jM4rK6556 Or another approach would be not to force a type and let it i...
67,136,353
67,139,250
Is it possible to implement two push_back(..) methods of std::vector in a single universal reference method?
I'm trying to implement std::vector all by myself for some exercising purposes. My question is about the push_back(..) methods. There are two overloads of this method as in the following. void push_back(const value_type& value); void push_back(value_type&& value); At first, I implemented them in two different function...
The second version is not equivalent to the first one. In the first you take an argument of type "reference to T", and in the second U can be of any type, not related to T. So the second version is actually more an emplace_back than a push_back. It will take any value and try to construct an instance of T using that (t...
67,136,646
67,136,802
Implement iterator of a circular list
I'm trying to implement a class of Circular List with a nested class of iterator and I wrote like this: template <class T> class CircularList { struct Item { T data; Item* next; }; Item* head; int size; public: CircularList() { head = new Item(); head->next = head; ...
Assuming by "in the main class" you mean in the main function, the problem is quite straightforward: you're trying to construct a ::Iterator<string>, but there is no class in the global namespace (or anywhere else, in this code sample) called Iterator! You could try constructing a CircularList<string>::CircularListIter...
67,137,159
67,137,342
C++ program in which, read a six digit integer as input from user and output each of its digit in words by for/ While loop
/Write a C++ program in which, read a six digit integer as input from user and output each of its digit in words by using loop./ #include <iostream> using namespace std; int main() { int number, last_number, count = 0; cout << "Please enter a six digit number:" << endl; cin >> number; while (count < 6)...
well the problem in your logic is last_number = number % 10; because when you divide the number u get the last element for example if you divide 12345 with 10 you will get 5 as a remainder and that is where the problem arises try using string and a for loop it will be easier #include <iostream> using namespace std; int...
67,137,265
67,137,357
Returning an array in c++ conversion function
I am trying to learn c++ with OpenGL. OpenGL renders on a coordinate system from -1 to 1 on the x and y axis. I am trying to make a function to convert pixels to openGL coordinates. I have this code: float pixelsToCoordinates(int pixels[2]) { float r[2] = { (pixels[0] - windowWidth / 2) / (windowWidth / 2) * window...
Th expression in the return type return r; has the type float * due to the implicit conversion of an array designator to a pointer to its first element. On the other hand. the return type of the function is float. So the compiler issues an error message because there is no implicit conversion from the pointer type flo...
67,138,176
67,138,274
The syntax of a concept in C++20
How can we convert the requirements In this question link to a concept I have attempted the following: template< typename U, typename Tin, typename Tout> concept MyConditions = ( U::value_type && Tin::value_type && Tout::value_type && std::is_floating_point_v<typename Tin::value_t...
You don't need to manually check for the presence of the types. If they're not there, SFINAE will cause your concept to silently return false anyway. So: template< typename U, typename Tin, typename Tout> concept MyConditions = std::is_integral_v<typename T::value_type> && std::is_floating_point_v<typename U::v...
67,138,724
67,138,774
Array not initialized but includes curly brackets
#include <iostream> int main() { int arr[3][4] = {{0,1,2,3}, {4,5,6,7}, {8,9,10,11}}; int* ptr[4] = arr; } Why does the above code produce the array must be initialized with a brace-enclosed initializer error? I've seen other posts with this issue but the solution was to add in curly brackets, which I alread...
int* ptr[4] = arr; This is an array of four pointers to an int. And your compiler is, understandably, discombobulated because it's not initialized with a brace-enclosed initializer. You obvious intent is that this is a pointer to an array of four integers. That would be int (*ptr)[4] = arr; instead.
67,138,866
67,139,565
Suspend and Resume Lambdas in C++
I need something to suspend Lambdas in C++ and resume them. I try to narrow it down to a very simple example: Lets assume I have a singleton class orchestrator where I can register a lambda: int main() { orchestrator::getInstance().registerLambda([&](){ // Do something: ... wait(); // Suspe...
In the interest of the future where coroutine support will be more complete, here's one way a coroutine could look: resumable foo() { std::cout << "Starting foo\n"; while (true) { co_await std::suspend_always{}; // Could be co_await wait(); if you prefer, if wait() returns suspend_always std::c...
67,139,190
67,139,272
Pass by value in c++ :Why is the iterable value changing when I'm returning to main function?
I am trying to print the population the user defines from the current map: My question is why is the value of the iterable changing when I'm returning it to the main function? #include <iostream> #include <string> #include <map> std::map<std::string , int> :: iterator get_population(std :: string s...
You're passing the map to get_population by value. The lookup happens on the copy of the map, and you're returning an iterator into that copy (which is destroyed when get_population returns). Change your code to look like this: std::map<std::string , int> :: iterator get_population(std :: string state , const std::map<...
67,139,230
67,139,423
Why is move constructor called when doing assignment?
I'm trying to make a sample implementation of std::unique_ptr. Here is the code: include <iostream> template<typename T> class UniquePtr { public: explicit UniquePtr(T * ptr) :m_ptr(ptr) {}; UniquePtr(UniquePtr const & other) = delete; UniquePtr& operator=(UniquePtr const & other) = delete; explicit Un...
In the assignment, move is called because the UniquePtr<int>(new int(4)) is constructing a temporary object, and in this case the compiler tries to use the move assignment if possible, else it would fall back to the copy assignment, which is deleted. UniquePtr<int> t(new int(3)); t= UniquePtr<int>(new int(4)); // move ...
67,139,748
67,139,803
Constructor with parameter and array input doesn't work c++
I am facing a problem to parameterize a constructor with array user input. My question is: Create a class named Student and make a constructor with parameter like Student(int i, string n, double s) there are three private variables named int id, string name, double score and use int getID(),string getName(),double get...
Currently the code is not even compilable, you should get an error: undefined reference to Student::Student(). Your constructor is missing body. Change Student(); to Student() {}.
67,140,191
67,140,217
How to pass an array of mat4 as a uniform
I have to pass an array of mat4 as a uniform to my vertex shader like this: in the vertex shader: uniform mat4 u_jointMatrix[2]; in my C++ program I did like this: glm::mat4 jointM[2]; //I filled jointM with 32 values (16 x 2) int jointMatrixLoc = glGetUniformLocation(programT, "u_jointMatrix"); glUniformMatrix4fv(joi...
jointM[2] address the 3rd element in an array with 2 elements. You have to specify a pointer to the first element: glUniformMatrix4fv(jointMatrixLoc, 1, GL_FALSE, glm::value_ptr(jointM[2])); glUniformMatrix4fv(jointMatrixLoc, 2, GL_FALSE, glm::value_ptr(jointM[0]));
67,141,714
67,141,967
Cuda c++ odd even sort implementation
This is my code code for odd even sort: This code compiling, and running okay but, not sorting I guess. Please help me I am currently using CUDA 11.3 on visual studio 2019. My idea is creating odd and even functions and run it on after another. I'm multi threading the process of each function. In other words if(arr[2k]...
I suspect there are two problems. First, you are overwriting the first value in the array every time you run Odd(). You should remove the line arr[0] = 0; to fix this problem. Second, you are passing the host pointer a instead of the device pointer ptr to the kernels. You should pass ptr instead. With these (untested) ...
67,141,800
67,144,525
How to avoid this nested if statement?
I want to check if one file exists in two different paths. If the first one doesn't, check the second. filepath1 = "/path1/file.txt" filepath2 = "/path2/file.txt" file_descriptor = open(filepath1) if ( !file_descriptor.open() ) { print("file 1 did not work"); //try file 2 file_descriptor = open(filepat...
I guess this pattern is pretty general: you can try as many paths as you wish: auto filepath1 = "/path1/file.txt"; auto filepath2 = "/path2/file.txt"; // We assume file_descriptor has been declared earlier for (const auto fpath: {filepath1, filepath2}) { file_descriptor = open(fpath) if (file_descriptor.open()) ...
67,142,228
67,145,722
Turtle Mock: How to ignore unexpected calls?
Is it possible to ignore unexpected method calls for Turtle Mock? During my test the mocked method is called multiple times. I want to check only one invocation with specific parameters per test. Now I have to write one enormous test where I have to write all method invocations.
The expectation selection algorithm describes how you can set multiple invocations: Each method call is then handled by processing the expectations in the order they have been defined : looking for a match with valid parameter constraints evaluated from left to right checking that the invocation count for this match ...
67,142,423
67,142,516
Reduce the else if (true) of an if block
well, i just grab this function from an old code, but how i can delete the else if (true) i know that is possible, but i dont understeand how to do this with no affect on the output of fValid. I know that this is an easy easy problem, but i dont figure it out. Regards. template <typename T> void Set(const T pbegin, con...
If the condition of the first 'if' is false, then the code inside the 'else' block definitely executes. if (true) and its else statement are redundant. The equivalent of your code is this: template <typename T> void Set(const T pbegin, const T pend, bool fCompressedIn) { if (size_t(pend - pbegin) != keydata.size())...
67,142,444
67,151,052
How to use assignment operator on proxy of index operator
In the following code I made a template class, Its initialized in main function and I'm trying to assign char* as you can see below but It isn't working. I think the issue is in assign operator function I defined in Proxy class but I can't figure it out #include <iostream> using namespace std; template <class T> class...
Try this: using namespace std; template <class T> class Vector { public: T* p; int sz; Vector(int size) { p = new T[size]; sz = size; } template<class T> class Proxy { Vector<T>& v; int i; public: Proxy(Vector<T>& vec, int index) :v(vec),i...
67,142,463
67,145,878
custom comparator in lower_bound() stl function in c++
#include<iostream> #include<algorithm> using namespace std; bool compare(int a,int b){ cout<<a<<" "<<b<<endl; return a<=b; } int main() { int n; cin>>n; int a[n]={1,2,5,10,50,100,200,500,2000}; int money=100; int it =lower_bound(a,a+n,money,compare)-a; cout<<a[it]; return 0; } In th...
Right, just as Yadav said. You can also see cppreference about compare requirement: comp - binary predicate which returns ​true if the first argument is less than (i.e. is ordered before) the second. https://en.cppreference.com/w/cpp/algorithm/lower_bound
67,142,513
67,142,574
Why does this does not print nor terminate?
I had coaching today and we wrote this little code. What it does is obvious so I wont explain in details. After I run it and type something in, it does not print anything, and does not terminate either. If I switch chars for ints, it works fine. What is wrong with this code? #include<iostream> #include<string> using na...
The issue here is that the char data type has values from -128 to 127, so no matter how much you increment them, they will never reach 255. They will just loop back to -128 after going over 127. You can try using unsigned char or int.
67,142,596
67,142,798
Destroying nodes in a binary tree
Suppose I have a certain binary tree. I used new to create nodes, but now I want to delete them in the destructor: void BinaryTree::recursiveDestructor(Node *& noeud){ if (node != 0) { recursiveDestrutor(node->leftTree); recursiveDestructor(node->rightTree); delete node; node = 0; ...
You can breadth-delete a tree with a std::queue. Note: this is hammered out online with no syntax checking, but hopefully you get the idea: BinaryTree::~BinaryTree() { if (!root) return; std::queue<Node*> q; q.push(root); while (!q.empty()) { Node *p = q.front(); q.pop(); ...
67,143,154
67,144,028
How to print the b-th prime number coming after n?
I'm trying to write a c++ program which gets an integer n (n>=1 && n<=100000) from the user and puts the sum of its digits into b. The output needed is the b-th prime number coming after n. I'm an absolute beginner in programming so I don't know what's wrong with the for loop or any other code that it doesn't show the ...
As dratenik said in their comment: You have destroyed the value in n to produce b in the while loop. When the for loop comes around, n keeps being zero. That's a key point to understand, sometimes we need to make a copy of a variable. One way to do that is passing it to a function by value. The function argument will...
67,143,880
67,200,830
What is the definition of a thread safe function according to the C++11 (Language/Library) Standard?
TL;DR: What is meant by saying a specific function is 'thread-safe' as a data race occurs by simultaneously calling two possibly different functions? This question is especially relevant in the context of people telling "const means/implies thread-safe in C++11" [1][2] Consider the following example: class X { int...
Note that this my own opinionated answer based on my own research and provided input from others. What is the definition of a thread-safe function? A function is thread safe iff it does not access (read or write) any memory that could be modified by another function without internal synchronization: only set_y is threa...
67,143,881
67,143,932
Convert list iterator to pointer doesn't work?
I want to implement a function which iterates over a list and returns a pointer in case of a match. I wrote: std::list<JobEntry> jobs; JobsList::JobEntry *JobsList::getJobById(int jobId) { for (auto const& job : jobs) { if (job.pid==jobId) { return std::addressof(*job); } } retu...
getJobById() is declared to return a pointer to a non-const JobEntry object, but job is a reference to a const JobEntry object. You can't assign a pointer-to-const to a pointer-to-non-const. So drop the const. Also, a range-based for loop handles iterators internally, so job is the actual object you want to return a p...
67,143,966
67,144,060
Passing function as reference in template?
Recently I've came across this answer. I've noticed that a variation of this answer to: template<typename Adder> void AddHandler(int n, Adder& adder) { int r = adder(n); std::cout << r << std::endl; } also works. Does it matter how a function is passed? Is one way preferred over the other? How about performanc...
Assuming AddHandler is called with a function f that takes an int and returns an int int f(int i) { return i; } then the template taking a reference template<typename Adder> void AddHandler(int n, Adder& adder); // #1 will deduce Adder to be a function object type, specifically int(int). However, the overload taking...
67,144,077
67,144,087
Why am I getting the wrong numbers when putting them in a loop?
I am a beginner programmer specially with functions, my "sum" variable keeps returning ridiculous numbers like 32864 when the numbers that were entered were no more than 100, I tried deleting the if statement in the getgrade function but it doesnt seem to help, help me please. my code goes like this: #include <iostream...
You used the value of sum, grade, and numbOfTests without initializing them. Add initialization like this: int main() { int grade, sum, numbOfTests, average; displayIntro(); sum = 0; // initialization of sum numbOfTests = 0; // initialization of numOfTests // initialization of grade for (grade = 0; g...
67,144,139
67,144,170
c++ Reading a file into a vector of objects, then copying to vector pointer
I am writing a program to read from a file and take each line into an object and have all the contents of that line separated into their own variables in that object. I got that part down, it's just that the functions that have been defined for me are like so void printSpecs(vector<watercraft *> inventory). Can you h...
tempPtr is local to its scope and is invalidated at the end of its scope. Therefore, storing its pointer and dereferencing the pointer later is dangerous. For example, you can create objects on heap so that they won't be deleted by exiting scope. for(int i = 0; i < 18; i++){ test.push_back(new watercraft(inFile)); ...
67,144,334
67,144,447
c++ Insertion Sort Count Comparisons
I am working on a project that asks us to implement different sorts and add counter variables to measure the runtime with different array sizes. My problem is that my current output is not matching the expected output for my insertion sort. Any suggestions on what is wrong? Output: Array Size: 10 1...
Your counting (counter++; is not synchronized with the comparision. I moved counting to just before comparision and got the desired result. template<class ItemType> int insertionsort(ItemType theArray[], int n) { int counter = 0; //keeps track of number of comparisons for (int unsorted = 1; unsorted < n; unsorte...
67,144,539
67,144,708
How to format steady_clock time into HH:MM:SS.Milliseconds using <chrono>from c++ stdl?
I'm currently making a small game for my C++ programming class and the professor requires us to have a timer for the game. We haven't talked at all about how to use timers and any std timer libraries so we're on our own. I found the std library and have tried to implement a simple timer for the game and have managed t...
You can get the number of hours out of time_elapsed with: auto h = chrono::duration_cast<chrono::hours>(time_elapsed); Then you can subtract the number of hours so that time_elapsed only holds a duration less than an hour: time_elapsed -= h; Then you can get the number of minutes out of time_elapsed: auto m = chrono:...
67,144,650
67,144,668
C++ Question "timeout: the monitored command dumped core"
Hello I am making this question because on the for loop "for (grade = 0; grade != -1; numbOfTests++)" or in the getGrade function there seems to be an error if you enter the integer "-1" in the cin input first. More so it gives the "timeout: the monitored command dumped core" error. What is causing this? I looked up on...
When -1 is the first input, numbOfTests++ in the for loop is executed once. This causes numbOfTests to be zero and the finalAverage function will perform division by zero according to that. This may lead to runtime error.
67,144,670
67,145,104
How to compile a project with clases in Clang?
Seen this post: How do you compile a C++ program with multiple class files from OS X Terminal? I see that to compile with gcc a project with a class (with .h and .cpp) is easy as: g++ [list of all source files] -o [executableName] And it actually works for me, but when i try to use Clang: clang++-11 main.cpp Person.h...
If you run clang++-11 main.cpp Person.hpp Person.cpp -o main with the header file, clang notices this and compiles the pre-compiled header "Person.pch", the default -o Person.pch is implied. Meanwhile you want getting yet another output file "main". Thus, clang complains it can't generate multiple output files, -o Pers...
67,144,798
67,152,019
MFC MDI OutputWnd.cpp Context popup in COutputList "Hide" not working due to NULL Pointer
I'm doing some final cleanup in my code for straggler functions. My output pane is taken directly from the out of the box OutputWnd.cpp created by the MFC wizard. When you right click on the output pane with the 3 tabs it creates, the context options are copy/clear/hide. I have copy and clear working. But the issue is ...
An attempt to explaining this behaviour Yes, you're right. If we create a simple project (based on the "MFC App" template with "Project Style" as "Visual Studio" and "Visual Style and Colors" as "Visual Studio 2008"), then even the out of the box solution doesn't work. Why is this happening? In the next code when the...
67,144,806
67,145,198
C++ check if path is outside a given directory
What is the simplest way to check if a given path A is outside another path B? I.e.: determine whether foo/../../bar/ is outside foo/.
Something like this should work. Also note that both paths should exist. #include <filesystem> #include <algorithm> #include <iterator> #include <cassert> bool isSafePath(const std::filesystem::path &root, const std::filesystem::path &child) { auto const normRoot = std::filesystem::canonical(root); auto const ...
67,145,457
67,145,565
Moving an object that contains values
I have a class like this: class Bla { private: size_t length; ComplexClass expensiveData; // Very expensive, and Bla manages everything about someStuff, including its creation and deletion }; Now suppose I wanted to do something like this: Bla a = ...; Bla b = ...; a = b; Now what I think would happen is tha...
Storing a pointer to ComplexClass would work, but using a raw pointer would be unwise. Use std::shared_ptr<ComplexClass>. Alternatively, you could delete the copy constructor & assignment, and then store Bla in shared_ptrs when you do need assignments. And instead of deleteing the copy operations, you can: Make them p...
67,146,135
67,146,201
C++ std::function parameters const reference
I want to write a function, which could receive a ostream, a iterable object v, and a function op. The function is supposed to call op on every element in v, and then send the result to ostream. So I write the following code: template<typename T, typename IN = decltype(*std::declval<T>().begin()), typen...
Note that IN, i.e. the type decltype(*std::declval<T>().begin()) is a reference int&; then for const IN&, const is qualified on the reference and just gets ignored. So given IN is int&, const IN& -> int& & -> int&. See the behavior of decltype: ... If the argument is any other expression of type T, and a) ... b) if t...
67,146,430
67,147,431
C++, how to make efficient, 1 shared array of resources for multiple threads
Description: I have multiple threads (4-32). These threads can all access an array: int resources[1024]. Resources array contains different values (0-1023). There can only be one instance of a single resource(int). Each thread requires different number of resources, which are at some point returned back to the array. T...
This problem is a variant of the dining philosophers problem, which is an area of active research. There are some solutions, but none are perfect and generally in such situations avoiding a deadlock in a generic and constant-time way is problematic. Some general solution directions: Use an arbitrator. This can be as s...
67,147,097
67,147,713
How to correctly use smart pointers inside of a class
I am creating a binary tree in C++, and I have some problems when using smart pointers inside of the node class. When using normal pointers, everything works fine, but with smart pointers it is just not working. I think that the problem is in this line in the insert method: ''' binaryNode* node = this; // This ...
You do not need to use shared_ptr<>. Actually smart pointer are here to 'solve' ownership on object, thus when an object has a single owner, unique_ptr<> should be used, and when ownership is shared, shared_ptr are used. In you situation, the ownership is clear, each node owns its left and right members, thus unique_pt...
67,147,828
67,147,893
How to add every element in a matrix?
I am trying too add every element in a int matrix so I can check if the player or computer wins. bool WinCondition(int Grid[10][10]) { int SumOfShips; for (int a = 0; a < 10; a++) { for (int b = 0; b < 10; b++) { SumOfShips += Grid[a][b] ; if (SumOfShips == 30) return...
You need to have int SumOfShips = 0; or some initial value, which makes sense in the context. The reason being, that SumOfShips, when not initialized holds an arbitrary (indeterminate) value given the randomly assigned memory location. Further, the uninitialized value is regarded as being 'indeterminate', check here fo...
67,147,885
67,148,100
с++ How do I pass the value of a variable to a method inside a struct?
How do I pass the value of a variable to a method inside a struct? Method for changing the width of the rectangle. It takes how many units to change the width (You need to change the coordinates of the rectangle). #include <iostream> #include <string> using namespace std; struct rectl { int x1; int y1; int x2; ...
// u need to declare size first before initialisation from the user. #include <iostream> #include <string> using namespace std; struct rectl { int x1; int y1; int x2; int y2; int size; void show() { cout << "\n\t" << x1 << "," << y1; cout << "\t\t" << x2 << "," << y1 <<...
67,147,947
67,148,956
Is there any way to makethis below code faster in Eigen squaredNorm
I have below Eigen C++ code and doing squredNorm calculations 10milliyon times. Is there anyway to make it more robust/faster . #include <Eigen/Core> #include <tbb/parallel_for.h> #include "tbb/tbb.h" #include <mutex> #include <opencv2/opencv.hpp> int main(){ int numberOFdata = 10000008; Eigen::MatrixXf feat = Eigen...
You should be faster by a factor of about 4 if you store feat in the same order in which you access it (i.e., Eigen::RowMajor in your case). Minimal example removing all non-Eigen related things: int numberOFdata = 10000008; Eigen::Matrix<float,Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> feat = Eigen::MatrixXf...
67,148,663
67,148,847
Why the value is changing unexpectedly ? inet_ntoa
I'm trying to create a function which gathers all IPs present on the machine and will be able to detect when the IP in parameter is present.  The Issue is that the value of the variable containing my IP is changing after an inet_ntoa done on another IN_ADDR. I tried to use std::string without success. I know inet_ntoa ...
In short: this happens because you use the returned pointer directly instead of making a copy of the string. char* IPName = inet_ntoa(WFIAddr.sin_addr); As stated in the documentation of inet_ntoa (see here for Windows or here for Linux) the result is a pointer to a static buffer: The string returned is guaranteed to...
67,148,881
67,148,926
How to sort integer first then string?
I am trying to sort students name and their marks. I want to sort mark first then sort string of student names with same marks. Here is my code so far: #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { struct student { int mark; string name; ...
You should use a comparision function that matches your specification. sort(s.begin(), s.end(), [](const student& a, const student& b) { return a.mark < b.mark // a < b if a.mark is less than b.mark || (a.mark == b.mark && // when a.mark equals to b.mark a.na...
67,149,071
67,149,101
A c++ program to take the size and components of an Array from user and return the reversed Array
I have written this code that should take the size and components of the array from the user and then return the reverse of the Array but not able to identify and fix the error. My best guess is that the while loop is causing trouble, but I am not sure. #include <cmath> #include <cstdio> #include <vector> #include <ios...
int mainarray[] = {n} ; n = sizeof(mainarray); This is a wrong way to allocate array with n elements. This is allocating an array with one element, then overwriting n with the number of bytes taken by the array. Instead of this, you should do this for allocation: int* mainarray = new int[n]; Then, before return 0;, ...
67,149,726
67,179,992
How to pass a QML callback to c++ invokable function and execute it in the GUI thread?
I have a c++ Q_INVOKABLE function that starts an asynchronous operation (image downloading). I want to pass a QML callback to the function for when the operation finishes. I know that it could be done with QJSValue, but this way the callback is not called in the GUI thread so when I try to update some QML element, it p...
I figured it out. I just needed a way to call the slot in the GUI thread. When I pass the receiver object to the connect() method, it runs the slot in the receiver's thread. Thus, I can pass either the qml engine object or the qml component that calls the function to the connect() method and it will work. A: void Image...
67,149,854
67,155,356
Data type for std::string or std::endl
I have the following function template: #ifndef FUNCTIONS_H #define FUNCTIONS_H #include <iostream> #include <string> #include <vector> template <typename Streamable> void printall(std::vector<Streamable>& items, std::string sep = "\n") { for (Streamable item : items) std::cout << item << sep; } #endif ...
If you want the default value for the second parameter to be std::endl, then you can simply add an overload that takes only one parameter, and don't provide a default for the string overload. This will give you the overload set that you desire. template <typename Streamable> void printall(std::vector<Streamable>const &...
67,150,729
67,151,005
: 0xC0000005: Access violation writing location 0x00000000 C++ with inline assembly
I've been writing this code to implement the C "strcmp()" function using C/C++ with embedded assembly code like this bool myStrCmp(char* mystr1, char* mystr2) { if (myStrLen(mystr1) != myStrLen(mystr1)) return false; char s1[100], s2[100]; strcpy_s(s1, mystr1); strcpy_s(s2, mystr2); int i = 0; i...
It seems your debugger stops at the last instruction before the one where an exception occurred. The error is actually at the next line: inc [esi] That tries to increment a value stored at address esi. Since esi is 0, incrementing a value at address 0 results in an access violation. To increment esi itself, simply wri...
67,151,279
67,151,687
How to execute specific number of orphan and zombie processes in a single program?
I' m trying to write program that executes specific number of orphan and zombie processes. The number of each type of process is defined. I wrote some code, but it doesn't creates the expected output. Expected output means that program should create 15 zombie processes and 17 orphan processes. Meanwhile it 'produces' 1...
Your second for loop isn't doing anything. Let's refer to the initial process as the grandparent, the children of the first fork we'll call the parents, and then the children of the second fork as grandchildren. Every time the grandparent creates a parent (17 of them, based on the for(... i< Orphans...) statement), tha...
67,151,578
67,151,875
How can I document if variables passed by reference to a function need to be cached again when the function returns?
The following statement from the (wonderful) book c++ templates (p 109) suggests to me that passing arguments to a function by reference might compel the processor to cache the associated variables again: Under the hood, passing an argument by reference is implemented by passing the address of the argument. Addresses ...
You cannot in general write portable C++ code related to the CPU cache. Some microcontrollers don't have any cache. Some high-end processors have several levels of them. Notice the GCC builtin __builtin_prefetch. I believe some other compilers have similar things But see also this answer. In many cases, you should not ...
67,151,579
67,151,622
How to retrieve a value from a vector of vectors?
I am trying to make a vector that contains vectors, that contains a string. I am unsure on how I would go about retrieving said string. I've tried vector.at() but I'm not sure how to make a sort of 'multi-layered' version of it. This is the value inside of my code: std::vector<std::vector<std::string>> dialoguestore;
There are many ways to go about this with a 2D vector. Option 1: at(): dialoguestore.at(index).at(index2); Option 2: operator[]: dialoguestore[index][index2] If you have a multidimensional vector, use the ways you normally access a vector, but for the number of dimensions.
67,151,808
67,155,016
c++ search for string in an vector of strings
I am working on a project to read a Context-free Grammar and represent it 1.Vectorial, 2. Branched chained lists, 3. Array (Table). I encounter a problem with string comparison. When I read a string from keyboard representing right side of a Production rule, I want to check if that string exists in a vector of strings....
To do that you'd have to loop into the vector with a for loop and compare every string in it, it would be something like: #include <iostream> #include <string> #include <vector> using namespace std; bool doExists(string s, vector<string> v) { for (int i=0;i<v.size();i++) { if (s.compare(v[i]) == 0) { ...
67,151,845
67,152,011
How to execute an OS command from Cpp when it depends of code?
Let's say I have a function that takes an integer int m as a parameter, and I want to create a file which name contains the value of m, such that; if I call function(1); the function creates the script: scrp1.plt, if I call function(2); it creates the script: scrp2.plt and so on. Also, I want to execute an OS command ...
Try this: void function(int m) { ofstream file; string filename = "scrp" + to_string(m) + ".plt"; file.open(filename); //some code string scriptname = "gnuplot scrp" + to_string(m) + ".plt"; system(scriptname); }
67,152,108
67,153,145
For loop: Print the car name with the highest result. If they are equal, take the first one
I am starting with simple C++ codes and I am stuck with an easy task... I have to show the maximum speed value and the fastest car, after comparing two cars. To do that, I designed a function maxSpeedCar, that calculates the value "maximum speed". Then I store that value within variable fastestCar. If the fastestCar is...
I think this could help. Try running this and let me know if it doesn't work. You just update if only if you get a car with more speed. If you get a car with equal speed or lower that the current maximum result, you don't update and this way your bestCar still stores the first ever maximum found and discards all those ...
67,152,206
67,152,272
the code ends out of nowhere -1073741819 (0xC0000005)
When I enter different numbers in "studentNumber" and "testNumber" variables, the code closes at a specific place. No matter what value I give to the variables, the code stands in the second exam part of the 1st student. Code terminates with this error "Process returned -1073741819 (0xC0000005) execution time: 11.105 s...
Two issues: This line: for(int i=1; i<=studentNumber; i++) Should absolutely be: for(int i=0; i < studentNumber; i++) The other issue is here: for(int z=0; z<testNumber; z++) { cout<< "\n" << "Enter the " << z+1 << ". exam grade of the " << i << ". student: " ; cin >> Students[i].testResults[z...
67,152,418
67,152,514
How to take input to an array with unknown number of elements? ( I don't wanna use std::vector )
int n = 5; int arr[n]; for (int i =0; i<n; i++){ cout << "enter number" <<endl; cin >> arr[i]; } but what if the number of inputs is unknown? how can I take the unknown number of inputs in an array
Once you do int arr[n]; the size of the array is decided, once and for all. There's no way you can change it. On the other hand, you can dynamically allocate memory to which a pointer points to. int * arr; arr = new int[n]; // now you can use this arr just like the other one If you need, later, to change the size of ...
67,152,536
67,152,879
How similar are two words?
I would like to measure the similarity between two words. The similarity will be a function written in c++ which return a float between 0 and 1. If the two words a very similar, then that float will be near 1 and if they are very differents, then it will be something near 0. For instance, "Analyse" and "Analise" might ...
Have a look at Levenshtein Distance and Levenshtein Distance Implementation You can use the result of the above mentioned algorithm to achieve what you need Later edit: #include <iostream> #include <map> #include <vector> unsigned int edit_distance(const std::string& s1, const std::string& s2) { const std::size_t ...
67,152,660
67,153,146
Argument of type "SQLCHAR" is incompatible with parameter of type "SQLCHAR *"
#include <iostream> #include <sql.h> #include <sqlext.h> #include <sqltypes.h> #include <string> using namespace std; int main() { SQLHSTMT retrieveNumber; SQLUINTEGER IDNumber; SQLINTEGER IDNumberInd = 0; SQLRETURN rc; // Tried creating SQLWCHAR here to input to SQLPrepare but gives me: ...
Your text and statementText1 variables are declared all wrong. You are dereferencing a pointer to a narrow string literal, thus accessing its 1st character, which you then assign to text, which is declared as a single wchar_t. You are then assigning that wchar_t to statementText1, which is declared as a single unsigned...
67,152,783
67,154,429
Qt : How to alternate alignment of a QTextEdit in a QVBoxLayout?
I would like to add QTextEdit widgets in a layout and alternate the alignment QVBoxLayout *lt = new QVBoxLayout; for(int i=0;i<5;i++) { text1 = new QTextEdit; text1->setText("Hello world !" + QString::number(i)); text1->setMaximumSize(100,30); lt->addWidget(text1); lt->setAlignment(Qt::AlignLeft); ...
Just checking in the Qt doc i found that I just needed to add some arguments when adding my widget in the QVBoxLayout Here is the code : QVBoxLayout *lt = new QVBoxLayout; for(int i=0;i<5;i++) { text1 = new QTextEdit; text1->setText("Hello world !" + QString::number(i)); text1->setMaximumSize(100,30); ...
67,152,962
67,153,509
How to write a function template that takes a comparison opertator as a parameter?
I was given the task to write a function template that takes an interval as the first 2 arguments, and a comparison operator as the 3rd argument, and decide if it's monotonic or not using this comparison operator. Examples for usage: 1. int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; monotonic(a, a+10, std::greater<int>()...
Best way to design API and write code is by using tests. template<typename T, typename F = std::less<typename std::iterator_traits<T>::value_type>> bool isMonotonic(T b, T e, F cmp = {}) { if (b == e) return true; auto last = b++; while (b != e) { if (!cmp(*last, *b)) return false; last = b+...
67,153,159
67,153,272
How can I avoid circular dependencies between Entities and Map?
Lets say there are two classes: Map and Entity. Map has an array of pointers to all Entities in the game, and the entity uses a map to check if there is an empty spot where he is going to go. So, in the main function, I am doing the following: map->getEntity(x, y)->walk(map) which causes a circular dependency between ...
Just have a method declaration in the header file, and nothing more. Simply do not define the methods inline: class Entity; class Map { public: void add(Entity* ent); } Then in your map.cpp file you include both headers, and define the method: void Map::add(Entity* ent) { ent->getX() } map.cpp #includes both...
67,153,959
67,154,434
Class to calculate performance of a function
I'm writing a class as follows: struct TimeIt { using TimePoint = std::chrono::time_point<std::chrono::high_resolution_clock>; TimeIt(const std::string& functName) : t1{std::chrono::high_resolution_clock::now()}, functName{functName} {} ~TimeIt() { TimePoint t2 = std::chr...
NOW you have made the problem clear! By writing this: TimeIt("Reading"); you are creating a temporary object, which is immediately deleted. You need to give this object a name so it lives until the end of the block: TimeIt timer("Reading");
67,154,640
67,156,393
free(): double free detected in tcache 2 while deleting dynamic array
I am trying to read a .txt file and print the lines, while using only c-style string. int main(int argc, char * argv[]){ ... size_t size = 2; char* line = new char[size]; char c; while (file.get(c)) { if(c != '\n'){ line[size - 2] = c; char* temp = new char[size + 1]; ...
I am getting the error free(): double free detected in tcache 2. What is the problem and how can fix it? By understanding the error in this code: char* temp = new char[size + 1]; memcpy(temp, line, size * sizeof(char)); delete[] line; line = temp; delete[] temp; The important thing to remember is that temp and line ...
67,154,695
67,155,057
Why is the output 2020?
I have the following code: #include <iostream> using namespace std; class Foo { int data; public: Foo(int d = 0) { data = d; } ~Foo() { cout << data; } }; int main() { Foo a; a = 20; return 0; } The output of this code is 2020. I think what happens is, a temporary object a is cre...
You are right. Actually modify your code as follows can show the logic of the code more clearly. #include <iostream> using namespace std; class Foo { int data; public: Foo(int d = 0) { cout << "call constructor!" << endl; data = d; } ~Foo() { cout << data << endl; } }; int main() { ...
67,155,037
67,155,114
Can C++ tuple element types be conditionally added based on template parameters?
I'm trying to conditionally add types to a tuple template type based on some compile time condition, as follows: template <typename T> class Base { ... } template <int I> class Derived : public Base<std::tuple<std::conditional<I % 8 == 0, int, void>::type, std::conditional<I %...
A small part of your question does not compute: std::conditional<I % 1 == 0, float, void>: Since the remainder of any integer when divided by 1 is 0, this conditional will always be true. Whatever the actual intent was here, I'll just give an example with two conditionals that can be trivially extended to include add...
67,155,750
67,155,932
how to compare strings in vector in c++?
hey I have class containing #include <iostream> #include <string> #include <vector> #include <fstream> #include <iomanip> using namespace std; struct student { std::string ID; std::string Name; std::vector<std::string> friends; }; And main function contains int main() { vector<student> List_Students...
You can use the standard std::find_if() algorithm, eg ... #include <algorithm> ... int main() { vector<student> List_Students = { { "d123", "Jacob", {"e321"} }, { "e321", "Abo", {"d123", "e456"} }, { "e456", "Mark", {} } }; for (auto& s : List_Students) { cout << s.ID ...
67,155,875
67,165,983
Even and odd sorting arrays
I can't get the following program to sort 'orig', 'even', and 'odd' arrays in ascending order. The code seems fine to me, but it doesn't sort correctly at all, it will separate the array into the original even and odd lists, but the order is random and not in ascending order at all. The output should look something lik...
You have overcomplicated yourself too much with a two dimensional array and whatever int Max[3] is. Things are simple: sort the original vector, then filter the odds and evens. Since you filter after you sort, the two resulting vectors will already be sorted. Here's the C++20 solution: int main() { using namespace ...
67,156,830
67,156,918
Math on std::optionals?
When I try this: #include <optional> using namespace std; int main() { return make_optional(2) + make_optional(3); } ...
As you can see here std::optional simply doesn't offer an operator+ member. After all, std::optional is able to contain anything, including types for which operator+ doesn't make sense. What would optional<that_type>::operator+ do for those types? Clearly, you can write your own free function (modulo const/&/both or wh...
67,157,361
67,157,383
Strange operator[] behavior
When I was writing a program, I made a typo. I have wrote i[data] instead data[i]. However the program was successful compiled and worked right. Operator[] behavior with arrays: #include <iostream> using namespace std; int main() { int data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; cout << data[6] << endl; // pr...
i[data] is the same as *(i + data) data[i] is the same as *(data + i) And data + i is equal to i + data.
67,157,461
67,157,561
Struct/Class metadata for object representation and managed/unmanaged interaction
I know there is plenty of similar questions, but I want to understand very specific aspects that are never mentioned anywhere. In both cases: managed (NET runtime in this case) and native /unmanaged (c, cpp, etc) Taken from here: https://adamsitnik.com/Value-Types-vs-Reference-Types The first issue that not just wasn...
If struct is just all its data packed together, then where is metadata about what type of struct it is? There isn't any. With raw value data - whether that means an individual value, or an array/vector/whatever, the consuming code is the thing that knows how to interpret it. What it is is just: bytes. How would you ...
67,157,739
67,163,178
How to make the & sign blue if it is a reference sign?
template<typename T> void f(T const&& n1, T const& n2) { T&& x1 = static_cast<T&&>(n1); T& x2 = static_cast<T&>(n2); } The snapshot is from Visual Studio Code with C/C++ extensions. Problems 1. In T&& n1 and T& n2, & signs are blue. 2. In T&& x1 and T& x2, & signs are white. 3. In <T&&> and <T&>, & signs are...
(Based on rioV8's comments). In C++, & has different meanings depending on context. It can be the address-operator, it can denote a reference, it can also be a binary bit-and operator. To distinguish all these, you need to parse the tokens next to it. && is only marginally simpler, it can't be a unary operator. In T & ...
67,157,822
67,157,988
Template specialization for class wrappers
I can't have my int class wrapper acting like a primitive int in template specialization. I've prepared this code to explain my issue in detail: #include <iostream> #include <stdlib.h> class Integer { int _v; public: constexpr explicit Integer(int v) : _v(v) {} constexpr Integer next() const { return Integer(_v...
You can easily make Integer a structural type (C++20). Then its values are valid template parameters. class Integer { public: int _v; constexpr explicit Integer(int v) : _v(v) {} constexpr Integer next() const { return Integer(_v + 1); } constexpr operator int() const { return _v;} }; template <Integer i> voi...
67,158,684
67,159,555
How to generate field name of a class knowing its type?
Here is a sample code to clarify what I want to achieve: template<typename T> struct Compose{ T some_way_to_make_name_out_of_type(T); // -------------------^ // It may be some preprocessor hack or something based on templates }; The reason I want to do this is that there is a way to check if the field of a certain...
You cannot generate member name from template parameter. You can play with MACRO, something like: #define DEFINE_COMPOSE(type) \ struct Compose_ ## type { \ T T ## _field; \ } DEFINE_COMPOSE(int); Compose_int ifs; ifs.int_field = 3; Variadic Macro can be used to handle up-to some hard count limit. In regul...
67,158,869
67,159,002
How to solve "expected a ; " error when sorting a vector?
I am trying to sort vector using sort method. here is my code bool compare(const student * a, const student* b) { return *a.mark < *b.mark || (a.mark == b.mark && a.name < b.name); } sort(total_student.begin(), total_student.end(), compare); I get error before return, which read expected a ';', any idea why I mig...
Either you defined the function compare within another function or the reason of the error is another syntax error that precedes the line with the function definition. You may not define a function within another function. Instead of the function you could define a lambda expression. Place the function definition in a ...
67,158,995
67,159,085
cannot sort an array of objects according to objects' attribute value
The class Record contains the month, day, and balance. After creating the Record Object array, I would like to sort it by balance in ascending order and display them. Then, I would like to sort it by the date in ascending order and display them again. I was able to sort by balance, but cannot get the right order when s...
If you built this with compiler warnings turned on and paid attention to them, you would have noticed the stray semicolon at the end of the line if (isGreater(arr[j], arr[j+1])); which effectively disables that check and just performs the swap regardless. (That said, you should be using std::sort instead of writing ...