question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
61,982,188
61,982,522
How to understand `std::make_shared<Object>("foo")`?
What does std::make_shared<Object>("foo") do? std::shared_ptr<Object> p1 = std::make_shared<Object>("foo"); I know that std::make_shared<T> is template class and I could understand Object("foo") is a temporary object indeed. But I could not understand std::make_shared<Object>("foo"). Can someone explain me, step by st...
std::make_shared<Object>("foo") method Notice the std::make_shared at the start of this code. It identifies a function. If we put the actual function aside and step back a little, then before the <> signs and the () sign you have a function name. generic The in this code specifies that the generic T is specified in t...
61,982,696
61,982,753
How to make c++ using cin optional?
I want to allow user to input three strings from the keyboard. For example, firstname, lastname and middle name. The middle name is optional. The code sample below: cout << "Enter your name, first name then middle name and last name (Ex: Abby Scuito S): "; char lastName[21], firstName[21], middleName[21]; cin >> lastNa...
Read the data into a single string and separate them by space. You may have to do some filtering, but you'll get the idea.
61,982,901
61,985,207
How do I know on which cache level my array is stored?
I understand, that spatial and temporal locality have an enourmous impact on performance. What I don't understand is how my data structures are stored in these caches? For simplicity, assume the L1 cache has 8 bytes, the L2 16 and the L3 32 bytes. Does that mean that if we have: std::array<double, 1> x = {1.}; std::a...
You are thinking about the caches the wrong way. You can only see which cache has them with special tools (intel debugger comes to mind) and the results will be specific to your run and architecture. Changing the processor can break your setup fairly easy. That said you can try to have use solutions that are cache frie...
61,982,969
61,983,116
How to use protected type inheritance in class?
#include<iostream> #include<string> #include<cmath> using namespace std; class Polygon { public: Polygon() {} Polygon(int point, float length) { mPoint = point; mLength = length; } ~Polygon() {} virtual void calcPerimeter() { cout << "Perimeter: " << mLength * mPoint; ...
You're right about being able to use protected data in the derived class. However, that's not the problem here. In Rectangle (int point, float length): mPoint (4), mLength (4 * length) {} you are initializing the fields, and that can only be done once, in the initializer list of the constructor of the class in which t...
61,983,237
61,983,420
How to enable a friend class's friend function access its private members directly in C++
I'm writing a sparse matrix class, and I want to output the sparse matrix by overloading operator<<. I'm wondering how to enable a friend function of SMatrix (operator<<) directly (not by some interface) access private data members of TriTuple? Note that SMatrix is meanwhile a friend class of TriTuple. See code as fol...
[class.friend]/p11: If a friend declaration appears in a local class ([class.local]) and the name specified is an unqualified name, a prior declaration is looked up without considering scopes that are outside the innermost enclosing non-class scope. For a friend function declaration, if there is no prior declaration, ...
61,983,601
62,010,089
Math to calculate line thickness on triangulated line strings
I am creating my own 2D paint engine that is able to stroke and fill paths. I am having trouble with the corners of line segments connecting. The way I do it is calculate the normal of each line segment and in the corners, I use the average normal of the two adjacent edges. To calculate the vertices for the thickness o...
I used ripi2's answer to switch from trying to get the correct normal length to calculating the intersection points of the extruded edges and clipping the lines to that intersection point. And that actually works! Although Beta's answer might be better as it looks less computationally intensive. I might look into that ...
61,983,736
61,983,817
Shouldn't `typename` only be used in template function or template class?
Shouldn't typename only be used in template function or template class? Why the expresion below is legal?What's the function of typename in the expresion below? #define DECLARE(T) using Request = typename T::Request; I would be grateful for any hint on this question.
This is to allow using such expression in a macro (like mentioned in the original post). Macro cannot know if it is used with template type argument or not, but has to work in both. Since typename is required when working with a template, it makes sense to allow it in non-template code (where it can be ignored). Your o...
61,983,866
61,983,957
How to write the code of a function outside the class? c++
I am new in c++ and i am learning classes and objects. In the class I have defined a function, and I want to write the code of it out od the class. I think it shoud be something like this: #include <iostream> using namespace std; class student{ public: string name; int mark1, mark2; float ...
return_type class_name::member_function_name(parameters) { //action } In Your Case: float student::calc_media(int x, int y) { float media = (x + y)/2.0; return media; } In your class change this cout << "Media:"<< calc_media(int, int) << endl; To cout << "Media:"<< calc_media(mark1, mark2) << endl;...
61,983,875
61,984,146
Why this for loop always show 'o's.C++
Here I have written a code that contains a struct (vectors). I've used a for loop display the data inside the structure. I think something is wrong with the for loop. Could you guys correct me out. #include <iomanip> #include <iostream> #include <string> #include <vector> using namespace std; struct coffee { string...
You can use brace initializers to make it easier: int main() { int coffeetype = 1; vector <coffee> coffee_drink = {{ "Espresso", 120, "Italy", 20 }, {"Iced coffee", 150, "France", 20}, {"Long black", 80, "Austral", 20}, {"Americano", 100, "America", 20}, {"Latte", 200, "Italy", 20}, {"Irishcoff...
61,984,263
61,984,815
Migrating preprocessor configuration definitions to constexpr without memory bloat
Better late than never: I am trying to update my code bases to recent C++ standards, right now trying to really understand the intentions of the constexpr syntax feature. However, I am struggling with this: In one of my microcontroller projects (plain C++ without some of the higher level std features), I have a configu...
You can always use a tool like godbolt to see what the compiler creates. And if you check the result for this setup you will see that the compiler will generate the same output for #define and costexpr, if you solely use them as constants, even with no optimizations turned on: #include <iostream> #define DEFINE_CONST ...
61,984,390
61,984,944
See reference to function template instantiation message when catch std::exception in Visual Studio 2019
I've noticed an annoying message during a build of C++ console application in Visual Studio 2019, Windows 10. I have a template function which produces a message: message : see reference to function template instantiation 'int run_loop<wchar_t>(int,const char_type *[])' being compiled with [ char_type=w...
This compiler messages does not stand for its own, it accompanies another message. Given your code the complete output is warning C4100: 'argv': unreferenced formal parameter message : see reference to function template instantiation 'int run_loop(int,const char_type *[])' being compiled with [ ...
61,984,407
61,984,530
How to create Makefile for multiple files in multiple directories?
Good morning, I new in c++ and I am trying to compile my simple code to executable form. I will explain structure of project. - main.cpp - /utility/server.h - /utility/server.cpp I enclose file sources for complete information. main.cpp #include <iostream> #include "utility/server.h" using namespace std; using namesp...
In server.cpp, here: namespace server { static char* get_domain() { return getenv("SERVER_NAME"); } } You have made char* server::get_domain() a static function, making its definition visible only within this translation unit and invisible to the linker. Remove the keyword static here, and also in serv...
61,984,412
61,984,540
Recursive lambda C++17
I have the following situation, I have a class with functions which looks like this: void GetTest(int id, std::function<void(Test)> cb); void GetTest2(long id, std::function(void(Test2)> cb); The cb method will be called after the method is done which will run in the background, the order of execution of the CB method...
You should specify the return type of the lambda: template <typename T, typename T2> void QueryList(std::vector<T2> list, std::function<void(std::shared_ptr<std::vector<T>>)> finalCallback) { std::shared_ptr<std::vector<T>> ret = std::make_shared<std::vector<T>>(); auto callback = [this, list, ret, finalCallba...
61,984,642
61,985,011
Rotating the player model to point towards a point
I have seen the post from three years ago asking a somewhat similar question about how to achieve this with glm::lookAt, but couldn't quite apply it to my game. I have a camera and player model moving on a curve. This is done by calculating points on the curve and simply moving the player there with glm::translate (ide...
Assuming you have a position and a targetPoint. You can define an upVec and compute the axis of the rotation matrix by the Cross product as follows: glm::vec3 upVec(0, 1, 0); glm::vec3 z_axis = glm::normalize(targetPoint - position); glm::vec3 x_axis = glm::normalize(glm::cross(upVec, z_axis)); glm::vec3 y_axis = glm:...
61,984,728
61,985,200
Performance and security in C++ when avoiding use of pointer
I'm trying to create a class in C++ with an idea of absolute encapsulation and efficiency for the sake of practice. In my case this means every data member is supposed to be inside the class with no pointers pointing outside (e.g. to dynamically allocated storage). For example, I'm using char name [10]; instead of st...
access to the stack is considerably faster than to the heap This is false: an access to memory is an access to memory. Two things might have confused you here. First, it is true that different types of memory can be accessed at different speeds. For example, the disk is usually the slowest (without talking about netw...
61,984,958
61,985,361
C++ program bad output
// Example program #include <iostream> #include <stdio.h> using namespace std; int a(){ int formula = 20/30; return formula; } int d(){ return a(); } int main() { cout<< d() <<endl; return 0; } I have a program code above. For some reason program output is 0, but it should be 0.6
The problem is with the data type that you have used (i.e. int). Checkout Corrected code (Because int can't store floating point numbers you need to change it to some other data type): // Example program #include <iostream> #include <stdio.h> using namespace std; float a(){ float formula = 20/30; return formul...
61,985,030
61,985,222
Passing an class type as a constructor argument C++
I am trying to learn c++ when I stumbled on a error. I have this class that inherits from the class PERSON. #include <iostream> #include <string> class PERSON { private: std::string name; bool sex; public: PERSON(std::string name, bool sex) : name(name) , sex(sex){}; //methods }; class TEACH...
A CLASSROOM is not a kind of TEACHER so I think don't really want to derive CLASSROOM class from TEACHER class. Once the above is corrected, you can then write the constructor as follows: class CLASSROOM { private: std::string name; TEACHER lecturer; TEACHER s_teacher; public: CLASSROOM(std::string nam...
61,985,085
61,985,408
How can I detect off-by-one errors (OBOEs) in C++ code?
Consider this simple program: #include <array> #include <iostream> #include <cstdlib> int main(int argc, char* argv[]) { std::array<int, 5> arr = {0, 1, 2, 3, 4}; int idx = std::atoi(argv[1]); int val = std::atoi(argv[2]); arr[idx] = val; for (auto i=0u; i <= idx; i++) { std::cout << "arr[...
Why doesn't the off-by-one case throw an error? Because -fsanitize=undefined doesn't detect out of bounds accesses. Can you suggest any other tool that can reliably detect out of bounds access by one element? I suggest gcc with -fsanitize=address. $ g++ -O0 -std=gnu++14 -fsanitize=address 1.cpp $ ./a.out 6 98 ===...
61,985,709
61,985,802
Given solution using Bitmask, I am unable to understand the evaluation of condition as marked in code
I an unable to understand the bit masking used here, the given code is a solution of finding no of palindrome paths in a binary tree which contains digits 0-9 inclusive. I have marked the line in code with in a if statement. This is the question of LeetCode contest. Question is as given: Pseudo-Palindromic Paths in a B...
count & (count - 1) == 0 If count is a power of 2, this statement is true. Example: Count = 8 00001000 = 8 & 00000111 = (8-1) = 7 ------------ 00000000 = 0
61,986,337
61,986,373
Easiest implementation of Graph in cpp
Currently I am learning graph implementation. I found 2 implementation namely matrix and adjacency list using vector in cpp. But the problems I face are following With matrix Passing to function is hard Adding new nodes is not possible memory inefficient Vector implementation of adjacency list // Code taken from geek...
I have efficient and easiest implementation of graph in cpp. It solves all problems you mentioned above. It is called as vector in vector. // Suppose at start we have // number of nodes int nodes = 5; // number of edges int edges = 4; // define graph vector<vector<int>> graph(nodes, vector<int>()); int u, v; // edge...
61,986,839
61,986,915
Const has no effect when passing class member by reference in c++
Consider the following code: #include <iostream> class ObjectCalculator { public: struct Object { int id = 0; }; void setObject(Object& object) const { object.id = 1; } Object m_object; }; int main() { ObjectCalculator objCalc{}; std::cout << objCalc.m_object.id << std::end...
const related to the members of the class. You modifying the method argument, so it can be changed, regardless of const. const after method applied to the implicit first method argument this, through which all class members accessed. cppreference A non-static member function can be declared with a const, volatile, o...
61,987,042
61,987,264
About std::unique_prt() and decltype()
What doesstd::unique_ptr<std::FILE, decltype(&close_file)> fp(std::fopen("demo.txt", "r"), &close_file); mean ? I konw std::uqiue_ptr is an unique pointer. But i could not understand the entire expression. Could anybody do me a favor? void close_file(std::FILE* fp...
Given void close_file(std::FILE* fp) { std::fclose(fp); } decltype(&close_file) is void(*)(stdFILE*) (function pointer). You can provide custom deleter to std::unique and it is what is done here: std::unique_ptr<std::FILE, decltype(&close_file)> fp(std::fopen("demo.txt", "r"), ...
61,987,147
61,987,252
How I can output a constant text in struct when call cout?
I have this struct: struct sample { int x; }; and then I have this overload of operator<<: std::ostream &operator<<(const std::ostream &os, const sample &s) { if (s.x == 0) return os << "zero"; else return os << "not zero"; } main: int main() { sample sam; sam.x = 0; std::cout << sam << std::endl;...
You are right except for a small error in your operator signature: std::ostream &operator<<(const std::ostream &os, const sample &s) // ^^^^^ Problem You mark the output stream as const but then modify it inside the function: os << "zero"; and os << "not zero"; Because std::basic_ostream<CharT,...
61,987,220
61,987,517
Pass Array to Recursive Function While Modifying It C++
I have a recursive function that takes a 2D array as a parameter in C++. The contents of this 2D array are to be unique among all recursive calls of this function. I would like to modify this array each time before I make the recursive call. How can I do this without modifying the array for both of the 2 recursive cal...
C-array cannot be copied, std::array can :) So I would use std::array. a[2][2] = 5 mutates array, whereas i - 4 doesn't mutate integer i (so nothing to discard in that case, contrary to f(i -= 4)). there are no operator on array which allows easy customization, we can create function or lambda for that: // pass by valu...
61,987,423
61,988,167
c++ class template partial specialization without specializing all member functions
let's say I have a class X<'T, N'>, which has a few functions defined and I want also class X<'T, 3'> to have them all, but also a few additional functions (a real life example would be a Vector<'T, N'> and Vector<'T, 3'> would have all Vector<'T, N'> functions, but could also implement rotation in 3D space) template <...
In my experience use inheritance method (2) when you actually want a new class that inherits from the template. Use method (1) when the partial specialization is sufficiently different from the general case or general case is not defined at all and you just declare a bunch of partial specializations to make use of SFIN...
61,987,600
61,990,138
Write Eigen VectorXd in CSV format
I'm trying to write an Eigen::VectorXd to a CSV file. The vector is from a row of an Eigen::MatrixXd. My function is defined as follows: void writeMatrixToCSVwithID(fs::path path, VectorXd row, unsigned long int row_id){ const static IOFormat CSVFormat(StreamPrecision, DontAlignCols, ", ", "\n"); ofstream file(...
The cause of the error is that Eigen outputs VectorXd as a column. MatrixXd::row(id) returns Block which seems to output either a row or column extract as a column! Thus, rather than passing the VectorXd row, I now pass the row as a MatrixXd. The IOFormat object is initialised with the row separator as ','. void write...
61,987,624
61,989,037
Should I make my local variables const or movable?
My default behaviour for any objects in local scopes is to make it const. E.g.: auto const cake = bake_cake(arguments); I try to have as little non-functional code as I can as this increases readability (and offers some optimisation opportunities for the compiler). So it is logical to also reflect this in the type sys...
I believe it's not possible to move from a const object, at least with a standard move constructor and non-mutable members. However, it is possible to have a const automatic local object and apply copy elision (namely NRVO) for it. In your case, you can rewrite your original function as follows: Cake helper(arguments) ...
61,987,625
61,987,825
C++ Array of Derived Classes
I am currently working on a problem that requires a few concepts to be tied together. I first define a class "Base" which uses the CRTP (see https://www.modernescpp.com/index.php/c-is-still-lazy) to achieve run-time polymorphism. I then define two derived classes of Base called "Derived1" and "Derived2" as examples of ...
CRTP is used for static polymorphism. If you need runtime polymorphism, there are many ways of achieving that. Virtual member functions with classic OOP inheritance is only one way. From the excellent "Embrace no Paradigm Programming!", we can see other ways we can do it and how they compare to each other: If you're o...
61,987,787
61,989,042
How to overload a comma operator to assign values to an array
So I've got the following code: #include <map> #include <iostream> using namespace std; template<class V, unsigned D> class SparseArray { public: map<string,V> data; SparseArray(){} class Index { private: int dims[D]{}; public: int& operator[](int index) { ...
How do I implement the comma operator so that obj = 1, 2, 7 will do the exact same thing as doing obj.arr[0] = 1; obj.arr[1] = 2; obj.arr[2] = 7;? This would completely change the meaning of comma operator. I will prefer initializer list: obj = {1, 2, 7}; over the usage of comma operator in this scenario. I know ...
61,987,828
62,004,848
How to Access Subgraphs of an Existing Graph in Boost
I have read a graph with read_graphviz() and know the graph contains subgraphs. However, I cannot find where the Boost documentation covers how to access said subgraphs. All I can find is create_subgraph(), which obviously does not access existing subgraphs. What am I missing? Thanks in advance
The documentation lists these member functions that aid in subgraph traversal/navigation: subgraph& root() Returns the root graph of the subgraph tree. bool is_root() const Return true if the graph is the root of the subgraph tree, and returns false otherwise. subgraph& parent() Returns the parent graph. std::pair<chi...
61,987,838
61,988,185
Is private within this context? Trying to overload << operator
#include <cctype> #include <deque> #include <iostream> #include <string> #include <vector> #include <iomanip> #include <list> #include <limits> class Song { friend std::ostream &os(std::ostream &os, const Song &s); std::string name; std::string artist; int rating; public: Song() = default; Song...
operator<< is a regular function, and your overload is trying to use private members of the class. In a class, the default access is private, if you want public access by default, you should use a struct. There are two ways to solve your issue: 1.) Write your operator<< overload to only use public data/functions: std:...
61,988,168
61,992,522
why got segmentation error in my program?
ERROR: type should be string, got "https://www.hackerrank.com/challenges/gridland-metro/problem\nThis is the link to the question in hacker rank.\n#include <bits/stdc++.h>\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n int n, m, k;\n scanf(\"%d%d%d\", &n, &m, &k);\n int tot = n * m;\n vector<vector<int>> track;\n\n for (int i = 1; i <= n; i++) {\n track[i][0] = INT_MAX;\n track[i][1] = INT_MIN;\n }\n\n while (k--) {\n int r, c1, c2;\n scanf(\"%d%d%d\", &r, &c1, &c2);\n\n if (track[r][0] > c1 && track[r][1] < c2) {\n if (track[r][0] == INT_MAX && track[r][1] == INT_MIN) {\n track[r][0] = c1;\n track[r][1] = c2;\n tot -= c2 - c1 + 1;\n } else {\n tot -= (track[r][0] - c1) + (c2 - track[r][1]);\n track[r][0] = c1;\n track[r][1] = c2;\n }\n } else if (track[r][0] <= c1 && track[r][1] >= c2) {\n tot -= 0;\n continue;\n } else if ((track[r][1] > c1 && track[r][0] < c1) && track[r][1] < c2) {\n c1 = track[r][1] + 1;\n tot -= c2 - c1 + 1;\n }\n }\n\n printf(\"%lld\", tot);\n}\n\nThis is my code for the question and I am getting segmentation fault in this. PLz tell me the right way of doing this program because I guess my code is brute force one if it was made correct \n"
This may help you, however you have to change your approach of thinking : 2 reasons of segmentation fault : As others have told , you have to first allocate memory/initialize the vector. It automatically does not know what size to take. In your question the value of n , m < = 10^9, if you allocated memory containing t...
61,988,357
61,988,571
C++ elegant way for prioritized search in STL container
I wrote a small function whose aim is to go through a list of elements in order, do some checks on the hashmap value of it and if they pass, return it. QString ElementContainer::getPreferedAvailableElement() const { QStringList preferred_priority = { A, B, C, D, E }; foreach(QString element, preferred_priority)...
You can use std::find_if like this: QString ElementContainer::getPreferedAvailableElement() const { QStringList preferred_priority = { A, B, C, D, E }; auto it = std::find_if(preferred_priority.begin(), preferred_priority.end(), [this](const QString & element) { Element* data = m_hashmap.v...
61,988,477
61,989,327
Overloading constructor with 2 same datatype members
lets say i have a class with two std::string member and one int value, like: class DataGroup final { public: explicit DataGroup (const std::vector<int>& groupNr, const std::string& group1, const std::string& group2) : groupNr(groupNr) ...
There are several way to have expected behavior: Named constructor class DataGroup final { public: // ... static DataGroup Group1(const std::vector<int>& groupNr, const std::string& group) { return DataGroup{groupNr, group, ""}; } static DataGroup Group2(const std::vector<int>& ...
61,988,582
61,988,702
Why am i getting this error when i compile my code in devc++?
I want to pass address of object e but I am getting this error: D:\Timecal1\timecal.cpp In function 'int main()': 101 9 D:\Timecal1\timecal.cpp [Error] invalid initialization of non-const reference of type 'entry&' from an rvalue of type 'entry*' 97 7 D:\Timecal1\timecal.cpp [Note] in passing argument 1 of 'void m...
1 - The prototype declaration void menu(entry&); must be outside the main function. 2 - menu has a reference parameter, it means that whatever variable you pass it, it will take a reference to the variable, not a copy of it like normally, so you just have to pass the variable. If you pass the variable with the addres...
61,988,847
61,988,962
Sorting char pointer using STL sort()
Anyone knows how to sort a char* using std::sort() STL function? In c++ If i use sort like sort(str.begin(),str.end());. An error is coming -'request for member begin and end in str, which is of non-char type 'char*'. I know how to sort a string using std::sort() in #include<algorithm>
If you have a pointer to the beginning of a string, you can pass it directly to std::sort as the first parameter. Then the second parameter needs to be the pointer to end of the string. You can get it by adding string length to that pointer. std::sort(ptr, ptr + std::strlen(ptr));
61,989,067
61,999,485
parsing GLTF buffer with Qt
Here's the situation. Let's say I have a gltf file containing : "uri" : "data:application/gltf-buffer;base64,AAAIAAcAAAABAAgAAQAJAAgAAQACAAkAAgAKAAkAAgADAAoAAwALAAoAAwAEAAsABAAMAAsABAAFAAwABQANAAwABQAGAA0AAAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAQAAAAAAAAAAAAABAQAAAAAAAAAAAAACAQAAAAAAAAAAAAACgQAAAAAAAAAAAAADAQAAAAAAAAAAAAA...
you tried it like that?)) QByteArray by = QByteArray::fromBase64("AAAIAAcAAAABAAgAAQAJAAgAAQACAAkAAgAKAAkAAgADAAoAAwALAAoAAwAEAAsABAAMAAsABAAFAAwABQANAAwABQAGAA0AAAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAQAAAAAAAAAAAAABAQAAAAAAAAAAAAACAQAAAAAAAAAAAAACgQAAAAAAAAAAAAADAQAAAAAAAAAAAAAAAAAAAgD8AAAAAAACAPwAAgD8AAAAAAAAAQAAAgD8...
61,989,158
61,990,008
Does raising by too small double result in 0.0? If not, how to achieve this?
I am dealing with floating point very small in magnitude and would like to round to 0 whenever the floating point cannot be represented by a double because it is too small in magnitude. This code: #include <iostream> #include <cmath> int main() { double x{100.0}; double y{(-1.0) * 1.7976931348623157e308}; double...
Do expressions that result in a floating point too small in magnitude to be represented by a double always evaluate to 0 Not necessarily. The result depends on the rounding mode. For example, if FE_UPWARD is used, then you would get a very small non-zero result - assuming rounding modes are supported by the language ...
61,989,414
62,006,779
CMake - Could NOT find Boost (missing: serialization) (found version "1.73.0"
I've been using Boost with my project for a while now, though until now, I'd only used the header-only libraries. I now want to use serialization, but when I try to add serialization as a REQUIRED component, I get the error written in the title. Here is my CMAKE file: cmake_minimum_required(VERSION 3.15) project(GinRum...
I ended up using a C++ package manager called vcpkg to install Boost:x64-windows, and Boost and the appropriate components were properly found after that. The instructions for how to install it can be found here: https://github.com/Microsoft/vcpkg After installing it, 64 bit Boost can be installed with the following co...
61,989,754
61,997,652
error C2039: 'fabs': is not a member of '`global namespace''
My project compiled well, even with full rebuild, then I modified a single parameter in a dialog resource and now it doesn't compile even changing back the parameter, I have many errors, beginning with that: 1>C:\Program Files\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.25.28610\include\cstdlib(24,18): erro...
As the problem ocured after I modified the resource and I found that fabs was not declared because of _CRT_FUNCTIONS_REQUIRED not set to 1, I checked my resource.h file (comming from the original project) and saw that many definition lines where set and one containing #define _CRT_FUNCTIONS_REQUIRED 0. I commen...
61,989,982
61,990,058
Troubles converting double to LPARAM
I am trying to make my first Windows Desktop Application (have used exclusively console until now). This is probably a real noob problem. I am making something for work that receives serial data from remote test equipment and logs/displays the data for trend analysis. I am having no trouble getting the data from the re...
Convert double to string and cast string pointer to lparam: double d_number; wchar_t buffer[30]; swprintf(buffer, 30, L"%g", d_number); SendMessage(hwnd, WM_SETTEXT, NULL, (LPARAM)buffer);
61,990,153
61,992,168
Use derived class methods with unique_ptr to base class
I have a Base class and a multiple Derived classes (with their own .h and .cpp files) looking something like this class Base { // Base stuff } class Derived : public Base { public: derivedOnlyFunc(); } class SecondDerived : public Base { public: derivedOnlyFunc2(); } In my main file I have a vector o...
Dynamic cast is what generally what you want for this kind of pattern if (auto der = dynamic_cast<Derived *>(object.get())) der->derivedOnlyFunc(); else // is not a Derived
61,990,238
61,990,351
How to overload operator + with the parameters of a class?
I am learning about overloading operators in c++ and I have done this code aboout the sum of two imaginary numbers, formed by the real part and the imaginary part. #include<iostream> using namespace std; class Complex { private: int real, imag; public: Complex(int r, int i) { real = r; i...
The way you have defined operator+ is fine, expect that it needs to be a friend function. Also, note that Complex res; will not compile because you don't have a default constructor. You could define the function like this: friend Complex operator + (Complex const &num1, Complex const &num2) { return {num1.real + nu...
61,990,650
61,991,152
Text not appearing in the compiled window while using fltk
I am going through the book "C++ programming principles and practices". I am learning how to use fltk (Chapter 12) and I have managed to install the library and compile the programs. I can draw basic shapes and color them,change the line texture used to draw them, however, the problem is that I cannot get text to appea...
Ah, The problem was solved. Turns out the default font size for text is way too small to be visible to the naked eye. I had to increase the font size of the text by using the function "set_font_size" and the text became visible again.
61,990,687
62,012,531
Extra space at the beginning/end of .text section
I'm looking for a way to reserve some extra space at the begining/end of the .text section from C/C++ using Visual Studio compiler. I've only found one solution on how to reserve some extra space in code section in Visual Studio: PE File .text Section Size #pragma optimize( "", off ) #define NOP __asm { NOP } ; #define...
With VS 2019 the following reserves 4K at the beginning and end of the code segment, respectively. #pragma section(".constext", read) #pragma section(".xonstext", read) #pragma comment(linker, "/merge:.constext=.text") #pragma comment(linker, "/merge:.xonstext=.text") extern "C" __declspec(allocate(".constext")) const...
61,990,971
61,991,146
Why don't I need to specify "typename" before a dependent type in C++20?
This bit of code compiled in C++20 (using gcc 10.1) without using the typename keyword before the dependent type std::vector<T>::iterator. Why does it compile? #include <vector> template<typename T> std::vector<T>::iterator // Why does this not require "typename" before it? f() { return {}; } int main() { auto fp...
One of the new features in C++20 is Down with typename. In C++17, you had to provide the typename keyword in nearly all† dependent contexts to disambiguate a type from a value. But in C++20, this rule is relaxed a lot. In all contexts where you need to have a type, the typename keyword is no longer mandatory. One such...
61,991,148
61,991,215
Implicit conversion to comparison function object (functor) for std::sort but not std::map?
I have been using std::sort with a function as comparison function. The function is implicitly converted to a functor (by GCC). I tried the same when declaring a std::map type, but this fails. Compiling with g++ -Wall -Wextra -std=gnu++14 -pedantic: #include <map> #include <algorithm> #include <vector> struct S { int ...
You seem to be mixing up types and values. The third argument to std::sort is a value, the third argument to std::map is a type. using MyMap = std::map<const S*, Payload, bool (*)(const S* const&, const S* const&)>; is prefectly legal. Then you could write MyMap my_map(compare); PS there's no implicit conversion to a...
61,991,232
62,009,593
C++/WinRT UWP - HRESULT 0x80073D54 : The process has no package identity
I'm working with C++/WinRT for UWP. I am trying to create a file, but an exception is thrown at line 11 : #include "pch.h" using namespace winrt; using namespace Windows::Foundation; using namespace Windows::Storage; IAsyncAction createFile() { try { StorageFolder local{ ApplicationData::Current().Loc...
The issue here is with ApplicationData::Current(). https://learn.microsoft.com/en-us/uwp/api/windows.storage.applicationdata.current?view=winrt-18362 The API to get current application information is based on the identity of the application. Any Windows App can have identity (it doesn't have to be a UWP), but it must b...
61,991,470
62,010,546
How to flip image vertically using Boost::GIL
I'm trying to generate an image icon. Based on some restrictions, I need to get a one-dimensional array of int32_t pixel values ​​in order {r, g, b, a, r1, g1, b1, a1, ...}. In this case, the order of the rows should be the same as with OpenGL UV (bottom to top). For this, I used the following, verified, it works: cons...
You can use a flipped view to do the transform: #include <boost/gil.hpp> #include <boost/gil/algorithm.hpp> #include <boost/gil/dynamic_step.hpp> #include <boost/gil/extension/io/jpeg.hpp> #include <boost/gil/extension/io/png.hpp> namespace bg = boost::gil; int main() { bg::rgba8_image_t v; bg::read_and_conve...
61,991,554
62,008,707
'wx/wx.h' file not found when compiling hello world wxWidget program on mac
I have just installed the latest stable version of wxWidget on my mac and tried to compile the code from the hello world tutorial. This is the code that is causing the error: #include <wx/wxprec.h>' #ifndef WX_PRECOMP #include <wx/wx.h> #endif My compiler throws the following warning: hello_world.cpp:4:10: fatal error...
I found out the answer to this problem. To fix it I used the following line to compile/build the hello world app: g++ `wx-config --cxxflags` -o out *.cpp `wx-config --libs` after doing this it was only a matter of sorting out the linking, adding header guards and adding in IMPLEMENT_APP(MyApp) and DECLARE_APP(MyApp)...
61,991,569
61,991,704
Best way to move from unordered_map with unique_ptr values
I have a map like this std::unordered_map<std::string, std::unique_ptr<V>> map; I want to eventually run a function on all the remaining V in the map, so I do the following: for (auto&& [_, v] : map) { func(std::move(v)); } This works, but I've been naively assuming the compiler would ignore the key values, since t...
In the C++ standard, [stmt.ranged] specifies that a range-based for loop has equivalent semantics to a certain ordinary for loop. In your case, this is: { auto &&__range = map ; auto __begin = __range.begin() ; auto __end = __range.end() ; for ( ; __begin != __end; ++__begin ) { auto&& [_, v] = ...
61,991,648
62,001,798
C++ OpenGL wrapper: interface similar to fixed pipeline, can export .collada
I have opengl code that uses the fixed pipeline. Hitting two birds with one stone, I need a wrapper that can help me with the following tasks: Convert the code to the new shader-based pipeline with minimal effort. I have a class that calls opengl functions, such as: glBegin(triangles/lines), glVertex, glPushMatrix, gl...
Although there are some parts in legacy OpenGL that are not optimized in current drivers (like glDrawPixels, the raster drawing operations and indexed color mode), between modern hardware and the modest requirements of legacy applications, legacy OpenGL stuff runs well enough on modern systems. The main reason to "mode...
61,992,005
61,992,276
Partial template specialization for constructor
I need a class which looks like this: template<typename T, class S, size_t C> class myClass { public: myClass(); // Ctor /* */ private: S myData; } Where T is type of stored data, S is a container type and C is it's size. Methods won't depend on a container type, but I still need to properly initialize ...
You cannot partial specialize a method, you could partial specialize the whole class, but require some duplication. As you can use C++17, you might tweak the implementation instead: template<typename T, class S, size_t C> myClass<T, S, C>::myClass() { if constexpr (std::is_same_v<S, std::vector<T>>) { // sp...
61,992,243
61,992,436
Can you instantiate the unspecialized version of a template and inherit from it inside the specialization?
I am trying to define a Vector as a row/column Matrix. Vector needs some methods which Matrix doesn't have, so I specialized Matrix: template<typename T, unsigned N, unsigned M> struct Matrix { T data[N][M]; }; template <typename T, unsigned N> struct Matrix<T, N, 1> : public Matrix<T, N, 1> { T at(unsigned in...
You can use SFINAE to disable method. It's necessary to have template method with template argument dependent on the class template parameter. C++11: #include <type_traits> template<typename T, unsigned N, unsigned M=1> struct Matrix { T data[N][M]; template<typename V = T> typename std::enable_if<M == 1...
61,992,431
61,992,487
In C++, why is mentioning the type of the pointer necessary?
In C++, mentioning the type of pointer is necessary. For example, int a = 5; int * p = &a; Here, 'int' in the 'int *' was necessary. The reasons I found are that its needed for dereferencing.(Knowing no. of bytes to read, and their interpretation) and Pointer Arithmetic. However, if I write:- int a = 5; char * p = &a;...
If you declare b as auto, the compiler will use type inference and determine the type itself. But if you use a specific type, it has to be the correct one.
61,992,442
61,992,632
Solving a modular exponentiation with unknown power
Guys I what is the fastest algorithm to solve a modular equation in the format of a^b = c mod p where p is a really big prime and b is unknown. e.g.: 2^k = 15 mod 30903154482632612361920641803533 I already tried trial and error using boost library in C++ but it would take very long time to reach the answer.
You're trying to solve what is called a discrete logarithm. If there was an efficient solution to this, I imagine whoever discovered it would wreak chaos on cryptographic systems long before it would be posted here. You will find quite a couple of algorithms on Wikipedia with varying time complexity. Some of these are ...
61,992,562
61,992,653
error: reference to non-static member function must be called when starting a thread
I have this code that works. void MediaRecorder::sendData(int timeslice) { using namespace std::literals::chrono_literals; while (!s_finished) { requestData(); std::this_thread::sleep_for(5s); } } ExceptionOr<void> MediaRecorder::startRecording(Optional<int> timeslice) { ... ...
For a non-static member function, the thread constructor needs the address of the member function, as well as an object pointer: ExceptionOr<void> MediaRecorder::startRecording(Optional<int> timeslice) { // ... std::thread th1 (&MediaRecorder::sendData, this, timeslice.value()); // ... }
61,992,682
61,992,875
Need help locating the reason for "Segmentation fault" in this piece of C++ code
I have the following code #include <cstdio> #include <cmath> #include <vector> #include <iostream> #include <sstream> #include <string> int main() { int NoOfArr; std::cin >> NoOfArr; std::vector<std::vector<int>> VecOfVecs; for(int i = 0; i <= NoOfArr; ++i) { int x; // Add all elements ...
You need to add std::cin.ignore (); after std::cin >> NoOfArr;. std::cin >> NoOfArr; does not remove the end-of-line character from the input stream, which means that the next call to getline returns an empty string. In consequence, vector temp is empty and so temp.begin() passes an invalid iterator to temp.erase(). T...
61,992,789
61,992,839
When and how are thread_local variables initialized and destroyed?
I'd like to better understand thread_local before I use it in my code. Let's say, I declare thread_local myclass value; That will create new instance of myclass for each thread that is using the value? What happens when the thread exits? Will the instance be freed or is it going to remain somewhere in the memory? When...
[basic.stc.thread]/1 All variables declared with the thread_local keyword have thread storage duration. The storage for these entities shall last for the duration of the thread in which they are created. There is a distinct object or reference per thread, and use of the declared name refers to the entity associated wi...
61,993,125
61,993,489
How do you access each shape/object individually in SFML for C++
I'am looking for a way to make multiple clickable rectangle shapes appear on the users screen using SFML. The code that i wrote only works for the last initialized shape and changes the color for all of the squares. #include <SFML/Graphics.hpp> #include <iostream> using namespace std; int main() { sf::RenderW...
As suggested in the comments, you create only one RectangleShape and then change it's position. Probably better idea would be to create array of shapes with predefined positions at the begining of your code like this: std::vector<sf::RectangleShape> shapes; for (int i = 0; i < 10; ++i) { for (int j = 0; j < 10; ++j...
61,993,198
61,999,441
Keep only the good keypoints panoramic images stitching opencv
I am working on a project regarding the matching of consecutive images in order to find the panoramic image. I found the keypoints with SIFT and the matches between couple of images using BFMatcher, but after removing the bad matches I am not able to keep the corresponding keypoints, or even to display the matches usin...
I edited some parts that I will mark in the code. I would not recommend the data structures you are using, since it is very hard to read them. Consider creating typedefs or structs when you have multiple vectors of vectors. I used ORB since I did not install SIFT at the moment. Here is an example for three images: int...
61,993,271
61,993,861
cin gives garbage if the size is smaller than the receiver array
uint8_t data[252]; cout << "> " << flush; cin >> data; cin.clear(); If the user writes less than 252 chars, the data is padded with some garbage values. How can I prevent that?
Just initialize your array to set the value of all index 0 and that way you won’t be getting garbage values. uint8_t data[252]{};
61,993,298
61,993,400
qt Program crush with segmentation fault while switching cental widget
I tried maybe everything but I just don't see a mistake in this code. I made two windows inherited from QMainWindow: one with qt designer and another just in constructor. I'm trying to switch these windows in the MainWindow class depending on what buttons you press. LoginWindow.cpp LoginWindow::LoginWindow(QWidget *p...
From the documentation of QMainWindow::setCentralWidget: Note: QMainWindow takes ownership of the widget pointer and deletes it at the appropriate time. The widgets that logWindow and regWindow point to start life unowned. Then you call goToReg(), which calls setCentralWidget(regWindow) - now the main window owns *re...
61,993,300
61,993,324
Do I have to do something special to make a file a resource file in QT C++?
Basically I have an image I'm trying to use as a splash screen. I set up the splash screen and even told it the location(":/Nuclear_Vortex_100_About.jpg") but when I run the program, all I see is a general window background "window"(no close box or any of the decoration, just a widget for lack of a better word) and no...
create resource file (.qrc) and add picture in it. It'll appear in resources section of your project. Then you can use it freely in your program.
61,993,566
64,280,047
WAV writing function can't sync after writing to stereo
I'm trying to use the following function to create a 2-channel stereo .wav file from an interleaved input buffer. The function works fine when slightly modified to write to a 1-channel mono file, but in its current state it returns an exception thrown error: void audiowrite(double* inputBuffer, int bufferLength, int fs...
My best guess and the classic mistake with this function is that inputBuffer is too short. When you use sf_writef_double the unit of the third argument is a frame (i.e. sample*nb_channels). From documentation: For the frames-count functions, the array is expected to be large enough to hold a number of items equal to t...
61,993,632
61,997,362
Can you pass in complex types into Parameterised Tests with Google Test?
When passing values into a Parameterised Test using Google Test: INSTANTIATE_TEST_SUITE_P(InstantiationName, FooTest, testing::Values("meeny", "miny", "moe")); is there anyway to construct more c, such as a vector, before passing them into testing::Values?
You can pass many different types to the parametrized types, e.g. vector: struct VectorTest : public testing::TestWithParam<std::vector<int>> {}; TEST_P(VectorTest, MyTestCase) { auto expectedVector = std::vector<int>{42, 314, 271, 161}; ASSERT_EQ(expectedVector, GetParam()); } INSTANTIATE_TEST_CASE_P(VectorI...
61,994,124
61,994,281
Why is std::erase(std::erase_if) not a template in <algorithm> that works on any container?
std::erase(_if) is a nice addition to C++20(finally I can forget about obnoxious erase-remove idiom), but one thing is weird: it is not a generic algorithm in a sense that it only works for std:: containers, e.g. it can not operate on boost vector. #include<string> #include<vector> #include<boost/containe...
This is answered in the original proposal, N4009: Q10. Instead of overloading erase_if() for each container, should you provide a single erase_if(Container&, Predicate) function template that's specified to do the right thing for each container? A10. Such a general function template could be given user-defined c...
61,994,338
61,994,385
C++11: are 16-byte atomic<> variables automatically aligned on 16-byte boundaries allowing CMPXCHG16B instruction?
Are 16-byte atomic<> variables automatically aligned on 16-byte boundaries allowing the compiler/runtime libraries to efficiently use the x86 CMPXCHG16B instruction? Or should we as a matter of style always manually specify alignas(16) for all such variables?
Any decent implementation of std::atomic<> will use alignas itself to make lock cmpxchg16b efficient, if the library uses lock cmpxchg16b at all instead of a mutex for 16-byte objects. Not all implementations do, for example I think MSVC's standard library makes 16-byte objects fully non-lock-free using the standard mu...
61,994,436
61,994,581
Inconsistent value returned from C++ function vs Python function for skew normal distribution
I have a function to estimate the alpha parameter from the skew normal distribution in C++ and Python. The Python function is written using NumPy and the C++ function uses the STL. My issue is that my C++ implementation is giving me incorrect results. The two functions are essentially identical but the Python version g...
You're using a lot of integer numbers in what I can only assume to be intended as floating-point operations. Lines such as double numerator = std::pow(skew_, (2 / 3)); will resolve into double numerator = std::pow(skew_, 0); Because 2 / 3 in integers simply gets floored down to 0 If you want to make sure that th...
61,994,573
61,995,322
C++ style: Stroustrup' s placement of pointer asterisks
Does anyone know why Stroustrup's style is the placement of pointers as follows? Specifically, what Stroustrup has provided for guidance about this matter? int* p; vs int *p; because declaring multiple variables would require the asterisk next to each variable name. Which would result in: int* p, *x; vs int *p, *x...
C++ emphasis heavily on types and when it comes to pointers declaration, to avoid any sort of confusion, Bjarne suggested - Stick to one pointer per declaration. From Bjarne Stroustrup's C++ Style and Technique FAQ [emphasis added]: Is int* p; right or is int *p; right? Both are "right" in the sense that both are vali...
61,994,746
61,994,886
Why does this function without a type still work?
Why am I not getting an error even if I declared a function without a type? If the return type is accepted as some types by default, is it healthy to write codes like this? If it already works like this with a compiler feature, then why would we even need to write void for functions? Note: I am using Code::Blocks that ...
In C++ it's wrong to declare a function without a type in accordance with ISO C ++, but you can ignore this error using the "-fpermissive" flag. Your compiler is likely to use this flag to ignore standard coding errors downgrading them to warnings. You should always use at least the void type when declaring functions s...
61,994,870
62,482,599
Possible to Tie Keyboard Input to a Single Application in Win32?
I have a rather unusual Windows project for a client that has led me to believe that what we're trying to accomplish may not be possible. We're at a point where we would like to have the application listen for input from a proprietary keyboard device and process it. This application runs in the background and always li...
After some additional testing, blocking with a WH_KEYBOARD hook was only partially reliable. It did not work with the newer-style Windows Store applications or higher-level ones, even after moving the DLL and adjusting the permissions as I have read from others. Furthermore, it would often miss out or get duplicate hoo...
61,994,927
61,994,946
brace-or-equal-initializers initialization order
If using brace-or-equal-initializers, what's the initializing order of member variables? Are they initialize the same as code order? struct foo { int x = 1; int y = x + 1; } bar; Will bar.y always be 2 regardless of the compiler?
Yes, y is guaranteed to be initialized after x. Non-static data members are always initialized in order of their declaration in the class definition, regardless of how they're initialized (by member initializer list or default member initializer, even default initialization). 3) Then, non-static data member are initia...
61,995,191
62,007,304
QT: DirectShowPlayerService::doSetUrlSource: Unresolved error code 0x8007007b ()
I am using Qt Version 5.14.1. When I was trying to play a video(.mp3), the program stopped working And given error is DirectShowPlayerService::doSetUrlSource: Unresolved error code 0x8007007b () AudioPlayer::AudioPlayer(QObject *parent) : QObject(parent) , m_backgroundMusic(NULL) //QMediaPlayer * m_backgroundMusic { ...
Your path in QUrl::fromLocalFile(":/music/8bitDungeonLevel.mp3") appears to be off, AFIK there is no (at least not common) path naming scheme that uses : to begin paths. UPDATE: I was told that :/ refers to resources that have been compiled into a Qt application, I think using the Qt Resource Compiler (rcc)
61,995,342
62,003,746
C++ OPENCV 4.3.0 x64 Why face_cascade throws error?
I am using OpenCV to add a face recognition feature to my C++ program. I have never used it before and I cant seem to get the cascade feature for facial recognition to work. I am wondering if they have made some changes for the FLAGS in the new version. I can display an image but when that comes to the cascade it alway...
I modified the code as: /*... OTHER CODE ...*/ std::vector<Rect> faces; cvtColor(img, img_gry, COLOR_BGR2GRAY); equalizeHist(img_gry, img_gry); face_cascade.detectMultiScale(img_gry, faces); for (size_t i = 0; i < faces.size(); i++) { /*...PARSE...*/ } imshow("Display window", img); As @SourceCode mentioned :...
61,995,377
61,995,512
Is it safe to write "y=++x" when using c++ atomic?
If I have 2 threads and in main function, I init a variable x like this std::atomic<int> x=0;, In thread 1 I do this: while(true){ x++; } And In thread 2 I do this: y=++x; my question is that:is there any possibility that variable y can get the wrong number? I mean for example: if in thread2,at that moment,x=2;then...
If the concern is that in y=++x value in x equals to 2 first, then increased to 3 by ++x, then increased by another thread again before copying to y, then answer is no - this can't happen. Result of operation ++x is not a reference to the atomic value itself - it is plain int result of post-increment and the operation ...
61,995,908
61,996,003
C++ Bit Shift With Same Constant in Opposite Directions, Different Result With Minor Code Changes
I have a template function template< uint8_t HOW_FAR_CONSTANT, uint8_t START_CONSTANT, uint8_t ORIGINAL_CONSTANT> uint8_t Foo(); In Foo I do something like this const uint8_t OFFSET_CONSTANT = ( START_CONSTANT + HOW_FAR_CONSTANT ); const uint8_t RESULT_CONSTANT = ( ( ORIGINAL_CONSTANT << OFFSET_CONSTANT ) >> OFFSET_CO...
There is neither optimization. There is a truncation due to storing a result of a shift operation in an object of the type uint8_t. const uint8_t RESULT_0_CONSTANT = ( ORIGINAL_CONSTANT << OFFSET_CONSTANT ); When the shift operation is performed the integral promotions are applied to operands. So in this expression co...
61,996,316
61,996,775
How to Build the MySQL plugin for Qt Using MySQL Server 8.0?
I'm new to QT. I tried to Installing QMYSQL driver by using MySQL Server8.0. But I'm unable to build the MySQL plugin for Qt. I tried many ways and thats thing does not help to me. I used this way C:\Qt\5.14.2\Src\qtbase\src\plugins\sqldrivers>qmake -- MYSQL_INCDIR="C:/Program Files/MySQL/Connector C++ 8.0/include"MYSQ...
You are on the right way to do that, I hope you are using this web-page https://doc.qt.io/qt-5/sql-driver.html#how-to-build-the-qmysql-plugin-on-windows First of all, fix your command: add space before MYSQL_LIBDIR change "ib64" to "lib64" make sure all those paths are valid C:\Qt\5.14.2\Src\qtbase\src\plugins\sqldriv...
61,996,379
61,996,446
Differences between `decltype(&ordenary_func)` and decltype`(ordenary_func)`
Given the declaration void close_file_func(std::FILE* fd){}, I found that decltype(&close_file_func) is the type of void (*)(_IO_FILE*) whereas decltype(close_file_func) is the type of void (_IO_FILE*)? You could check the related code trough https://godbolt.org/z/QK5q3o. For your convenience, i post the code and the e...
You might think that both should give the same type as function pointer. Yes, function-to-pointer implicit conversion might be performed in some contexts1, but not for decltype(close_file_func) (and typeid(close_file_func)). When used with entity, decltype would yield the type of the entity; so decltype(close_file_func...
61,996,400
61,997,056
How do I know the positional value of a character in a string with respect to that of the English alphabets?
For example if I have something like : word="Bag" I need output as: B-2 a-1 g-7
Here is a more portable solution: There are only 26 letters to consider, thus your question is easily answerable by simply providing a lookup table. There is no need to call functions such as tolower, or to assume that letters are contiguous in the collating sequence (as EBCDIC does not follow this pattern): #include ...
61,996,577
61,999,040
Applying Rcpp on a dataframe
I'm new to C++ and exploring faster computation possibilities on R through the Rcpp package. The actual dataframe contains over ~2 million rows, and is quite slow. Existing Dataframes Main Dataframe df<-data.frame(z = c("a","b","c"), a = c(303,403,503), b = c(203,103,803), c = c(903,803,703)) Cost Dataframe cost <- da...
A possible solution, not very elegant but does the job: library(reshape2) tmp <- cbind(cost,melt(df)) # create a unique data frame row.idx <- which(tmp$z==tmp$variable) # row index of matching values col.val <- match(as.character(tmp$value[row.idx]), names(tmp) ) # find corresponding values in the column names # now...
61,996,707
61,997,986
Why is my string empty when taking input from file?
I have a huge file full of numbers (2 billion). So this is a file splitter that splits my file in groups of 100000 numbers. but this is returning empty files full of spaces and enters. I even tried to change the data type of the variable. I am struck. please suggest. #include <iostream> #include <vector> #i...
You have 2 uninitialised variables, count and curr, your compiler should have warned you about these. If it didn't make sure you have enabled compiler warnings. After the last getline in your initial while loop fails the stream will have the fail and eof flags set. Due to the stream not being in the good state all furt...
61,997,002
61,997,203
How to fix a stack overflow error caused by recursive functions? C++
As titled, I figured a recursive function has caused my program stack overflowing. And the recursive logic is needed, how to fix it? Code: static bool orient_flip_face(HE *edge) { if(edge->flip == NULL) return 1; return orient_face(face); } static bool orient_face(HEF *face) { assert(face->oriented...
Your code is an example of tail recursion because the recursive calls are the last thing executed in each function. Tail recursion is easy to transform into a non-recursive loop. The following code is the equivalent to the code you have and doesn't use recursion at all. static bool orient_face(HEF *face) { for (;;)...
61,997,310
61,997,394
c++ simple remove vector duplicates causing segmentation fault
I am trying to practice basic algorithm and am keep receiving segmentation error while running on my mac vscode. Can any one help? #include <iostream> #include <vector> using namespace std; int removeDuplicates(vector<int> &nums) { vector<int>::iterator itr = nums.begin(); int prev = *itr; for(itr = ++itr...
You can use the return value from erase function to be the new value of itr. You have to do this because the erase action invalidates the iterator.
61,997,692
61,997,799
Not being able to enter input during runtime
When I compile the code with inputs then it works fine. But when I want to run it with user input, it just doesn't take in inputs. It doesn't give any error. // kefaa and first steps // 2 2 1 3 4 1 #include <bits/stdc++.h> using namespace std; int main(){ int n, a[n], counter=0, maxIncr=0; cin >> n; cin.s...
First of all read this about your include and why we don't include like this. Second, if you want your program to run: int n; cin >> n; int a[n], counter=0, maxIncr=0; what you have it like @UnholySheep wrote to you, you initialize a[n] when n has not yet been assigne a value.
61,997,964
62,006,752
Getting each character from a textfile in my 2DgridArray
enter image description here you cann see at the picture that he is not printing out some strange letters and the white spaces are sometimes not included. The output is not right and i don't know where these strange letters come from .. maybe the transfer is not right ? #include <iostream> #include <fstream> #include <...
In the following i suggest a solution which adresses following points: When the file could not be opened the program should terminate instead of dealing with non existant data Grid should be initialized. I used '.' for this, but any other printable character will do The program should not exceed array boundaries. Ther...
61,998,066
61,998,173
Is memcopy extra data from std::string to std::array<char,size> an undefined behavior?
I don't mean to use this code in production environment, but I'm a little confuse about it.I thought it must be undefined,however,I ran this code without crash.Is this just conincidence? #include <array> #include <string> auto main(int argc, char** argv) -> int { // for (int i = 0; i < 1000; ++i) { std::array<char...
I thought it must be undefined Yes, it is undefined behaviour. src.data points to an array of 12 chars (=12 bytes), but memcpy will attempt to read 1000 bytes from it, so it reads out of bounds. however, I ran this code without crash That's the point of undefined behaviour. Anything might happen. This includes runn...
61,998,305
61,999,379
Converting C++ maps to Java map
consider the following cpp code string ans = "NO"; map<int,vi> idv ; //vi is vector of int for(int i=1;i<=n;i++) idv.[arr[i]].push_back(i); //frequecy >= 3 for(auto el:idv){ if(el.ss.size() >= 3){ ans = "YES";} } //non adjecent equal elements for(auto el:idv) { if(el.ss.size() == 2 && el.ss[0] != el.ss...
First of all, the following snippet pushes the indices to end of the vector and you need to approach the same in Java without enhanced for-each loop: // C++ for (int i=1;i<=n;i++) idv.[arr[i]].push_back(i); // Java Map<Integer, List<Integer>> map = new HashMap<>(); for (int i=0; i<arr.length; i++) { List<Integ...
61,998,683
61,999,394
C++ Concepts for checking if a function exists in a container class and implicit deduction rules
I'm trying to figure out how to do a few things that seem to be tricky to me with regards to concepts and template type like std::vector. I am trying to apply a compile time constraint similar to how I used std::movable on T, but on C with PushBackMovable. It works with the requires at the tail end of the function dec...
By using a template-template parameter you already constrain your function to containers that follow the standard library pattern but also to class templates that just happen to have two type template parameters. This is a strong constraint and usually useless in practice. That is, I would suggest that you instead oper...
61,998,704
61,998,779
Getter seems to crash the program even with 0 errors
im new in the C++ world and coding in general, just started studying getters and setters and made areally simple exercise to practice them, the build seems to have 0 errors and 2 minor warnings, however, when I try to use a function to return a private variable and print it, it simply crashes the program, however, if i...
Not all functions declared to return values actually return values so you have Undefined Behaviour and anything could happen. Example: string User::setUser(string usernm){ usernm = username; // should return a string here } string User::setPassw(string pass){ pass = password; // should return a string ...
61,999,005
61,999,052
dart: void function for ffi
I'm trying to call a native C/C++ void function form dart side via dart:ffi, final Void Function(void) funcNativeStart = nativeGuestLib .lookup<NativeFunction<Void Function(void)>>("NativeStart") .asFunction(); This gives me compiler error The type 'Void Function(void)' must be a subtype of 'Void Function(void...
Solved it myself. The working version should be final void Function() funcNativeStart = nativeGuestLib .lookup<NativeFunction<Void Function()>>("NativeStart") .asFunction(); The idea is that since we are "translating" native types into Dart (from right to left as for the equation), we should use the Dart lang...
61,999,069
61,999,121
lambda function doesn't show the right result
I wonder why this lambda function doesn't return the right answer: int main() { int a = 3, b = 7; [&]() ->void {(&a == &b) ? a : (a ^= b, b ^= a, a ^= b); }; std::cout << a << " " << b; return 0; } It shows me 3 7 instead of 7 3
Defining a lambda does not implicitely call it. You have to call it: auto f = [&]() ->void {(&a == &b) ? a : (a ^= b, b ^= a, a ^= b); }; f();
61,999,108
61,999,323
Pointer to member function or to static function in template context
I am using pointer to member function in generic context and It works OK. struct Mock{ static int inc(int){ return 0; } static int dec(int){ return 0; } }; struct Real{ Real(int v) : v(v){} int inc(int a) const{ return a + v; } int dec(int a) const{ re...
std::is_member_pointer can be used to detect pointers to members. You can then do a simple if constexpr to vary the behavior between those and a callable that should accept just the argument. template<typename C, typename F> auto user(C &c, F func){ if constexpr (std::is_member_pointer_v<F>) return (c.*func...
61,999,313
61,999,774
structured bindings to array element
What is the correct syntax of structured bindings when the left-hand side is a reference to an array member? For example, the following program does not compile: #include <array> std::array<int, 2> f() { return { 1, 2 }; } int main() { std::array<int, 4> a; a.fill(3); auto [ a[1], a[2] ] = f(); } giv...
structure binding declares new variables, if you want to reuse existing variable, std::tie is more appropriate. auto [ a1, a2 ] = f(); std::tie(a[1], a[2]) = std::tie(a1, a2);
61,999,314
61,999,431
Somebody please explain what it is behaving like this?
int main(){ int p = 10 , q = 11; int a[3]; int * ptr = &q; cout << *ptr+1 <<endl; cout <<"P = " << (int)&p <<endl; cout <<"q = " << (int)&q <<endl; cout << "Size of p = "<< sizeof(p) <<endl; cout << "(int)&a[0]:" << (int)&a[0] <<endl; cout << "(int)&a[1]:" << (int)&a[1] <<endl; ...
With regard to (paraphrased): An int take four or eight bytes but here the difference between p and q is twelve. An int does not take four or eight bytes, that's just a common thing in many implementations. The standard specifies a minimum range but no maximum. In any case, the standard does not mandate that distinct...
61,999,436
61,999,680
Privatising a public method in a subclass of a base class
I'm working on a class hierarchy structure for graphs in which I have this method called disjoint_union. Because the base class contains attributes (like the adjacency list) that need to be updated for all subclasses, I put a method in this class with parameter graph, like so: class graph { public: // .... ...
Yes, you get this warning because of the signatures disjoint_unions methods are different by arguments types. The best way to resolve this warning is do something like that in the derived class void disjoint_union(const graph& g) { auto* d = dynamic_cast<dgraph*>(&g); // cast to pointer to avoid exceptions if ...
61,999,460
62,035,564
Deduce if a program is going to use threads
Thread-safe or thread-compatible code is good. However there are cases in which one could implement things differently (more simply or more efficiently) if one knows that the program will not be using threads. For example, I once heard that things like std::shared_ptr could use different implementations to optimize the...
I support the other answer in that thread-safety decision ideally should not be done on whole program basis, rather they should be for specific areas. Note that boost::shared_ptr has thread-unsafe version called boost::local_shared_ptr. boost::intrusive_ptr has safe and unsafe counter implementation. Some libraries use...
61,999,605
62,000,440
How to iterate using vector of vector of pair in c++?
i would like to ask how do you iterate over vector of vector of pair? supposed i have the following. typedef pair<int,int> Pair; vector<vector<Pair> > adjList; and then i tried to iterate using the following code: vector<vector<Pair> > :: iterator i; vector<Pair> :: iterator it; for(i = adjList[N].begin(); i != adjLis...
You could use range-based for-loops and structured bindings: for(auto& inner : adjList) { for(auto& [first, second] : inner) { first = ...; second = ...; } }
62,000,566
62,000,676
I'm trying to make a menu in c++ and I don't understand why it doesn't loop
This is what I've tried so far. It might be that I'm using the worng do while syntax but I'm really stumped because I'm pretty sure I used this exact template to create a menu before. I think the condition in the while loop is wrong for some reason it ignores that line and stops the program. #include <iostream> #includ...
as @Yksisarvinen wrote you have a problem in your condition, your current condition says that: if selection equal to Q and equal to q run the loop and I'm guessing that you don't want what so you need to change the loop condition from this - while (selection == 'Q' && selection == 'q'); to this - while (selec...
62,000,671
62,002,025
MFC DrawText, vertical, DT_CALCRECT with lf_escapement = 900
I'm working on a MFC project with some GDI drawings. I use DC.DrawText to draw a vertical text into a DC using a LOGFONT with lfEscapement = 900. The text is output when i use DT_NOCLIP in the desired vertical formatting. However to center this text i used a call to DC.DrawText with the DT_CALCRECT argument. I recogni...
I found out about it in the remarks to the DrawTextEx function https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-drawtextexa. However, please note that neither the documentation of DrawText does say anything about this nor the documentation of the DT_CALCRECT flag. This is likely to be overseen if ...