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
64,669,450
64,669,484
Weird string result when creating a basic cipher in c++
I'm creating a simple cipher and i got stuck on a weird problem with which i believe is with my IF's. char name[25]; char cipher[25]; gets(name); int i; for( i = 0; i <= 25; i++ ) { cipher[i] = name[i]; if( name[i] = 'g' ) { cipher[i] = 'a'; }; c...
In your if statement, you're doing an assignment rather than comparison: if( name[i] = 'g' ) should have == like so: if( name[i] == 'g' )
64,669,505
64,669,549
Why the if statement is ignoring the command line argument?
I'm trying to make a simple program that takes one argument. I use as main: int main(int argc, char* argv[]) { if (argv[1] == "string") { cout<<"STRING AS ARG!!"<<endl; } return 0; } But when I run it with program.exe string nothing happens. What is wrong with the piece of code?
The problem is that both operands are C strings and the comparison does a raw pointer comparison. You need to make at least one operand a std::string or a std::string_view. std::string_view is the best option because it avoids the overhead of the std::string, but you need C++17: #include <string_view> using namespace s...
64,669,528
64,669,561
How can i include header files from a directory into cmake
I have a cmake file which generates my helloworld.workspace to work from. How do i get my cmake to include header files from a directory and external libraries example. -glfw3 like how i would normally use when using gcc directly. Note: i am on ubuntu. Any help is appreciated. CMakeLists.txt cmake_minimum_required (VER...
You need to tell CMake to add includes/to your program's include path. Usually this is done with either include_directories or target_include_directories add_executable (HelloWorld ${source_files}) # Assuming this is meant to be a public directory target_include_directories(HelloWorld PUBLIC "includes/")
64,670,257
64,670,486
is it possible to have a members of subclasses in superclass in c++
My goal here was, instead of placing all methods in ServerInterface(superclass), i wanted to place the methods in child classes to organize the code better. class ServerInterface { public: Router* router = new Router(); Client* client = new Client(); ServerInterface() { } //Creates new Router and Clien...
The problem is with the design. You can compile this but when you create a ProductionServer it will instantiate a ServerInterface which will create a Router and a Client and those will both also instantiate a ServerInterface that will create a Router and a Client and so on - until you get a stack overflow. In order to ...
64,670,361
64,670,642
C++20 concept / requires expression to test if generic lambda accepts type
I'm trying to verify at compile time if a given lambda accepts a certain type (double in the case of my example code). As long as the signature of the lambda explicitly specifies the types this works. However, as soon as I use a generic lambda with auto in the signature, I get compilation errors when evaluating the req...
This is expected behavior. The lambda f3 claims to accept anything. But to test if it can be invoked with a double, we need to instantiate the call operator. Only failures in the "immediate context" of that instantiation count as substitution failures -- where the immediate context is basically anything closely associa...
64,671,089
64,671,564
Returning by value or by rvalue reference from rvalue reference qualified member function?
In Effective Modern C++, Item 12, Scott Meyers writes the following class to show how useful overloading member functions on the reference qualifiers can be: class Widget { public: using DataType = std::vector<double>; … DataType& data() & // for lvalue Widgets { return values; } /...
values is an object member and an lvalue, so if you just return values directly, it will be copied to the return value, not moved. The point of the && ref-qualified overload is to avoid making an unnecessary copy. return std::move(values) accomplishes this by casting values to an rvalue, so that it gets moved from in...
64,671,130
64,671,479
SetConsoleMode returns ERROR_INVALID_PARAMETER when disabling quick edit mode
I am trying to disable quick edit mode in the console with winapi. The documentation says: To enable this mode, use ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS. To disable this mode, use ENABLE_EXTENDED_FLAGS without this flag. I expected this code to work: #include <Windows.h> #include <iostream> int main() { ...
The first argument to SetConsoleMode is a handle to either "the console input buffer or a console screen buffer" per the linked docs. ENABLE_QUICK_EDIT_MODE is part of the set of flags which apply to an input handle, only, but the console handle in the posted code is a console screen buffer, instead. To set or change t...
64,671,280
64,671,332
Prevent object copy on return
I have this: struct Point { size_t x; size_t y; ~Point() { std::cout << "Destro" << "\n"; } }; const Point& getPoint() { return { 100, 120 }; } int main() { Point p = getPoint(); std::cout << "Exit" << "\n"; } and the result is Destro Exit Destro I'm basically trying to make t...
You need to return by value instead of reference. Using Point getPoint() { return { 100, 120 }; } Allows C++17's guaranteed copy elision to kick in which causes Point p = getPoint(); to act as if it was Point p{ 100, 120 }; Side note: Never, Never, Never, return a function local object by reference. That object...
64,671,850
64,672,033
Why is copy constructor invoked by return statement of expression?
I am implementing the addition operator for a custom class. The function/operator invoked is neither a friend or a member function and adds a scalar value to the vector (the class is supposed to be a linear algebra vector class). Internally, this function calls the addition operator of the class which in turn calls the...
Since operator+= returns a reference, the return statement needs to copy this referenced value into the return value for the function. There is not a value available that the compiler can use to elide this call to the copy constructor. Your first example is the equivalent of template<class T> template<class S> Vector<T...
64,672,164
64,672,193
Having trouble with remove()
I am having some trouble. What I am trying to do is make a file named <username>.txt and change a line in that file. The function should create a new file <username>.n where it makes the changes, and then delete the original file and rename the new file to <username>.txt. The problem is that this does not work: remove...
rename(/*oldpath=*/(user + ".n").c_str(), /*newpath=*/(user + ".txt").c_str());
64,672,693
64,672,744
How to reliably "clamp" an iterator?
I'm iterating through a vector as follows: for(auto it = myVector.begin(); it != myVector.end(); ++it){ // Do some stuff } Inside the loop, based on some condition, I add a variable amount to the iterator so as to "jump forward" (but, importantly, never "move back"). What is the "right" way (or, at least, what ...
if (myVector.end() - it < variable_amount) it += variable_amount; else break; Using std::distance and std::advance would allow this to work with non-random access iterators, but that would be an inefficient algorithm for them, so I recommend not using them. Algorithm for non-random-access iterators: for (; var...
64,672,959
64,673,067
Getting infinite loop errors and uncertain as to why
I have to submit an assignment tonight, and the online grading component keeps throwing me errors related to infinite recursion despite my code working fine on my PC. Essentially, the program takes a file formatted like 1 1 2 2 And formats it differently, outputs it with .log, and computes the distance equation. So t...
My main issue was a improperly implemented do-while loop, although the while loop fix posted was also an issue. Thank you to everyone who helped. Here is my fixed code. int main() { ifstream inFS; ofstream ofFS; int x1, y1, x2, y2; string fileName; string fileCheck; string fileName2; do { while (!inFS.is_open()) { ...
64,674,120
64,674,885
Loki MakeTypelist recursive template make me confuse
I'm studying loki source code. below is the MakeTypelist which makes me confused. class NullType {}; template <class T, class U> struct Typelist { typedef T Head; typedef U Tail; }; template < typename T1 = NullType, typename T2 = NullType, typename T3 = NullType, typename T4 = NullType, typename T5 = Nu...
Recursive template will terminate due to specialization template<> struct MakeTypelist<> being defined which returns NullType value of Result. This specialization is totally equal to next variant of code template<> struct MakeTypelist<NullType, NullType, NullType, NullType, ..... /* ... 18 Times ... */> // ....... Bec...
64,675,009
64,677,603
How to mock response in google test?
I have a tricky situation for gtest mock response. Pseudo code is as below: .cpp myMethod(resquest, response) { String name = getName(); response.getResponseType().name() = name; } .t.cpp TEST() { EXPECT_CALL(mockResponse, getResponseType(_)).WillOnce(,Return ResponseType); Request request; Respo...
You need to create a mock for the Response class, which requires that getResponseType is (pure) virtual method. Also, the EXPECT_CALL must specify that a reference is returned (notice that ReturnRef and not just Return is used). Also, myMethod shall accept mock by reference (when a copy is made, you won't be able to se...
64,675,724
64,675,863
Sorting string with if-else
My lecturer asked us to write a program that sorts three strings alphabetically using only if-else (no sorting algorithms, usage of arrays whatsover). I'm fairly new to C++ programming but I've come up with this program and would like to know if there's any way to make this more efficient while only using if-else? Any ...
Realistically you're not going to make this more efficient. In theory you can save a few tests by doing something like if(word1 > word2) { // ... } else { // ... } but in practice the compiler optimizer will take care of this for you. You may want to do some stuff to make it more readable, like fixing your indent...
64,676,086
64,676,301
How to install/apply C++ patch?
I'm trying to make an old, legacy project compile on my computer. I'm stuck on #error "Threading support unavailable: it has been explicitly disabled with BOOST_DISABLE_THREADS and stumbled on a patch for it. See this question. I downloaded the patch file. What am I supposed to do with it? How can I install it? Putting...
Assuming you put the patch under boost_1_48_0/threads.patch, you should be able to apply it with cd ...\boost_1_48_0 patch -p0 < threads.patch You can remove the patch file afterwards.
64,676,399
64,676,835
sum of number using private mode of inheritance in c++
How to make this type of program. How to do that can someone say as soon as possible a simple program will also work like sum of two number with private mode of inheritance. output need to be look like this I make this program with public mode of inheritance and I want this program in private mode of inheritance. I ne...
Maybe you want this: ... class child : private base1, private base2 { public: void sum() { cout << "Sum of a and b is: " << a + b; } void getaandb() { geta(); getb(); } }; int main() { child c; c.getaandb(); c.sum(); return 0; }
64,676,409
64,676,755
Reference to an object with disabled copy constructor/assignment
In my application I have a list of objects. Since I must have only one instance I've disabled both copy constructor and assignment operator. Moving an object is still allowed. But since I perform various manipulations with the objects I need to store the pointer to one of them. Before I've used pointer for that purpose...
In C++ references are not rebindable. What does it mean? It means that once reference is created, you cannot change object this reference is refering to. It has major implications - for example this code: Item i1; Item i2; Item &r = i1; r = i2; is logically equivalent to this one: Item i1; Item i2; i1 = i2; It shou...
64,676,490
64,676,603
Do I need to delete point in plugin class in Qt?
Now, I perfect my question.The pointer m_Core will be initialized and GetCore() will be called first for sure.The most I concerned is the document said root component will be deleted automatically when QPluginLoader is fully unloaded,and I don't know how Qt process the memory when Qt destruct QPluginloader and instance...
Initial short answer Keeping in mind the principle of ownership, most probably yes: it will cause memory leak. Also, consider that each call to GetCore will allocate a new instance and create memory leak. However, without having a full example, it is difficult to understand how SF_Core is used, especially if it ownersh...
64,676,646
64,676,748
Visual studio - buffer overrun
Having this code: #include <iostream> #include <math.h> #include <algorithm> double abs_length(int * ar) { return ( sqrt(pow(double(ar[0]), 2) + pow(double(ar[1]), 2)) ); } int ** correction(int size, int(*ar)[2], int refX, int refY) { int **ar2 = new int*[2]; for (int i = 0; i < size; i+...
There's an error here int ** correction(int size, int(*ar)[2], int refX, int refY) { int **ar2 = new int*[2]; for (int i = 0; i < size; i++) { int x = abs(ar[i][0] - refX); int y = abs(ar[i][1] - refY); int vector[2] = { x,y }; ar2[i] = vector; } return ar2; } The li...
64,677,130
64,677,468
Copy constructor is being called first instead of only move constructor on passing even R-value reference
Hello! I am making my own string class named strings On passing a R-value move constructor and move assignment operator are being called This is the main function, all i am doing is passing R-value ref, but while debugging only copy are or both move and copy. int main() { strings s1="hey!"; cout<<"\n"...
An moving assignment (not an assignment initialization) requires a move operator=(strings&&). It is not available if you defined own copy constructor. Note, that in situation like this struct S { S() {} S(const S &obj) { std::cout << "Copy ctor" << std::endl;} S(S &&obj) { std::cout << "Move ctor" << std:...
64,677,639
64,677,934
glRotatef() works weird in Opengl
I'm about to make a rotating sphere in C++ OpenGL, MFC Application. so I declared a variable that has a spinning velocity in demo.h : GLfloat angle; void Init(); Also, I initialized that variable and implemented one normal sphere at xyz(0,0,0) in demo.cpp : Init(); angle += 1; glRotatef(angle, 0, 1, 0); GLUquadricObj...
angle += angle doubles the rotation value every update. Depending on your update frequency, the spinning will almost immediately become completely erratic, and within a few seconds at most overflow the possible values for a float, thus becoming INFINITY, which OpenGL most likely errors out on.
64,678,231
64,678,669
What is the correct way to fill a __m128i parameter, from basic type (such as short), to use with _mm256_broadcast_epi (such as _mm_broadcastw_epi16)
All the four _mm256_broadcastb_epi8, _mm_broadcastw_epi16, _mm256_broadcastd_epi32 and _mm256_broadcastq_epi64 functions are intrinsics for VPBROADCASTB, VPBROADCASTW, VPBROADCASTD and VPBROADCASTQ instructions accordingly. According Intel's documentation: "Intel® Advanced Vector Extensions Programming Reference", thos...
There are already sequence/compound intrinsics which do exactly what you want: _mm256_set1_epi8/16/32/64 From Intels intrinsics guide: Broadcast 8-bit integer a to all elements of dst. This intrinsic may generate the vpbroadcastb. Using those you then should be able to trust the compiler to generate the optimal code. ...
64,678,512
64,678,615
Explicitly defaulted default constructor is implicitly deleted because of unordered_map used with a struct as key
I have the following Graph class: class Graph { private: struct Edge { string vertex1{}, vertex2{}; int val{}; Edge() = default; ~Edge() = default; explicit Edge(string v1, string v2, int value) : vertex1(std::move(v1)), vertex2(std::move(v2)), val(value) {}; bool op...
The Key in an unordered_map needs to be hashable. Either by adding a specialization of the std::hash class template or by providing a hashing functor when creating the unordered_map. You haven't shown that you've made a std::hash<Edge> specialization and you aren't creating the unordered_map with a functor to do the ha...
64,678,595
64,684,158
BOOST:ODEINT Sudden Iteration stop
I'm new in the world of C++ and I'm having some trouble with the boost library. In my problem I want to solve a ODE-System with 5 equations. It isn't a stiff problem. As iterative method I used both integreate(rhs, x0, t0, tf, size_step, write_output) and integreate_adaptive(stepper, sys, x0, t0, tf, size_step, write_o...
If you read the documentation, then you will find that the constant step-size routines are integrate_const and integrate_n_steps, or possibly integrate_adaptive with a non-controlled stepper. The short call to integrate uses the standard dopri5 stepper with adaptive step size, so that the changing step size is no surpr...
64,678,772
64,680,119
How do I recursively split a linked list of integers into an odd and even list in C++?
Hey I just took a quiz in school involving linked lists with C++ and I couldn't figure out how to get the function to work in the way my prof wanted. The quiz is over but I'd like to solve it anyways and try to understand linked lists better. I've been trying to figure this out for like 3 hours so, help would be apprec...
odd_even() created two new lists by rewiring one old list. So far, so good. Unfortunately, while you put all the nodes from the old list where they belong, you forgot terminating them by setting the final next-pointer to null. Thus, one will have the original last node and is thus terminated, while the other links to s...
64,678,862
64,679,129
Iterate over a container with a custom start/end position
I'd like to iterate over a container (say a std::vector) but not from the beginning. I am basically trying to replicate boost::make_iterator_range(v.begin() + 1, v.end()). I came up with this: #include <vector> #include <iostream> #include <algorithm> int main() { std::vector<int> v {1, 2, 3}; std::for_ea...
std::for_each is in C++11 and with that you can do: std::for_each(v.begin() + 1, v.end(), [](auto &n) { ... });
64,679,192
64,710,786
undefined reference to '__stack_chk_fail_local'
there is already a question asked: undefined reference to `__stack_chk_fail' but that question is undefined reference to __stack_chk_fail and not __stack_chk_fail_local. this Is a linker error i am getting and i have searched but i don't know how to fix it. This is the exact error: ld: binaries/GlobalDescriptorTable.o:...
__stack_chk_fail_local is a function frim glibc which basically call stack_chk_fail. /* On some architectures, this helps needless PIC pointer setup that would be needed just for the __stack_chk_fail call. */ void __attribute__ ((noreturn)) attribute_hidden __stack_chk_fail_local (void) { __stack_chk_fail (); } ...
64,679,200
64,679,262
error C2137 : Empty character constant in c++
Here is the code : void SomeClass::SomeFunctionToCorrectName(CString &strName) { // Only alphabets (Aa-Zz), numbers(0-9), "_" (underscore) and "-" (hyphen) are allowed. for(int nIndex = 0; nIndex < strName.GetLength(); nIndex++) { TCHAR currentChar = strName.G...
If you want to remove a specific character, then Replace is not the right method to use. As you've noticed, there is nothing reasonable to replace the character with. Instead you can use Remove like this: strName.Remove(currentChar);
64,679,237
64,691,121
Clang always breaks inheritance list for multiple inheritance
Want to format my code in this way: class Foo : public Parent1, protected Parent2 { }; However clang-format always breaks inheritance list for multiple inheritance like this: class Foo : public Parent1 , protected Parent2 { }; which is not beautiful and not onvenient. Is there a way to fix this - seems no op...
The style option you're looking for is BreakInheritanceList. See the documentation for details. When this style option is set to BeforeComma, you get the formatting you show above. You might not be setting it explicitly - if your settings are based on the Mozilla style then this style option is set to BeforeComma. The ...
64,679,859
64,682,119
How to break std::cin(std::cin.getline) executuion from other thread
I have some code: while(true) { std::string message; std::cin >> message; // break it // send message } I want to interrupt waiting for user input from std::cin from other thread. How can I do it? Thanks in advance!
std::cin is a blocking call that can not be interrupted. This thread here seems to have some non-blocking alternatives: https://stackoverflow.com/a/40812107/2562287 If you used a non blocking alternative for std::cin along with an boolean (threadsafe from either a mutex or being atomic, preferably the latter), you coul...
64,680,101
64,680,204
Why doesn't the copy constructor work when I return an automatic variable from function?
In the below example I want to find out why the copy constructor isn't called when I return an automatic variable from the doit() function. I understand that the first version of handler is called because we have a temporary object but can't figure out why the copy constructor isn't called while creating that temporary...
Actually, there is a constructor being called in your code according to the rules of the language. However, the compiler has optimized that out and so you don't see the call. If you compile with -fno-elide-constructors you should see the copy-constructor being invoked. Note that the copy-constructor will only be invoke...
64,680,168
65,142,203
Smaller images have almost no consequences on inference time in OpenCV for a Mask RCNN model
CONTEXT I trained a custom MASK RCNN using Tensorflow Object Detection API to detect areas on the face. My input images are 480x480 but I chose to resize them to 240x240 so that the training can be quicker. MY ISSUE I did the inference in C++ on several computer using OpenCV DNN in another project and I have very diffe...
To people who might have the same problems, the MASK RCNN and other models similar like Faster RCNN have always the same number of parameters regardless of the input size of the image which makes the inference time almost always the same. It is then difficult to improve inference with OpenCV. The best solution is then ...
64,680,385
64,680,687
Derived public class doesn't inherit protected variable
So I have three classes which are the following: The Person class: #ifndef INC_7__LABOR_PERSON_H #define INC_7__LABOR_PERSON_H #include <string> #include <iostream> using namespace std; class Person{ protected: string lastName; string firstName; int dateOfBirth; public: Person(const string &lastName, ...
The short answer here is that this is because that's how inheritance in C++ works. Your Manager class is attempting to access a member of an Employee class that it inherits as protected from Person. It is a separate Employee object at hand, and it's trying to get at its protected member. Something that's protected cann...
64,680,424
64,932,920
Why g++ static linking doesn't work with sfml in windows?
I am trying to compile a simple program statically: #include <iostream> #include <vector> #include <string> #include <SFML/Window.hpp> #include <SFML/Graphics.hpp> using namespace std; int main() { sf::RenderWindow window(sf::VideoMode(800, 600), "HW Test"); vector<string> m = {"Hello", "world"}; for (con...
You have not passed parameters in correct order . Graphics Window Audio Network System This is correct order and this is correct command. C:\Users\Retsal\Documents\Cpp\SfmlTest>g++ -o hw.exe .\src\helloworld.cpp -I C:\Users\Retsal\Documents\Cpp\SfmlTest\include -DSFML_STATIC -L C:\Users\Retsal\Documents\Cpp\SfmlTest\l...
64,680,505
64,680,718
Not able to include a header file in C++
My code looks like this: #include <GLFW\glfw3.h> // define the function's prototype typedef void (*GL_GENBUFFERS) (GLsizei, GLuint*); // find the function and assign it to a function pointer GL_GENBUFFERS glGenBuffers = (GL_GENBUFFERS)wglGetProcAddress("glGenBuffers"); // function can now be called as normal unsigne...
In the path for the #include you use a backward slash \: #include <GLFW\glfw3.h> On a POSIX system like Linux or macOS this is not a valid path-separator, instead it's considered part of the file-name. You need to use forward slashes / on such systems: #include <GLFW/glfw3.h> Since forward slashes also works on Windo...
64,680,539
64,689,553
What is .c.obj / .cpp.obj file?
I got these console output while compilation via GCC. Building CXX object xxxxxxx.cpp.obj What are the .cpp.obj files? Are they the object file? Do the same as the .o file?
What is .c.obj / .cpp.obj file? Object files created from compiling .c and .cpp files respectively. What are the .cpp.obj files? See above. Are they the object file? Yes. Do the same as the .o file? Yes. Note that "extension" is just part of a filename and is customizable. You can name your file anything you wa...
64,680,769
64,680,981
C++ Core Guidelines for static member variables
I have a private static vector in my class that keeps a pointer to all objects created from it. It's necessary as each object needs access to information from all the other objects to perform some calculations: // Header file: class Example { public: Example(); private: static std::vector<const Example*> exampl...
What you've done is fine. This is literally the purpose of class-static. Some people would recommend alternatives, for unrelated reasons, which may be worth considering… but not because of anything clang-tidy is telling you here. You've run into clang-tidy bug #48040. You can see this because it's wrong in its messagin...
64,680,908
64,681,414
Compile C++ Program to run in background and show in taskbar
I am creating a no UI no console program in C++ to run in the background. Everything's working fine. But I want to have an icon of the program in the taskbar hidden icons. Also is there a way I could add options to the icon in taskbar (like settings, exit, etc) Details: Compiler: MinGW 64 OS: WIndows 10
In case you use Qt, this would do the job: MyClass::MyClass(QWidget *parent) : QDialog(parent) { hide(); // Gui is hidden createTrayMenu(); } void MyClass::createTrayMenu() { QAction* settingsAction = new QAction(tr("&Settings"), this); connect(settingsAction, SIGNAL(triggered()), this, SLOT(showSettings())...
64,681,140
64,684,531
C++/Flatbuffers - Verify table which is not root_type
Here is my fbs: namespace Vibranium; enum LOGIN_STATUS : int { INVALID_CREDENTIALS, LOGIN_SUCCESS, ACCOUNT_LOGGEDIN, ACCOUNT_INGAME, ACCOUNT_BANNED, ACCOUNT_LOCKED } table LoginRequest{ email:string; password:string; client_hash:string; connection_id:uint32; } table LoginResponse{ acc...
Functions like VerifyLoginRequestBuffer are "convenience" functions generated for the rout type. You can look at their (small) implementation, and call the exact same function for any other table type.
64,681,160
64,681,632
translate python function with yield(string) to C++
I'm translating a python function into a C++ function; this function uses a yield(string) statement that I don't know how to translate. Here the whole story...I have a certain function that reads an input ASCII file filename, which contains lines of data, and puts the content of the file into an std::vector. When readi...
This is a state machine that reproduces that generator's functionality. #include <stdexcept> #include <string> #include <iostream> class FileStructIterator { public: explicit FileStructIterator(const std::string& filename): m_filename(filename), m_state(STATE_START) {} std::string getNext() { ...
64,681,330
64,681,762
how to map multiple values in c++?
current code std::map<std::string,int> m; ... m.insert(std::pair<std::string,int>(text,lineno)); ... std::cout<<"key: "<<iter->first<<"lineno: "<<iter->second<<std::endl; how to save mutiple values in same key?
To sum up the comments of others, here's an answer. Say you have some type T and would like to map a std::string to multiple values of that type. The easiest way to do this, when you don't know how many multiple values you need to map to, is to use an std::vector <T>. If you do know how many multiple values you're goin...
64,681,341
64,681,440
summation of user input in a loop
I made a little store system and i put a code for each product(like barcode) and user will enter these codes, and I want to make a system that gives this code and input the price, and do this few times, but I don't know how to summation these price that known by user barcode input. #include <iostream> #include <conio.h...
I think if you want to sum all the items a simple solution would be to declare sum = 0 at the start, and later on when you add an item make it sum = sum + price.
64,681,796
64,686,730
Difference between -static -lxyz and -l:libxyz.a
Sory my english is bad. I'm using visual code, my project is c++, -L./libs/curl/lib include only libcurl.a, that is static lib When I build project with this link option, everything is ok: LDFLAGS = -static -L./libs/curl/lib -lcurl -lssl -lcrypto -lsqlite3 -lpthread -ldl -lz But when I use this link option: LDFLAGS = ...
By default gcc or g++ will link against some standard libraries. The list of these libraries is architecture dependent, but you find libc libgcc and some others. To see the list of libraries used for the link you can add -v option. You will see the list of libraries passed to collect2. Since you are compiling for x86_6...
64,681,976
64,682,631
Problem using hash map to find the first unique element in a string in c++
int firstUniqChar(std::string s) { //Using maps to find the first unique character of the string int string_len; int pos; std::unordered_map<char, int> m{}; string_len = s.size(); for (int i = 0; i < string_len; i++) { //if the char in string is not present in map, then add to the map w...
What you are returning is the first element of an unordered map. That element being first has nothing to do what is the first unique element of the string. What you should do instead is once you have calculated the frequencies, iterate the string again and return the first character with frequency of 1. P.S. If you ca...
64,682,157
64,683,167
Why am I getting a race condition?
I'm trying to combine multiple CGAL meshes into one single geometry. I have the following sequential code that works perfectly fine: while (m_toCombine.size() > 1) { auto mesh1 = m_toCombine.front(); m_toCombine.pop_front(); auto mesh2 = m_toCombine.front(); m_toCombine.pop_front(); bool result = C...
Instead complicating things check capability of standard library: std::reduce - cppreference.com Triangle_mesh_exact combine(Triangle_mesh_exact& a, Triangle_mesh_exact& b) { auto success = CGAL::Polygon_mesh_processing::corefine_and_compute_union(a, b, b); if (!success) throw my_combine_exception{}; return...
64,683,374
64,683,704
Getting segmentation fault (core dumped) error when declaring a int variable
I was trying to create vector like class. Here is my code #include <bits/stdc++.h> using namespace std; template<class t> class vec{ t *start; int size=0; public: void add_value(t a){ *(start+(sizeof(t)*size)) = a; cout << (start+(sizeof(t)*size))<< " = "<< *(start+(sizeof(t)*...
You probably want something like this: #include <iostream> using namespace std; template<class t> class vec { t* start = new t[100]; // initialize the pointer (fixed size of 100, to be improved) int size = 0; public: void add_value(t a) { *(start + size) = a; size...
64,683,833
64,684,104
Why the do\while loop is breaking and Terminal is hanged?
I have the following code and it somehow verify if the input is number, but the error occurs while looping back to ask the user for the second time to enter the number. I can't figure it out. #include <iostream> #include <limits> using namespace std; void botVarification(); void userDecision(); bool isHuman(string hu...
$ clang++-7 -Wall -o main main.cpp main.cpp:23:39: warning: variable 'humanInputvalidator' is uninitialized when used here [-Wuninitialized] for (int humanInputvalidator; humanInputvalidator < hum... ^~~~~~~~~~~~~~~~~~~ main.cpp:23:37: note: initialize the variable 'h...
64,684,031
64,684,055
In C++, how do I pass a 32 bit number into an 'int' variable without anything above 0x7FFFFFFF being considered negative?
I need to have an int variable go up to 4294967295 (0xFFFFFFFF), without using unsigned and long, so it can actually be used by other functions. Is that even possible?
You can't, unless you find a platform with an int that's larger than 32 bits (they are at the time of writing rare). If you need to use a signed type, then std::int64_t is a good choice. Or long long is also guaranteed to be large enough. If you're absolutely constrained by the interface to your function then you coul...
64,684,190
64,684,451
How does "while(getline(cin, name))" controls an unknown number of lines of queries?
In a problem of HackerRank there is a condition to take an unknown number of lines of queries. The problem's link is: Day 8: Dictionaries and Maps I couldn't be able to solve the problem for every test cases, but I looked at the solutions and found that people are using while(getline(cin, name)) to control an unknown n...
std::cin is an input stream. std::getline reads a line from std::cin and writes it to name. It returns the equivalent of true if this has no errors, false otherwise. The while loop therefore reads lines until it fails or is broken out of. You can force a fail with std::cin.setstate(std::ios_base::failbit);, or break ou...
64,684,449
64,684,622
How secure are string values?
Take the following program: #include <string> #include <iostream> constexpr std::string correct_pin = "1874"; std::string response; int main() { std::cout << "Enter a pin."; std::cin >> response; if (response == correct_pin) { std::cout << "That is the correct pin!"; } else { std:...
Yes, 1874 would be stored in memory and in the executable. You could use a cryptography library to salt and hash the correct pin and store the salt and hashed value. In the past I have used crypto++. This would be almost impossible to try and figure out the original value by working with the hashed value, they would ha...
64,684,484
64,685,971
Best way to find difference between two values in a cyclic system?
Take for example time: if we have the starting hour and ending hour, what's the best way to find the number of hours between them? If we take a 12-hour clock, we'd get the following results from 1 to 5 = 4 from 11 to 1 = 2 What is the most efficient way to do that?
Assuming input already in range 1-12, you might do return b - a + (b < a) * 12; benchmark showing a 2 times performance gain over cigien's solution.
64,684,599
64,684,809
trouble with switch block variable in c++
I have an assignment for a class I'm taking where I have to use a switch block to allow the user to select a shape and then determine the area for the shape. below is the (likely unnecessarily long and complicated for what this assignment is) code for this switch statement. C++ is new to me, and so right now my issue i...
Declare shape as an 'int' will solve the problem
64,684,954
64,685,261
Sorting 2 arrays row wise using quick_sort
I'm given 2 arrays, one that contains first names and another that contains last names. So far, I've been able to sort the last names alphabetically while retaining the corresponding the first name. The problem I have are with the duplicate last names. My goal is to first sort the last names, then if a group of people ...
Your code is pretty much correct , You will need to update your compare function to something like this . int compare(string last1, string last2, string first1, string first2) { if(last1 == last2) return first1 < first2; else return last1 < last2; } Here first last names are compared if they they are s...
64,685,001
64,748,378
embed video stream with custom meta data
I have an optical system that provides a UDP video stream. From device specification FAQ: Both single metadata (KLV) stream and compressed video (H.264) with metadata (KLV) are available on Ethernet link. Compressed video and metadata are coupled in the same stream compliant with STANAG 4609 standard. Each encoded vid...
The quote sounds like you have a transport stream containing two elementary streams (the H.264 video in one, and the KLV data in another). The transport stream is sent over UDP (or TCP, or is just a file, whatever you want - its mostly independent of the transport). There is a discussion of implementing this kind of th...
64,685,211
64,685,295
Problem with printing copy constructor OOP
Having trouble with the printing copy constructors elements from Arr s to Arr s1 , also having troubles with << operator it doesn't work, please help cuz I am not pro just a student. #include <iostream> using namespace std; class Arr { private: int size; int *arr; public: Arr(int size,int *arr) { th...
You are writing this->arr = x.arr; in the copy constructor, rather than this->arr[i] = x.arr[i]; That is, currently your code is copying the array pointer, not the elements of the array. When you're debugging, first look over your code to make sure each part is doing what you want it to do and that you didn't make a ...
64,685,409
64,685,950
Rule of five for derived classes
I've been trying to understand how "rule of five" should be written for a derived class. Only thing I found online was how it should be written for base class. So given following class A how should it be written for class B? class A { int a; std::vector<int> k; int *z; public: int getA() const {return a;} st...
For the derived class, you can reuse the base part of the copy and move constructors/assignment operators defined in the base class and only add what's added in the derived class. Before I show that, I've made a few corrections to the base class since it doesn't actually move anything. I also recommend not implementing...
64,685,491
64,685,600
Template template parameters and "<<" operator (ostream)
For several days I have been trying to understand template template parameters. I tried to write an example using C++17 in Visual Studio, but I get this error: Error C2679 binary '<<': no operator found which takes a right-hand operand of type 'std::vector<int,std::allocator<int>>' (or there is no acceptable conve...
std::vector is a template with more than 1 template parameter, so for functioon or operator<< to accept it as a template template parameter, that template template parameter itself needs to accept a variadic number of template parameters: template<typename T, template<typename ...> typename Tpl_Type> ...
64,685,531
64,712,332
Decimals as keys for unordered_map
I've often heard that you're not supposed to use float values as keys in an unordered_map or hash tables. For my use case, I have float values that are guaranteed to only be up to the hundredths in decimal value. As these decimals come in, I would like to count the number of times they appear. I only need ~90% accuracy...
From what I understand, you want to create an histogram. Using a map for a histogram is a waste of resources. A simple array, or vector, is more than enough, will work fine to this task, and will always be more efficient than a map. constexpr const float hist_bin_width = .01f; // change to wanted resolution. // becau...
64,685,621
64,686,316
C++ Convert one exact string element into an int
I want to create a string array and then after writing lines into it I want to change one exact character into int. I already know that all the characters are going to be numbers. As my goal is to change the one character at a time, options like atoi, stoi etc. are perhaps off? The closest I got is that: #include <iost...
In your loop: for (int i = 0; i < n; ++i) { for (int j = 0; j < 11; ++j) { i = str[i][j] - '0'; std::cout << i; } } you are modifying outer loop variable i (looks like for the purpose of printing a value). Given an unfortunate input, you would go out-of-bounds fast.
64,685,750
64,685,834
How to check two vectors of different types for equality
I have two vectors, a, b, of structs abc and abc2 respectively: struct abc { const int &data; abc(const int& cdata) : data(cdata) {} }; struct abc2 { const int& data; abc2(const int& cdata) : data(cdata) {} bool operator== (const abc& c1) const { return (c1.data == data); } }; int mai...
There is a standard algorithm for comparing equality: std::equal. In this case assert(std::equal(b.begin(), b.end(), a.begin(), a.end()));
64,686,680
64,686,744
Why when I am using file.peek() in C++ do I get a number rather than the char?
In most of my code, the in.peek() works as getting whatever the next char is supposed to be. However, when it is reading some symbols, it returns a number rather than the char, and I am not sure how to fix it to get the symbol I want. The text file reads: print "Good morning!!"; but during the " char I use file.peek(...
peek returns an int (to account for possibility of eof()). To make sure cout recognizes it as a char, you can cast it (though this will produce incorrect values if you did hit EOF), e.g.: cout << "hit " << ch << " " << static_cast<char>(in.peek()) << " " << temp << endl;
64,686,786
64,686,836
Will Calling clear() on a vector of lists clear all the nodes in the list at each index?
I am creating a hash table that has a private data member vector<list<pair<K, V>>> hashTable;. My understanding is that a rehash function should assign the elements of the original table to a temp table, empty the original table, resize it, the hash the elements of the temp table back into the original table. Will an a...
The convention for types in C++ is to have copy semantics, and std::vector, std::list and std::pair all adhere to this. Therefore vector<list<pair<K,V>>> tempTable = origTable; does a 'deep copy', and no reference to the old data is kept. And similarly calling .clear() on such a vector will destroy all used memory.
64,686,903
64,687,021
Extracting from set/unordered_set while using iterators
I just learned about the extract function added to std::set/std::unordered_set in C++17. I know this is valid: while (!my_set.empty()) { auto node_handle = my_set.extract(my_set.begin()); auto elem = std::move(node_handle.value()); } But is the following safe? (From https://stackoverflow.com/a/42519996/3234803) fo...
But is it guaranteeed that extract doesn't invalidated other iterators? Yes. Extract is guaranteed to not invalidate other iterators. Both loops are safe.
64,687,003
64,687,069
In command line arguments why can't we use string *arr instead of char **arr
Why does this work int main(int argc, char **argv) { cout << argv[1] << "\n"; } but not this int main(int argc, string *argv) { cout << argv[1] << "\n"; } isn't a string just a char*? Why can we use the first but not the latter? What is the difference between char** and string*
In command line arguments why can't we use string *arr instead of char **arr You could if your compiler supports such parameters for main. But the language standard doesn't require supporting such parameters, and I know of no compiler that does. So, you cannot use that because your compiler doesn't support it. What ...
64,687,023
64,687,712
What happens to unassigned `Eigen::VectorXd` object following a call to `segment()`?
I have a class Foo that stores Eigen MatrixXd and VectorXd of matching dimensions and offers a simple function .mult() that performs matrix-vector multiplication. And I have a function that calls mult(), takes a segment of the returned vector, and does some further computation. Here is a simplified version of the code:...
What you are doing is save (but inefficient). f.mult() returns a Eigen::VectorXd object by value which exist for the rest of the statement ("until the next ;"). So calling segment() on it is safe, as long as you store that result into a VectorXd (and not into an auto object). To get a segment of a matrix-vector product...
64,687,107
64,687,195
How do I create a list of objects in c ++ and use its methods?
I created this class and I need to use a for (iterator) to enter the values, they will not necessarily be i, any other value, for that I need to use a list: #include <iostream> #include <list> using namespace std; // 1ra clase base class Person { int e; public: Person(int); void printDates(); }; Person::Perso...
The problem is that list does not provide an index into the container. persons[i] // does not work for list (though it does work for vector). So you need to use an iterator. Older versions of C++ this is done like this: for(auto loop = persons.begin(); loop != persons.end(); ++loop) { loop->printDates(); } In mod...
64,687,630
64,688,005
Passing a variable through parameters and modifying it later in the class
How can I store a variable in a class, and modify it later in program flow? For example: bool bGlobalStatus = false; class foo { public: foo(){} ~foo(){} void InitGlobalBool(bool &var) { // I can change the value here, but I want to store the variable and modify it later. // var = !v...
I think you want to do something like this: bool bGlobalStatus = false; class foo { public: bool *mVar{}; foo(){} ~foo(){} void InitGlobalBool(bool &var) { mVar = &var; } void Update() { *mVar = !(*mVar); } }; int main() { foo Foo; Foo.InitGlobalBool(bGloba...
64,687,657
64,687,694
How much memory is allocated in heap using new operator?
int main() { int ptr* = new int[10]; } I wonder if in heap is allocating 10 * 4 bytes (40), and for the pointer also is allocated 8 bytes, or the whole line allocates only 40 bytes. If for the pointer is allocated memory then 8 bytes are allocated in stack? I am not sure but I think that for the ptr is allocated 8...
You meant int* ptr = new int[10]; Space for at least 10 ints is allocated (the C++ runtime library and operating system might actually allocate more memory than this, but of course you have no portable way of observing that). That's 10 * sizeof(int) bytes. On common current desktop systems that is indeed 40 bytes. That...
64,687,824
64,689,223
How to separate message zmq server?
I am trying to send a video through a ZeroMQ server and I successfully got it with a 1 GB video, but when I try to send a movie with, with a very larger size ( 6.7 GB ) I get the following error: cliente: /usr/local/include/zmq.hpp:1958: zmq::recv_result_t zmq::detail::socket_base::recv(zmq::message_t&, zmq::recv_flags...
Q : "How to separate message zmq server?" Well, avoid attempts to move 6.7 GB at once. Doing a sndmore-trick to send that huge volume of data as a multi-part structured message does not save the problem, as such a structured message will (almost) never fit into RAM-constraints. Best setup an indexing data-reader, mov...
64,687,936
64,688,037
Accessing Each Node in a list that is an index in a vector
I am currently making a hash table by using a private data member vector<list<pair<K, V>>> hashTable;. I need to access each list, and in turn, each pair for various different functions. I am currently doing so like: for(int i = 0; i < hashTable.capacity(); i++){ list<pair<K,V>>* listPtr = hashTable[i]; for(pai...
The simple way to access each pair on each list is for (const auto& list : hashTable) { for (const auto& pair : list) { ... } } but the insert function in the code above worries me. If you are iterating over the vectors/lists while you are simultaneously modifying them, that changes things.
64,688,354
64,688,646
Pointer to a std::vector object(s)
I need to do the following: std::vector<std::string> A; std::vector<std::string> B; ==> pointer_to_vector<std::string> ptr; //Some Code ptr = A; //ptr points to object A //Some More Code ptr = B; // //ptr points to object B During the program, ptr needs to refer to both A and B at different times. How would it...
You define a pointer to a vector the same way you define a pointer to any other type - using * in the pointer declaration, and the & address-of operator to get the memory address of a variable to assign to the pointer, eg: std::vector<std::string> A; std::vector<std::string> B; std::vector<std::string> *ptr; //Some...
64,688,451
64,688,506
function pointer in C++ in bisection method
I have a function my_func(), which takes 2 parameters a and b. I want to define a function inside the solve_for_b_by_bisection() function, called f, such that I can just call f(b), which is my_func(a, b) for some fixed input a. How do I do that? Do I use a function pointer? The reason I am doing this instead of calling...
You might use lambda: auto func = [a](double b) { return my_func(a, b); };
64,688,716
64,688,829
Is Aws GetObject downloading all the data into memory or to a file cache?
Here is a method to access a file from S3: GetObject(...) returns Aws::S3::Model::GetObjectOutcome Aws::S3::Model::GetObjectOutcome has GetResultWithOwnership().GetBody() method to return Aws::IOStream I wonder if that Aws::IOStream is a string stream to memory where whole file was downloaded to, or a stream to a file ...
Yes, it downloads all the body into memory and uses stringbuf. There is a method how to download avoid loading all the file to memory: https://docs.aws.amazon.com/sdk-for-cpp/v1/developer-guide/configuring-iostreams.html Example from that page in case the link is removed: GetObjectRequest getObjectRequest; getObjectReq...
64,689,186
64,689,366
Use default value of Subclass method in an array of Base class
Is there any way that cout << a[0]->function(); can give a 5 instead? At the moment, it takes the default value of the base class and runs the method of the subclass. But I want it to run the method of the subclass and take the default value of the subclass. class Basis { public: virtual int function(int i = 1) { r...
Your code is calling function() via a Basis* pointer, so it is going to use the default value defined by Basis, there is no way for Sub to override that. Calling function() via a Sub* pointer would use the default value defined by Sub instead. So, given the code you have shown, the easiest way I can think of doing wha...
64,689,241
64,697,202
Having a constructor causes an error “error: no operator "=" matches these operands”
So, I have a struct mesh which holds a std::vector of triangles which holds vectors. template <typename T> struct genericVec3d { T x = 0, y = 0, z = 0, w = 1; //////constructors genericVec3d() {}; genericVec3d(T _x, T _y, T _z, T _w) :x(_x), y(_y), z(_z), w(_w) {}; genericVec3d(T _x, T _y, T _z) :x...
You need more {}'s, because what you are doing just now is creating a vector with a single triangle, and that triangle is trying to set 3 variables when there is only 1 (the array). // what you have sheet.tris = { // vector of triangles { // triangle 1, // meant to be array of vf3ds, but it'...
64,689,368
64,689,717
C++ Increase Atomic Float
I have a std::atomic<float> that I would like to increment by a certain value. However, using fetch_add() on an atomic<float> does not compile and does not seem to be allowed. Is there anyway I can get around this? Here is the code snippet I tried: std::atomic<float> data(0); void do_work(){ data.fetch_add(1); } The e...
Floating point atomics are only supported by the C++ library in g++ 10.1 and later. See https://gcc.gnu.org/onlinedocs/libstdc++/manual/status.html and search for P0020R6. Your code compiles fine with g++ 10.2: Try on godbolt
64,689,521
64,689,626
Setting bits on cpp_int
Silly question but, does setting bits on a cpp_int from the boost library work the same as normal numbers? For instrance, I tried to set some bits on a number like so: vector<bool> bits; //contains 000000000000011010001100101110110011011001101111 cpp_int M = 0; int k = 48; for(bool b : bits) M ^= (-b ^ M) & (1UL << k--...
Probably unsigned long is 32 bit on your system. Thus the first masks generated with (1UL << k--) with k-- being 48 to 32 are not what you expect (it's undefined behaviour). You can fix this by using a larger type, like unsigned long long, like M ^= (-b ^ M) & (1ULL << k--);. If you have more than 64 bits, you can prob...
64,690,136
64,704,662
Can you get an explicit skeleton out of a gltf file?
For debugging purposes I want to render the skeleton of a skinned mesh. However, in glTF they seem to be defined in a very abstract way. That is to say, there is no "skeleton" as in, a set of vertices connected by lines. In other words this is not explicitly defined: Instead the "skeleton" is actually a collection of ...
I'm sure you're not looking for a "mostly" or "kinda-sorta" answer here, but indeed there are some complicating factors. I'll start with the basic strategy: glTF is a last-mile format, a GPU-ready format designed to get data pumped into rendering APIs with minimal fuss. As such, glTF has no compassion for "artist ass...
64,690,385
64,690,420
Switch to execute same function for all cases along with single print statement for one of them
I have a switch case where for all cases the same function is to be executed, however for one of the cases I would also like a print statement to be printed. I understand that to execute the same function for all cases you do something like this: switch(caseType) { case A: case B: case C: case D: ...
You would have to re-arrange your cases, so that the "special" one is on top - and then fall through: switch(caseType) { case E: printf("CASE E\n"); // no break; here, fall through case A: case B: case C: case D: printf("Your case type = %s\n",caseType); break; defaul...
64,691,111
64,691,499
Frustrating Math Problem, results not as expected (EDQ)
Here is my code, throttle comes out to -18 when I run the program, and when I do the math I get 77.941... which is what I'm looking for. I know this is an EDQ "Extremely Dumb Question", and I am most likely to experience a FIF, "Fist In Forehead" moment any minute but I am stuck on it for now. FYI, programming it on an...
The short answer is, (800 - 270) * 100 = 53000. which is too large a number for the space that was allocated for the calculation results, integer overflow. so changing the code from this... int throttle = (((800 - 270) * 100) / 680); to this... long largeValue = 100; int throttle = (((800 - 270) * largeValue) / 680);...
64,691,438
64,691,518
What's wrong with my power function which takes 2 as base, n as exponent and computes answer modulo 10^9+7?
My code: int power(int n) { int num = 1000000007; if (n == 0) return 1; if (n%2 == 1) { int storage = power((n-1)/2); return (2*storage*storage)%num; } int storage = power(n/2); return (storage*storage)%num; } I have used exponentiation by squaring to make it more e...
storage * storage may overflow int value sometimes, e.g. if storage is 2^30 then storage * storage is 2^60 which will be truncated to int to fit into 2^32 but you want full-size computation otherwise you'll get wrong remainder. Use int64_t for intermediate results, like in code below: Try it online! #include <cstdint> ...
64,691,593
64,691,623
Cannot Overload + Operator in Class C++
I am trying to overload the addition operator. #pragma once #include <fstream> #include <iostream> class ComplexNumber { private: int* real; int* imag; public: ComplexNumber(); ~ComplexNumber(); ComplexNumber(const ComplexNumber&); ComplexNumber& operator=(const ComplexNumber&); friend std::...
Just dereference your real/imag pointers by * operator, like in code below. Alternatively maybe you just need to store them as plain int (e.g. int real;) instead of pointers to int. Try it online! #include <fstream> #include <iostream> class ComplexNumber { private: int* real; int* imag; public: ComplexNum...
64,692,638
64,692,739
Overload operator for different template parameters
#include <cstddef> template <typename T, std::size_t MaxElements> struct circular_buffer{}; template <typename circular_buffer> bool operator==(const circular_buffer &a, const circular_buffer &b) { return true; } int main() { circular_buffer<int, 2> a; circular_buffer<int, 3> b; a == b; return 0;...
Following might work for you: template <typename T, std::size_t M1, std::size_t M2> bool operator==(circular_buffer<T, M1> const & a, circular_buffer<T, M2> const & b) { // some meaningful logic return true; }; Problem you have is that a and b are of different types, i.e. those two objects have different MaxEl...
64,693,065
64,693,145
Separate class declaration from definition
I would like to separate class definition and declaration into 2 separate files: foo.hpp and foo.inl. foo.hpp file has Foo class declaration with its' description, and also this file includes foo.inl: /* foo.hpp */ // Foo class description comment class Foo; #include "foo.inl" foo.inl contains Foo definition without...
Foo::Foo(); and void Foo::bar(); area member function declarations, and those are not allowed outside of a class. You have it a little bit backward, define the class in the "main" header file foo.hpp. Then define the functions as inline in the "inline" header file foo.inl. Perhaps something like this: // Foo.hpp #pragm...
64,693,293
64,693,882
How to properly include header C++ files (from ALGLIB) in Matlab MEX files
I am struggling to get a mexfunction in MATLAB to work from C++ file. Below you can find my code first the mex file to compile and call and a header and the corresponding cpp file. And now I have 2 questions: A basic question; that code compiles and runs, but normaly I have learned to include the header files #include...
Well actually the solution is to compile all cpp files that you will possibly use according to the command in Matlab, having all files in the same folder: File = 'cSpl_CPP.cpp'; % Mexfunction list = dir('**/*.cpp'); % Collect all cpp files cppfiles = {list.name}; % Gather file names cppfiles(find(strcmp(cppfiles,File))...
64,693,866
64,693,952
C++ assignment operator during declaration
This is my class Hero with two overload assignment operators - Hero to Hero and String to Hero. #include <iostream> class Hero { private: int x; std::string name; public: Hero():x(42), name("JohnDoe") {}; Hero(int a, std::string b):x(a), name(b) {}; void print(){ std::cout<<na...
When initializing an object at definition, it's not using assignment even when the = syntax is used. When you do: Hero zak = foo; it's equivalent to: Hero zak(foo); Which is copy-initialization and as such invokes the copy-constructor. The problem with Hero bar = "HelloWorld"; is that it's equivalent to: Hero bar =...
64,694,218
64,694,337
How to express concepts over variadic template?
I'd like to define a concept which just tuples with values of a specific type can satisfy. Let's say for simplicity I just want to accept tuples just holding elements of a numeric type. How would I do this? e.g. std::tuple<int16_t, int32_t> // satisfies concept std::tuple<std::string, double> // doesn't satisfy concept...
Simply enough: namespace impl { template <class T> struct is_tuple_of_integrals : std::false_type { }; template <std::integral... Ts> struct is_tuple_of_integrals<std::tuple<Ts...>> : std::true_type { }; } template <class T> concept tuple_of_integrals = impl::is_tuple_of_integrals<T>::valu...
64,694,269
64,696,349
Getting uWebSockets for Visual 2017 via Conan
I'm trying to add uWebSockets as a dependency in my conan.txt conan install .. returns the following error: ERROR: uwebsockets/18.3.0: Invalid configuration: uwebsockets requires a compiler that supports at least C++17 How can I handle this ? The error comes from https://github.com/conan-io/conan-center-index/blob/ma...
By default, Conan settings supports Visual Studio versions as integer numbers only. Passing -s compiler.version=15.9 returns an "invalid" error It complains because your custom version, it is not listed in settings.yml, however you can add your version there, there is section explaining how to customize your settings...
64,694,431
64,694,761
Motion After Rotation In Sdl C++
Here are my functions: void main_loop(){ SDL_Surface* image; image=SDL_LoadBMP("plane.bmp"); plane=SDL_CreateTextureFromSurface(renderer,image); double angle=90; int speed=1; SDL_Event event; bool quit=false; while(!quit){ while(SDL_PollEvent(&event)!=0){ if(event.type==SDL_QUIT) quit=true; ...
int angle_rad=angle*PI/180; Your radians are being stored in an integer, so they will get truncated to the nearest whole number. Store them in a float or a double instead.
64,694,977
64,695,026
How the ++ operator of the const_iterator works for vector<string> in C++ standard library?
String size is not fixed. How they made iterator knows where to point to after the increment? #include <iostream> #include <string> #include <vector> using namespace std; int main() { vector<string> myVector{"ABC", "DEF"}; for (auto p = myVector.begin(); p != myVector.end(); ++p) cout << *p << endl; }
In fact, sizeof(std::string) is fixed. The actual string data (which is not of fixed size) is stored elsewhere in memory, and the std::string object only contains a pointer to it. So an iterator over std::vector<std::string> can simply advance by sizeof(std::string) bytes at a time.
64,695,297
64,696,293
basic insertion sort in linked list with logic problem (maybe it is because pointer)
I write a code for insertion sort for integer data in linked list in c++, I referred to the algorithms on the Internet, and finally took the following code using array as a basic concept for my version. however, the sorting always ignore my first element,(but all the other element is ordered well). I have tried checkin...
One of the most important difference between a linked list and an array is that it is sometimes required to handle the first element as a special case. Here is a fixed version of your sorting method : void insertionSort() { bool breakByCompare; Node* keyptr; Node* judgeptr; int key; for(keyptr = lis...
64,696,022
64,697,854
Visual Studio tries to link against nested library dependency of static library
I have a executable project, Game.exe, which is linking against a library Engine.lib. I want to link another internal library, Video.lib, into Engine.lib, so that Game.exe can simply link against Engine.lib and not worry about the symbols provided by Video.lib. This sort of linking setup makes the most sense for my cur...
The issue turned out to be with the library I was using specifically, which is wxWidgets (I simplified the example above in order to avoid complications). wxWidgets uses #pragma comments to link specific libraries in. In this case, wxWidgets ("Video.lib") was causing Game.exe to "see" these pragma comments and ultimate...
64,696,036
64,696,918
Why is QAudioRecorder not recording through the constructor?
header #ifndef AUDIORECORD_H #define AUDIORECORD_H #include <QMediaRecorder> #include <QAudioRecorder> #include <QUrl> class AudioRecorder : public QAudioRecorder { Q_OBJECT public: AudioRecorder(QObject * parent); ~AudioRecorder(){} }; #endif // AUDIORECORD_H source #include "audiorecord.h" #include<...
Cause What would be if I tell you 10 000 times: Go buy some milk, while firmly holding your hand, then just before I let you go to say: Ah, forget it? Would you be able to buy the milk? You are doing the same with your code: int x = 0; while ( x > 10000) { this->record(); x++; } this->stop(); You are calling ...
64,696,104
64,700,339
Deadlock avoidance by ordering std::mutex
Is there a portable implementation of the deadlock avoidance logic here (see the section marked `NON-PORTABLE'): #include <cstdint> #include <iostream> #include <mutex> #include <thread> typedef long Money; //In minor unit. class Account { public: bool transfer(Account& to,const Money amount); Money get_balan...
tl;dr - you can make your original pointer comparison portably in C++20. I'd probably wrap that code into a scoped_ordered_lock or something though, because the code is still a bit hairy. The assumptions are (and I believe sufficient – anyone?) that intptr_t exists and that the relational operators on intptr_t imply ...
64,696,190
64,696,263
How to dereference pointer object in C++?
I am getting error while running this? cout << *head << endl; Why we cant dereference Object pointer? Like wise we do in int data type: int obj = 10; int *ptr = &obj; cout << *ptr << endl; //This will print the value 10 by dereferencing the operator! But not in object why? #include <iostream> using namespace std; cl...
The fact that you're dereferencing a pointer is a red herring: std::cout << N1 << endl; will not compile for the same reason. You need to implement std::ostream& operator<<(std::ostream& os, const Node& node) for (at global scope) your Node class, which in the function body you'd write something along the lines of { ...
64,696,203
64,696,799
Creating objects from a retrieved row from Sqlite database
This is a C++11 program that connects to an Sqlite database, using the SqliteModernCpp library. There is the following class, which represents a record from this database (at least, the header file): #ifndef MOVIE_H #define MOVIE_H #include<string> class movie { public: movie(int id, std::string title, in...
This seems too easy as you already have solved the hard part (untested code) auto id = 1; movie idmovie db << "SELECT * FROM movies WHERE rowid = " + std::to_string(id) >> [&](int rowid, std::string title, int year, int length) { idMovie = { rowid, title, year, length }; }; You might be able to shorten that to aut...
64,696,689
64,696,727
Check if file exists using StreamReader
I open this file to read data, but if file doesn't exist it throws error. So how can I check if file exists? In console project I can use ifstream, where I can check it by writing if(!file) {}, and StreamReader doesn't allow me to do this. StreamReader^ data = gcnew StreamReader("data.txt");
You need to read the documentation. The exception thrown is FileNotFoundException if the file cannot be found.
64,697,790
64,701,551
SFINAE: 'enable_if' cannot be used to disable this declaration
I want to enable and disable a function declaration in a template class, just based on if the template parameter has one type defined or not for which I use boost/tti/has_type.hpp. However, I got the complains from compiler, i.e., 'enable_if' cannot be used to disable this declaration. #include <boost/tti/has_type.hpp>...
if I change it to similar non-member function template, it works. The point is: funtion template. Your code doesn't works because SFINAE works over templates, with test related to the template parameter. Your contains() method is a function, inside a template class, but isn't a template function. To make SFINAE works...
64,697,798
64,697,852
How to model a vector of non-owning raw pointers extracted from unique_ptrs?
Note: Apologies if the title is unclear, I don't quite know how to express the issue in proper terms (improvement suggestions are very welcome). Code, onlinegdb example of the working version and example of the non-working one first to simplify the explanation: #include <iostream> #include <vector> #include <memory> c...
You're already doing the right thing. A raw pointer is a perfectly reasonable way to model something with unknown or lacking ownership. You're not storing the vector anywhere, so there is no confusion and no risk. The only problem here really is that you've had to regenerate the entire vector, which seems like a bit of...