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,874,620
61,874,656
Segment faults on program
I'm trying to solve a problem in hackerrank called Variable Sized Arrays. input 2 2 3 1 5 4 5 1 2 8 9 3 0 1 1 3 output 5 9 The way the problem works is you first get two inputs let's base on the above example, '2 2' here means that we need 2 rows of data and 2 queries. the next input is how many data is in this row...
std::vector<std::vector<int>> nums; You've used default constructor of vector. This vector is empty and doesn't contain any elements. nums[i].reserve(col); Here, you access the ith element of the empty vector. Because the vector is empty, this index is outside the bounds of the vector. The behaviour of the progra...
61,874,935
61,875,008
Is there a way to force a C++ compiler to store a variable in a register?
I know that the inline keyword makes the compiler more likely to inline a function, although the decision is up to the compiler, and the GNU extension __attribute__((always_inline)) forces the compiler to inline it. Correspondingly, is there... __attribute__((always_register)) register int foo = 678; ...or something l...
GCC has a way to specify register for a local variable through usage of keywords asm and register: register int *foo asm ("r12"); Note the quote: The only supported use for this feature is to specify registers for input and output operands when calling Extended asm. This feature is used in Linux kernel on some arc...
61,875,100
61,876,118
Why is there no enumeration concept in C++ 20?
I am trying to update some older code to the coming C++20 language using current GCC10. I was not able to update some templates because they used a std::enable_if<std::is_enum_v<T>> condition and there is no std::enumeration concept defined in C++20. Of course I can define my own concept but still it makes me wonder wh...
There is no enumeration concept because there was never a specific intent to create a concept to match every type trait. Or even most of them. The C++20 concept library was, more or less, based on what was needed to make the Ranges library work. It focuses on things concepts are good at, like asking "what can I do with...
61,875,211
61,875,483
What is the difference between the three ways of applying constraints to a template?
I just learned that C++20 provides three ways of applying constraints to a template: Requires Clause Trailing Requires Clause Constrained Template Parameter I successfully used constrained template parameters and I tend to prefer that syntax. Still I wonder why there are three ways defined in the standard. Are there ...
There are no technical differences. // (1) void foo(Concept auto&& x); means exactly the same thing as: // (2) template <Concept T> void foo(T&& x); means exactly the same thing as: // (3) template <typename T> requires Concept<T> void foo(T&& x); means exactly the same thing as: // (4) template <typename T> void fo...
61,875,263
61,875,660
Docker image not executed by host bin/bash
I have a linux executable. I've built a docker image with centOS 7 which runs ok when executed directly from macOS terminal (macOS Mojave version 10.14.6). The image is built with: Dockerfile: $ docker build -t my_testi . FROM scratch ADD centos-7-x86_64-docker.tar.xz / LABEL \ org.label-schema.schema-version="1.0...
There are two problems which needed addressed. Firstly, the docker command had to be terminated with \n and it had to be run in non-interactive mode i.e. -t instead of -ti. Thus, the command changes to: s += std::string("docker run -t -v ") + analysispath.parent_path().string() + std::string("/:/ca...
61,875,282
61,875,885
Save user input as it is - Ruby on Rails
I am trying to create an Online Judge where users will write/paste c++ code to evaluate it. I'm using rails 6 and Ruby 2.6.1 . The problem is users' input can contain any type characters \n,\t etc . I need to save it to a cpp file as it is. For example a user is submitting the following code: #include<bits/stdc++.h> us...
Use an actual Ruby method: File.open('code.cpp', 'w') { |f| f.write(params[:code]) } Or shorter: File.write('code.cpp', params[:code])
61,875,449
61,876,140
Parts of a structure in C++
Here is a code of a structure. On that there is a BSTree function included on the structure. I am stuck because I do not understand how a function can get called when is inside the structure. Here is the structure and if anyone can explain the trick would be helpful: struct BSTree{ int data; BSTree *left; ...
There is no trick. In C++ structs and classes can have data and function members. The particular function you have there is a constructor, it's used to create an instance of the struct, an object of this type. A particular struct or class can have many constructors with different parameters, or no parameters at all. st...
61,875,705
61,878,342
Error Messages using the c++/WinRT Direct3D UWP Game DR template, Direct X11
I'm getting this compiler error when I use this template and I have no idea how to solve it. Standard compiler options. Visual Studio 2019, latest updates installed. It still compiles but I want to understand it to know if I have to watch out for something. Error Message : D:\Windows Kits\10\Include\10.0.18362.0\cppwi...
Those are warnings recently added to the VS 2019 compiler as part of improving C++ standards conformance. You can resolve this with any of the following: Disable two warnings (5204, 5205) You can disable Conformance Mode (turning off /permissive-) and disable just one warning (5205) Upgrade to the latest Windows 10 SD...
61,876,060
61,876,183
How can I know the real maximum size of a vector? (Not using std::vector::max_size)
On an online course I am learning about vectors. In one of the examples they explained that: std::vector::max_size() should give me the maximum size the vector can reach. I decided to test it: #include <iostream> #include <exception> #include <vector> int main(void) { std::vector <int> nums; int max = nums.max...
Note that the max_size function returns a theoretical maximum number of elements, it doesn't say anything about the amount of memory needed. If we assume that sizeof(int) == 4 (pretty common) then 204324850 elements would need 817299400 bytes of contiguous memory (that's almost 780 MiB). You get a bad_alloc exception b...
61,876,249
61,876,987
Compile multiple .cpp files in Visual Studio Code with clang++ on macOS
I'm trying to build a simple project with multiple *.cpp files with clang++ on macOS. The tasks.json: { "version": "2.0.0", "tasks": [ { "type": "shell", "label": "clang++ build active file", "command": "/usr/bin/clang++", "args": [ "-s...
Don't complicate tasks.json. It is better to use something such as CMake that takes care of all of this configuration (C++ version, compilation flags and warnings, etc) and just call make (or ninja or any other generator that you choose with CMake). Then in your tasks.json the value of "cwd" in "options" would point to...
61,876,486
61,876,967
Argmin for static arrays
Hello all I am trying to implement the Argmin function. following the example from one of the comments here ArgMin for vector<double> in C++?, I have written the following logic. rev_tone = get_rev_tone(cam_model_path); //reading the images Mat img_rev = imread("C:/Users/20181217/Desktop/images/imgs/outp...
My question is why is it only a problem for an array but not for vector? vector is an object, so it has member functions like size() and begin() and end() for iterators. While array is just a raw type, just like and int or a float and not an object, so you don't have any member functions for it. According to the cpp...
61,876,604
61,877,567
Concert Tickets, sorting and searching problem
There are n concert tickets available, each with a certain price. Then, m customers arrive, one after another. Each customer announces the maximum price he or she is willing to pay for a ticket, and after this, they will get a ticket with the nearest possible price such that it does not exceed the maximum price. Input ...
This can be solved using a data structure like tree map. For each fixed price of ticket i.e. h[i] put them in a tree map with the count as value. Tree map ensures the keys inserted are in order. So for example, for the input in question, the map will look like : 3 -> 1 5 -> 2 7 -> 1 8 -> 1 Then in this map, search for...
61,877,527
61,877,648
How to compare string char to struct array?
My goal is to turn a user imputed string to Tap code/Knock code. https://en.wikipedia.org/wiki/Tap_code The problem i'm having is that i don't know how to compare the char i get from the string to the struct array. I want to read a letter of a string then compare it with the structure array. So if i input the letter "...
There's actually no need to loop through the array to find the letter that matches. You can use character arithmetic to transform a letter from the input into an index of your Tap Code array. That may look like: for (int x = 0; x < length; x++) { if(std::isalpha(static_cast<unsigned char>(input[x]))) { // If it's n...
61,877,751
61,879,483
Outside the range of representable values when casting double to long long with UBSAN enabled
Compiling the code below with UBSAN enabled causes this error: Runtime error: value 9.22337e+18 is outside the range of representable values of type 'long long' double a = (double)LLONG_MAX; // or (double)LLONG_MAX - 1 long long b = (long long)a; Is this a known issue? My understanding is that the value is not out...
What you are seeing is expected behavior. LLONG_MAX is a 64-bit integer on your system, needs 63 bits to fully represent its value (since one bit is used to hold the sign). A typical double (using IEEE arithmetic) only has 53 bits of precision. When you assign an integer to a double, the integer value needs to be conve...
61,877,905
61,878,150
No match for operator << in exception handling program
#include <iostream> #include <string> #include "NegativeBalanceException.hpp" #include <memory> class Account { private: std::string name; double balance; public: Account(std::string name, double balance); ~Account() {std::cout <<"Calling Account Destroyer" << std::endl;} void get_name() const {st...
Your get_name() and get_balance() methods are both declared with void return values, so your overloaded operator<< can't pass them to os << .... Internally, the methods are doing their own logging to std::cout, so you would need to change your operator<< accordingly, eg: std::ostream &operator<<(std::ostream &os, cons...
61,878,156
61,878,692
SIMD instructions on contiguous iterators
I have two vectors v1 and v2 of type T and want to create a function that performs v1 & v2 using SIMD instructions and stores the output in a vector out. Ideally, what we would have is first1 = v1.begin(); last1 = v1.end(); first2 = v2.begin(); d_first = out.begin(); while(distance(first1, last1) >= 64 / sizeof(T...
Normally you just get a pointer from .data() on the container and loop manually over the array, like a C-style array. Or increment an index and do _mm512_loadu_si512(&vec[i]). (Unless you used a custom aligned allocator for your std::vector, you shouldn't assume that the data is aligned. But 512-bit vectors on curre...
61,878,586
61,881,489
using %union for structs
I searched a lot but can't seem to find a clear example on how to use %union is my parser file. I would like to save for example the following token in a struct called classID: [a-zA-Z][a-zA-Z0-9]* { yylval=new IDClass(yytext); return ID; } This is the struct in my .hpp folder which I included: class Node {...
There is no "correct use of %union in structs", since %union is used to declare a union. (You could, of course, declare a union with just one member, but that's almost pointless.) The correct way of declaring a semantic type which is not a union is: %define api.value.type { Node* } But that's not going to get you wan...
61,879,165
61,879,525
Modifying the member of a class from outside the class in C++
I'm wondering if the following procedure is actually doing what I intend for it to do, and convince myself of the different ways of doing it. I have a base class called simulationEngine that has an object of type class ValuationFunction as a member that looks like this: class SimulationEngine { public: SimulationEn...
I think what you are looking to do is return by reference like so: const Wrapper<valuationFunction> & SimulationEngine::GetFunction() const { return theFunction; } Note the use of const (twice) avoids the member from being inadvertently modified. Returning by reference avoids a copy but runs the risk of being unin...
61,879,169
61,879,251
Condition variable wait in child thread stops execution in main thread
I have class player with its own thread: player.cpp int soh::player::instance_count{ 0 }; int soh::player::current_player{ -1 }; std::mutex soh::player::mutex; std::condition_variable soh::player::cv; soh::player::player(std::string name) : name{ std::move(name) } , id{ soh::player::instance_count } , thre...
soh::player{ "player_0" }; creates an unnamed temporary object that immidiatelly gets destroyed hanging at .join() because thread routine hangs at cv.wait. You should give it a name so will survive until it gets out of scope.
61,879,225
61,880,940
Why does the MSVC C++ compiler expand a simple Hello World into 4000 lines of assembly?
Lately I'm diving into optimizing my C++ code and as such started to play around with the compiler explorer. Since i am mainly developing on windows with Visual Studio i used the msvc compiler. At some point msvc got out of hand. after some fiddling around i could narrow it down to the iostream header, that's supposed...
This may not be a complete answer, but I think I can explain much of the differences. Much of the standard library (e.g., iostreams) is template heavy code. I believe the Microsoft compiler generates more template instantiations and relies on the linker to remove unnecessary ones. I think that's an effect of the diff...
61,879,302
61,879,426
(C++) OpenGL renderering tilemap causes framedrops
I'm using OpenGL to draw a large tile map currently made up of 50 x 50 tiles. I'm using GLFW, GLEW and GLM to handle most of the OpenGL functions. When I try to draw the map it will only render at about 30 fps, as opposed to drawing one object at 1000+ fps. This is even if I'm drawing a single color for every tile inst...
First, as you are using the same shader and the same VAO for each draw, you should use your shader and bind your VAO once (before your two loops). This should really improve your performance. To go further I recommand you to look the function glDrawArraysInstanced which allows to draw all your tiles with only one draw ...
61,879,350
61,879,507
Link external C++ External C++ In the Main file?
I want to make my code into multiple C++ files. Here is an example of what I mean: main.cpp holds basic layout player.cpp holds how the character moves bg.cpp holds the background and attachments I want to join all of the code from these files together in main.cpp. Like in C, you can link external files using inclu...
The #include directive works the same in C and in C++ compiler: It literally pastes the text of the specified file instead of where the directive is located, as though you had performed a copy-and-paste of its contents. So, yes, you could write #include player.cpp within main.cpp. However - this is discouraged and very...
61,879,664
61,886,949
QObject::connect not working - Signal not found with function syntax
I am trying to create a very basic dialog with Qt: QDialog *inputDialog = new QDialog(g.ParentWidget); QVBoxLayout *layout = new QVBoxLayout(inputDialog); inputDialog->setWindowTitle(to_qstring(p_strTitle)); inputDialog->setLayout(layout); QDialogButtonBox *buttonBox = new QDialogButtonBox( QDialogButtonBox::Cancel ...
since you did not specify the compiler, OS, and I also encountered such an error, I advise you to switch to the old syntax, QObject::connect(buttonBox, &QDialogButtonBox::accepted, inputDialog, &QDialog::accept); QObject::connect(buttonBox, &QDialogButtonBox::rejected, inputDialog, &QDialog::reject); change to QObject...
61,880,503
61,880,679
Multiple definitions when using #ifdef
I am having a problem when compiling: Multiple definitions of "myFunction()" I will greatly simplify the problem here. Basically, I have 3 files: "main", "header", and "myLibrary". main.cpp #include "header.hpp" int main() { } header.hpp #ifndef HEADER_HPP #define HEADER_HPP #include "myLibr...
You are defining the body of the function inside the header file. So every translation unit that you include that header in (in this case, main.cpp and header.cpp) will end up with its own copy of that function body. And when you try to link those multiple units together, you get the "duplicate definition" error. The...
61,880,574
61,880,735
non-template std::reference_wrapper assignment operator and template constructor
In the C++ 20 Standard the constructor of the class template std::reference_wrapper is a template. template<class U> constexpr reference_wrapper(U&&) noexcept(see below ); while the assignment operator is not a template constexpr reference_wrapper& operator=(const reference_wrapper& x) noexcept; What is the reason t...
If std::reference_wrapper<T> had a single constructor accepting T&, then it would lead to bugs like std::reference_wrapper<const T> being able to bind to temporaries of type T. So, originally there were two constructors (other than the copy constructor): one taking T&, and another taking T&&, which was defined as delet...
61,880,648
61,884,511
Handling Image data from IMFSourceReader and IMFSample
I am attempting to use the IMFSourceReader to read and decode a .mp4 file. I have configured the source reader to decode to MFVideoFormat_NV12 by setting a partial media type and calling IMFSourceReader::SetCurrentMediaType and loaded a video with dimensions of 1266x544. While processing I receive the MF_SOURCE_READERF...
New media type says this: "video is 1266x544 and you expected/requested, but I have to carry it in 1280x544 textures because this is how GPU wanted it to work". Generally speaking this does not require further scaling or cropping you already have the frames you need. If you are reading them out of sample objects - whic...
61,880,672
61,888,621
In C++, is it possible to "overload" an object which is a member of another class?
I have a class driver which does a bunch of computations based on a member, which is an object of another class computation_A. The header for driver looks like: // driver.hpp #ifndef DRIVER #define DRIVER class driver { public: // Making this public may be considered bad practice but this is for illustration p...
There are many different approaches. Below few of them aiming at low number of changes in driver.cpp file. Note that form is very terse and skeleton. Case 1 --- You know types at compile time. Simple template based solution. struct mult { int a; double do_work(int b) { return a * b; } }; ...
61,881,337
61,881,531
Class does not name a type in bison
This is the beginning of the parser.ypp file %{ #include <iostream> #include "hw3_output.hpp" using namespace std; using namespace output; extern int yylineno; extern int yylex(); int yyparse(); void output::errorSyn(int lineno); void yyerror(char const* s); output::TableStac...
The code which you pasted is at the top-level of the generated file (which makes it possible to use #include directives, for example). Recall that the top-level of a C++ program can only contain declarations and definitions, not executable statements. And SymboleTableStack->makeTable(); and st->push(0); are executab...
61,881,436
61,881,487
C++ - Sorting first and second of a vector of pair at the same time
vector<pair<int, char>> pair_vec; I have such a vector containing pairs. I'd like to sort second of pair in descending order, and if there are two pairs with the same value of char, those two should be then sorted by first of pair of ascending order. sort(pair_vec.begin(), pair_vec.end(), sortbysecdesc); This is the...
Use this- bool sortbysecdesc(const pair<int,char> &a, const pair<int,char> &b) { if(a.second==b.second) return a.first<b.first; return a.second > b.second; }
61,881,988
61,882,031
Repetitive output using cout in CPP
I tried to read a line of string into the program, and when the string is "q", the program should break, but there were some weird behaviors with my main function. Could you find it out for me? Thanks a lot! #include <iostream> #include <string> using namespace std; int main() { int distance; int points[1000]...
The clear function doesn't do what you apparently expect it to do. It clears the streams state flags only. What you seem to want is probably the ignore function to ignore the newline left by the first input operation: cin >> distance; cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Skip the remainder...
61,882,261
61,882,441
Get the right size of a char array string
I want to get the size of an array from return value of a function. This is the function: const char* bukaKunci(){ if(mlx.readObjectTempC() >= tempMin){ // if temp is lower than minimum temp digitalWrite(selenoid, HIGH); delay(1000); return "Kunci terbuka!"; } else{ digitalWrite(selenoid, LOW); ...
int msg_len = sizeof(msg); the above line of your function is returning the size of the object of the pointer and via pointer you can not determine the size of the array . May be you should read about a array decay. Two possible solutions . Iterate over the array with a counter and counter will tell you the exact si...
61,882,455
61,882,577
C++ why max of 64bit double has 308 digits?
In my environment (Win10 64bit, VC++2019 and 32bit project), sizeof(double) is 8 bytes, the max value should be 1.84e19. But std::numeric_limits<double>::max() is around 1.79e308. Why they are so different? The WIKI has more detailed informations: Double-precision floating-point format The bits are laid out as follo...
Floating point types work differently than integer types. Integer types directly map their min-max range values to all the binary permutations from all 0s to all 1s. So they can directly represent a value, if its in range. Floating point types are essentially 2 numbers: fraction (mantissa) and exponent. So number 1,000...
61,882,684
61,882,715
Smart Pointers in templates c++
Create a class template SmartPointer that should contain a pointer to any object and delete that same object when the destructor of that class is called. In order for the smart pointer to behave the same way the raw pointer behaves, you must overlap the operator * and ->. So, this is my task, and I've done this code,...
The operator-> function should return a pointer. And it should be a pointer to the wrapped object: T* operator->() { return x; }
61,883,059
61,886,825
cv::namedWindow() crashed, Segmentation Fault
This is a stochastic problem. When I re-make my project, this problem is more likely to happen. I used gdb core dump analysis and found out that cv::namedWindow function may be the reason? This is main.cpp Simple_ORB_SLAM::Map map; Simple_ORB_SLAM::LocalMapping localMapper(&map); Simple_ORB_SLAM::VisualOdometry vo(&lo...
You should not open a cv::namedWindow from a thread that isn't the main thread. It might work, but I wouldn't recommend it.
61,884,158
61,884,241
Failed to read the same file using multithread
I created 50 threads to read the same file at the same time and then, in each thread, tried to write its content to new file that create with different name. The code was supposed to generate 50 different files. But I got unexpected results that it just generate 3~5 files. When all the read the same file, there is no ...
I believe your problem is that you are passing src (which is a pointer to a local variable on your main thread's stack) to your thread's entry function, but since your copy() function runs asynchronously in a separate thread, the char src[40] array that you are passing a pointer to has already been been popped off of t...
61,884,812
61,886,166
How to convert a boost::hana::tuple into a std::variant
I have the following code where I want to convert a boost::hana::tuple into a std::variant namespace hana = boost::hana; template <typename Tuple> struct to_variant; template <typename... Ts> struct to_variant<std::tuple<Ts...>> { using type = std::variant<Ts...>; }; auto my_tuple = hana::make_tuple(hana::type_c...
I suggest three corrections in your code (two are already addressed in the other answer): Use decltype(my_tuple) to pass a type into to_variant Inside to_variant, use using type = std::variant<typename Ts::type...> to extract the types out of the Hana type_c's. Use a hana::tuple in the specialization, not a std::tuple...
61,884,947
61,885,467
Why is my code not returning 0? I'm using scanf() instead of cin
I wanted to make sure I understood how to use scanf(), but I don't understand why my code didn't return 0. I understand that scanf() has it's own issue when it comes to loops, etc, but it bewilders me how something as simple as displaying a string wouldn't return 0. Is there perhaps any problems with my code? My simpl...
Your first program has undefined behavior. scanf and printf expect for the %s a pointer to char, not a pointer to std::string. They are C library functions and as such don't know anything about C++ types such as std::string. You are required to provide the correct type as argument for the format specifier. If you don't...
61,885,420
62,277,116
FInd position of latest smallest element in the array for all elements
I want to calculate, for an array of integer elements, the position of the latest element which is smaller than that element(if possible) otherwise store -1 in this place. By latest element I mean that largest possible index smaller than current index. Eg. (based on 0 indexing) let problem[5] = {4,7,1,3,8} then sol arr...
You can exploit stack data structure, containing indices of elements waiting for smaller precursors. Approach is linear. Make a stack `S` Scan array `Q[]` from the end while (Q[i] < Q[S.top()]) t = S.Pop() Sol[t] = i Push i onto stack Write -1 into Sol[] for all indices remaining in the stack ...
61,885,796
61,886,627
C++ - iteration over a n-ary tree
This is the function with iteration algorithm over a n-ary tree, given a name, and use it to find the parent tree, return parent tree's data if found, "ZERO" if no parent is found, and "NA" if the name is not in any tree in the Tree<string>* vector. It works most of the time, but will occasionally give wrong output tha...
You should push children of current node/tree you visit. I also remove some copies. std::string getSource(const std::string& name) const { if (!existInVector(name, trees)) { // vector of Tree<string>* return "NA"; } std::queue<const Tree<std::string>*> treesQueue; for (const auto& tree : trees) ...
61,885,949
61,892,374
How does python venv manage C++ dependencies
I'm using a library which offers a python wrapper to a c++ executable. I installed it (https://github.com/bulletphysics/bullet3) using venv (https://docs.python.org/3/library/venv.html) - and all is working great. I'm considering trying to build https://github.com/bulletphysics/bullet3 From the root of the venv folder ...
python just looks for correctly named dynamic libraries in PYTHONPATH, loads such library and uses predefined interface for further info : https://docs.python.org/3/extending/index.html
61,886,098
61,886,285
In C++ can we dereference this pointer? If so then how and if not then why?
I was working on a personal project with classes and didn't wanted to initialling each of the data members. So I made a call to *((Classname *)(this)) = {}; in the constructor. Hoping that it would behave the way #include <iostream> struct Test1 { int data1; int data2; void print() { std::cout...
UPDATE: I just realized you modified the code, and the new one does not make sense now. My answer is related to the original code. Yes, you can dereference this and invoke member functions on it, such as this->f(); which is the same (*this).f(). Similarly, (*this) = ... is the same as this->operator=(...);. The problem...
61,886,138
61,886,498
Gmock for a nested object
I need to make a mock for the function foo, which is called in dosomething, is it possible with gmock? class Base { public: int foo() { } }; class A { A() { pointer = new Base(); } double dosomething() { //more code pointer->foo(); } private: Base* pointer;...
You need to use Dependency Injection. There are many ways to do that, I'll present the easiest one: class Base { public: virtual int foo() { } }; class BaseMock: public Base { MOCK_METHOD(int, foo, (), (override)); }; class A { A(Base* providedBase = new Base) { pointer = providedBase; ...
61,886,145
61,890,936
auto type for defining variables
I was trying auto type for defining variables. I declared an array in two ways 1. using auto auto a={10,30,20,40}; 2. using int int b[]={10,30,20,40}; Then I wrote the following code: cout<<sizeof(a)/sizeof(int)<<" "<<sizeof(b)/sizeof(int) OUTPUT: 2 4 Why output is different for the two cases though both the statemen...
The rule is that when an auto variable (i.e. a variable declared by auto) is initialized with a braced initializer (e.g. {10,20,30,40} in your case), the deduced type is an instantiation of type std::initializer_list<T>. (in your case it will be std::initializer_list<int>). In addition, do not forget that the sizeof o...
61,886,286
61,886,354
Removing items from c++ list
I am trying to remove some items from a string list in c++. The code compiles successfully but at runtime it gives "Segmentation fault (core dumped)" error. I have abstracted the code as follows. #include <iostream> #include <list> using namespace std; int main() { //a string list list<string> entries; /...
std::list<T,Allocator>::erase invalidates the iterator to the erased element, i.e. i. After that the operation like i++ leads to UB. You can assign it to the return value of erase, which is iterator following the removed element. while(i != entries.end()) { if(*i=="two") i = entries.erase(i); else ...
61,886,455
61,886,575
Can class object attributes call methods that return a value that the attribute should have in C++?
Why can't I simply call a class object attribute (i.e. sum) that calls a calls method (i.e. calculateSum()) that returns the value that attribute should have? What am I overlooking here? I know about how getter and setter functions are usually used, but I like the shortcut of simply calling an attribute that gets then ...
In your code, the initialization order for class Entity is: x is default-initialized to indeterminate value y is default-initialized to indeterminate value sum is initialized as calculateSum() the body of the constructor is performed (x and y are assigned to the function parameters). As you can see, when data member ...
61,886,808
61,886,970
pthread_create in constructor segfault
I discovered, in this little example below, if I call pthread_create in the constructor of my struct, I get a segfault randomly on the call to pthread_mutex_lock(). And sometimes the name field is empty for the first philosopher. If I move pthread_create to a run() function after the constructor, no segfault. It see...
std::vector resizes when the code does philosophers.emplace_back(), which can move the elements in memory, so that their previous addresses become invalid and the feed() function ends up accessing objects using their old invalid addresses. A fix would be to make the philosopher class non-copyable and non-movable, and t...
61,886,997
61,887,527
How to work with this singly linked list?
I have a strange linked list (code is not mine): struct _P_NEXT { P_NEXT* p_el; }; As you can see, there is no data field. However, the list must contain complex structures. For illustration, I give a method of adding an item to the end of the list: void in_tail(P_NEXT* head_list, P_NEXT* el_list) { el_list->p_el...
This kind of structure is usually used as intrusive list this is usually useful in C where there is no type polymorphism and but you want to have common function for maintenance and utility. Usage example: struct node { struct _P_NEXT list; // must be the first member of the structure int data; // and so o...
61,887,066
61,887,190
Why we need rbegin and rend?
Since we now have advance() and the prev() to move iterator to go front or go back, and we already have begin() and end(). I wonder is there any situation we better/have to move reverse iterator back and front?
Algorithms often take two iterators that specify a range of elements. For example std::for_each: std::vector<int> x; std::for_each(x.begin(),x.end(),foo); If you want to make for_each iterate in reverse order (note: for_each does iterate in order) then neither advance nor prev are of any help, but you can use reverse ...
61,887,372
61,887,786
C++ Static const initialization order in templates
Risking getting flagged for duplication, I take my chances. Consider the following: Given the following static const arrays arrA and arrB, arrB depending on arrA. #include <iostream> #include <string> #include <array> template<int N> class MyClass { public: static const std::array< int, N> arrA; static const s...
If you want to guarantee the order of initialisation you have to wrap both arrays in a struct and use the struct's constructor to initialise the static variable. Here is an example of what I mean. #include <iostream> template <typename T> struct A { struct B { B() : c(0), d(c + 1) {} T c; T...
61,887,534
61,887,866
strtok_r is returning incorrect data after tokenizing
Below is the code where I am trying to use strtok_r() to tokenize my string to fetch the first token i.e. 38 in this case. If you observe the output somehow my token is incorrectly fetched (refer output :38 is fetched as 8)This is an intermittent issue which doesn't occur everytime. I am unable to find any solution for...
According to the man page strtok_r has a const char * delimeter. I would guess that you're screwing up the operation by pointing to a randomly terminated string, i.e.&cDelimeter. Try ... const char *cDelimeter = ","; ... pRecordString = strtok_r(szMsgBuff,cDelimeter,&pRemainString);
61,887,700
61,887,854
Arduino : A case of switch block the case that are after
I've a switch and a functions 'block the case that are after it' at the 4th case of the switch. I tried to move the case and apparently it's the 'P_JEU' case that block but I don't understand why. switch (partie) { case P_CHOIX_ANIM: allPlayers.chenillard(250,100); partie = P_CHOIX; case P_CHOIX: ...
You cant declare variables inside a case: https://complete-concrete-concise.com/programming/c/keyword-switch-case-default/ Can I declare variables inside an Objective-C switch statement? bool passResponse = allPlayers.Pass(); is wrong - you have to enclose it: case P_JEU: // Bug if (bConfig.isPressed()) { ...
61,887,890
61,887,932
using "transform" in c++ gives an error that this was not declared in the scope
I was converting a string to lowercase using transform and the compiler gives an error stating transform was not declared in the scope. transform(my_str.begin(), my_str.end(), my_str.begin(), ::tolower); Or tell me an alternative solution to solve this problem, thanks!
According to the documentation for transform, this is a function in the std namespace. You will have to include the correct header file, and qualify the function name: #include <algorithm> std::transform(my_str.begin(), my_str.end(), my_str.begin(), ::tolower);
61,887,903
61,888,038
What's the most idotomatic way of declaring two constructors with the same args?
As an example lets say I have a class called File. Now file can be opened as binary or text. My constructor is currently File(const char*filename). Let's suppose the implementation of open is completely different binary and text. How the heck do I construct this? I thought about using a static function but I don't want...
Two idiomatic ways are a factory function (nothing forces you to return a pointer), or tag dispatching (which is used in the standard library, for example in std::variant). // Factory functions struct File { static File openText(char const *filename); static File openBinary(char const *filename); }; // Tag d...
61,888,707
61,888,848
Using member function to solve equation C++
I am currently trying to create a program to calculate the mass of a rocket with given time values by passing an array to a member function of a class. I get these two errors and can't seem to figure out how to get rid of them. Any suggestions are much appreciated, thank you. 23 8 [Error] prototype for 'double equip...
In your class definition you've declared double calcmass() In the definition of the member function it's double calcmass(double time) They do not match. One takes a double as argument and the other does not.
61,888,763
62,230,480
How to create a CLI wrapper for a C++ library?
I have the header files(*.hpp) and source files(*.cpp) to a library. I built the library from source using CMake, then used Visual Studio to build it, which created a .lib file. To create a CLI wrapper, I need a header file that enumerates all the methods in the library in it, and a source file that creates proxy funct...
Use Swig library. It provides a comprehensive range of options to generate wrappers for C#, Java, Python, Tcl and many other popular languages. It is easy to use, and the documentation provided is extremely clear and helpful.
61,888,854
61,889,268
What is compile time function in C++?
I've searched this question here(on SO), and as far as I know all questions assume what is compile time functions, but it is almost impossible for a beginner to know what that means, because resources to know that is quite rare. I have found short wikipedia article which shows how to write incomprehensible code by writ...
In cpp, as mentioned by you, there are two ways of evaluating a code on compile time - constexpr functions and template metaprogramming. There are a few differences between those solutions. The template option is older and therefore supported by wider range of compilers. Additionaly templates are guaranteed to be evalu...
61,888,868
61,890,062
Create a python like list in c++
I have a python script that I have to translate in c++, and 80 % of my python script is based on lists. I have a file that I read, and put the data of that file in a list : //Code to translate in c++ bloc = [line] for b in range(11): bloc.append(lines[i + 1]) i += 1 I make my stuff with that data and then, I ...
The C++ container closest to a python List is a std::vector. However contrary to python a std::vector contains only one type of element. You have to declare what the vector will hold. In your case it would be std::string (reading from a file). So: std::vector<std::string> cpp_list; // container for lines (stored as str...
61,889,111
61,889,432
Own vector assign implementation
I'm implementing stl like vector with writing all default functions. And there is a problem that I don't understand why It calls ragne version of assign for simple types and doesn't default. Here is the implementation code: Vector.h void assign(size_t count, const T& value){ // Default version void ass...
The range version is a better match for vec.assign(5, 10); with InputIt = int. You should somehow disable that overload for a template parameter that doesn't represent an input iterator. Let's take a look at stdlibc++ implementation: template<typename InputIt, typename = std::RequireInputIter<InputIt>> void assign(Inp...
61,889,358
61,891,611
MacOS App compiled with Deployment 10.10 on Catalina crashes on versions < HighSierra due to ____chkstk_darwin
We have a multi-platform desktop application that uses a common component written in C++. The component uses OpenSSL and PocoProject - both are statically linked into the library. On macOS - we have a small Framework written in Objective-C - it's essentially single h/cpp wrapper for the C++ code. It enables macOS devel...
The issue is how the static libraries for OpenSSL and PocoProject were compiled. They also need to be compiled with the deployment target set to 10.10. The deployment target would be what prevents the compiler from inserting that call to the chkstk function. More generally, all of the code must be compiled with the dep...
61,889,551
61,891,529
Building SDL2_image alongside SDL2 (and similar cases)
I have the following conditions: I am using SDL2 (sources) as dependency directly from github mirror by using git submodules Also i am using SDL2_image (sources) as similar dependency My cmake project includes both deps with add_subdirectory Problem here is that SDL2_image is trying to find SDL2 with find_package, bu...
Create a FindSDL2.cmake with the following: add_library(SDL2::SDL2 ALIAS SDL2) Make sure find_package sees this file first by adding the path to it to CMAKE_MODULE_PATH or CMAKE_PREFIX_PATH.
61,889,608
61,890,020
comparison of external value in count_if
I want to iterate through a vector and want to get count of greater elements in another vector. I tried below code snippet, unfortunately it does not work this way. sort(begin(vec1),end(vec1)); sort(begin(vec2),end(vec2)); for(int i = 0; i < vec1.size(); i++) { int val = vec1[i]; count_if(begin(vec2),end(vec2)...
If you want to count how many elements in vec2is greater than the i'th element in vec1 then you are doing it correct and just have to capture val in the lambda for(int i = 0; i < vec1.size(); i++) { int val = vec1[i]; auto res = count_if(begin(vec2),end(vec2), [val](int x) { return (x > val); }); } but if you ...
61,889,726
61,890,715
Client gRPC connection with reconnect in C++?
Is it possible to have a client channel that automatically reconnects? I tried using wait_for_ready(true) on the context, but that doesn't seem to have any effect. I get this crash when I try to use a client channel with a lost connection: E0519 12:56:40.239405883 9379 client_context.cc:119] assertion failed: c...
My problem was attempting to re-use a context. Creating a new context for each attempt fixed the issue.
61,890,011
61,890,592
How to initialize a class in c++ based on an event?
My program performs some task in a specific manner mentioned by the user. There are exactly three ways to do the task. The problem is that the three ways, although doing the same job are needed to be implemented using different data structures for various performance boosts at specific places. So, I am performing 3 dif...
I can propose the following: 1) Read about polymorphism in c++. 2) In general, read about c++ design patterns. But for your case, read about Command design pattern. So, Instead of casting, use polymorphism: class Animal { virtual void sound() = 0; // abstract }; class Cat : public Animal { virtual void sound(){ ...
61,890,221
61,890,855
C++: Nested For-loops over 2 dimensional array with "auto"
To loop over a 3x3 array called "a" in C++ i used the following code. int a[3][3] {}; for(auto &b: a) { for(auto &c: b) { std::cout << c << std::endl; } } If I had to replace the "auto", I would intuitively try int a[3][3] {}; for(int &(b[3]): a) { for(int &c: b) { std::cout << c << std::endl; } } But...
If you have an array like this T a[N1][N2][N3]; where T is some type specifier and N1, N2, and N3 the sizes of the array then a reference to this array will look like T ( &ra )[N1][N2][N3] = a; If you need to declare a reference to the element of the array that (the element) has the type T[N2][N3] then you can write...
61,890,766
61,894,422
how can i split a vector <string > and acces what i need in it?
I take the input from text file. Inputs are similar with the example given below. size 5, turn_count 3, entity 1 ACDEF 2x2, entity 2 BDFHC 4x5, entity 3 CDHGF 5x5, turn 1 2x3 4x5 5x4, turn 2 3x3 4x4 5x3, turn 3 3x4 4x3 5x2. I assign this input line by line into a vector<string> by getline(). I want to access...
As user31264 suggested you could write a split function and split every line you got into its words. IMHO this is a better and more flexible split function though: #include <vector> #include <string> #include <sstream> std::vector<std::string> split(const std::string& str, char delimiter) { std::vector<std::string>...
61,890,892
61,891,228
Is there difference in string concatenation using shortand operator?
I tried appending character to end of the string using + operator to a coding problem .That solution was giving memory limit exceeded. Then I saw solutions using += to append character. Is there any difference between the two in case of time complexity or memory complexity ? Example - My solution string arrangeWords(s...
temp = temp + c; creates a temporary temp + c (which would probably require (slow) allocation) before to assign to temp. (Complexity is O(n)) temp += c; reuse buffer if large enough (complexity O(1)), else reallocation should be done (and then, it would be "similar" to above method) (complexity O(n)). (amortized comple...
61,891,141
61,891,435
std::span constructor, libcxx vs libstdc++, template vs non-template?
Strolling through the code of libcxx's std::span, I noticed that the first two value constructors (number 2 and 3 on cppreference) were not templates. _LIBCPP_INLINE_VISIBILITY constexpr span(pointer __ptr, index_type __count) : __data{__ptr} { (void)__count; _LIBCPP_ASSERT(_Extent == __count, "size mismatch in spa...
The iterator-constructor for std::span you mention was proposed in P1394R4. According to libc++ C++2a Status, this paper has not yet been implemented in libc++. libc++ implements P0122R7, where there is that pointer-constructor (replaced by the iterator-constructor in P1394R4). P1872R0 is also related: span should hav...
61,891,450
61,891,526
Ignore leading whitespace reading from file
I am trying to read from an input file to my C++ program but am having whitespace issues. I have an external .txt input file in the format: ABC DEF GH IJK LMNO PQ Each line contains two "words" and a random amount of whitespace between the first and second "word" on each line. Each line ends with a new line after ...
There is no need to use getline in a white space separated file. operator >> will ignore leading white space and stop at the first occurrence of white space so you can use that to read your file like std::string NextWord(ifstream& inputStream) { string nextWord; inputStream >> nextWord; return nextWord; } ...
61,891,597
61,896,336
Sharing a part of an array in MPI
I am thinking about a problem that requires sharing an array as follows: Suppose int array[10] and there are 3 processes so that; process 0 gets array[0:3] 3 is included. process 1 gets array[3:6] 6 is included. process 2 gets array[6:9] 9 is included. However I am not sure how to split this array between processes li...
A non-standard-conforming implementation using MPI_Scatterv: int arr[10]; const int counts[] = {4, 4, 4}; const int displs[] = {0, 3, 6}; int recv_buff[4]; MPI_Scatterv(arr, counts, displs, MPI_INT, recv_buff, 4, MPI_INT, 0, MPI_COMM_WORLD); displs are just simple offsets and are specified as follows: Original a...
61,891,856
61,892,485
passing the QAction's QString text as an argument
I have a QAction which when clicked emits a triggered signal which calls the slot method RegroupEtudes::OnNouvelleEtude connect(ui.actionNouvelle_tude, &QAction::triggered, this, &RegroupEtudes::OnNouvelleEtude); It is possible for void RegroupEtudes::OnNouvelleEtude() to take a QString parameter if I change its defin...
Since Qt5, you can use a lambda expression and the new connect synthax to pass an extra parameter to your slot: QAction *actionNouvelle_tude = new QAction(tr("Nouvelle étude..."), this); connect(actionNouvelle_tude, &QAction::triggered, this, [openAct, this]() { this->OnNouvelleEtude(o...
61,892,363
61,892,415
Inserting a string at the end of every word of a string
I'm trying to add "ay" to the end of every word of a string I get via getline in cpp, but the result prints infinite "ay"s without breaking. I used the 'insert' function for this: #include<iostream> #include<string> using namespace std; int main() { int add; string s; getline (cin,s); for (int i = 0; i ...
After you add the ay, the index i needs to be updated, otherwise, you continue the index at the recently added y, and the previous space is found again. Just bump the index in the loop if ay is inserted: if (s[i]==' ') { add=i-1; s.insert(add,"ay"); i += 2; // bump i appropriately }
61,892,533
61,892,709
Why arguments of comparator function of std::stable_sort() must be set constants?
Hello fellow programmers, I was solving a problem on leetcode that needed sorting in stable order. Problem link: https://leetcode.com/problems/rearrange-words-in-a-sentence/submissions/ I noticed that arguments of comparator function of std::stable_sort() must be set constants otherwise following compile time error is ...
Because that's what the function requires. Quote from cppreference on std::stable_sort (emphasis mine): The signature of the comparison function should be equivalent to the following: bool cmp(const Type1 &a, const Type2 &b); While the signature does not need to have const &, the function must not modify the objects...
61,892,547
61,892,677
Why can't I put a float into a ptr of any type without any kind of conversion going on?
I'm currently writing a runtime for my compiler project and I want general and easy to use struct for encoding different types (the source language is scheme). My current approach is: struct SObj { SType type; uint64_t *value; }; Pointer are always 64 or 32 bit wide, so shouldn't it be possible to literally p...
Not really. When you write C++ you're programming an abstraction. You're describing a program. Contrary to popular belief, it's not "all just bytes". Compilers are complex. They can, and will, assume that you follow the rules, and use that assumption to produce the most efficient "actual" code (read: machine code) poss...
61,893,431
61,904,006
c++ floating point only floats some numbers
When I testBed my code, it will not put any decimals on my numbers. However, all but one number get decimals in my second test. I am not sure if it is just that float only puts decimals when the user needs them, or if I am missing something in my code. Do I need to specify how many decimals to include, and if so, how ...
Use std::cout.precision and std::fixed to output currency: #include <iostream> // ... cout.precision(2); cout << std::fixed; cout << "\tIncome" << setw(11) << right << "$" << setw(11) << right << income; cout << setw(5) << right << "$" << setw(11) << right << income <<"\n";
61,893,460
61,894,189
error C2109: subscript requires array or pointer type (MEX, Windows 10)
I am using mex to implement C++ codes in MATLAB on Windows 10. I want to modify the elements of a 2D array that I created but I keep getting this error. Below are the codes and the error message. #include <omp.h> #include "mex.h" #include "matrix.h" // net.idx_phiz{m}(:,1:num_v) => get_index(net.idx_phiz{m}, num_v) e...
This line is incorrect, B and val are pointers to double, and therefore cannot be indexed twice, only once. B[i][j] = val[i][j]; Think of the data in a MATLAB array as a 1D array, where the columns of the logical array are stacked. Given m rows and n columns, one can obtain the location in memory for the matrix elemen...
61,893,920
61,894,080
C++ operator overloading not possible with **
Suppose I have a class called Complex, why I'm allowed to define the following function: Complex operator+(Complex& c1, Complex& c2); But I can't write: Complex operator**(Complex& c1, Complex& c2);//for power
From over.oper, you can see which operators can be overloaded. You will notice that ** is not one of the valid operators to overload. There is, however, the ^ operator you can use (although it's usually meant for bitwise) As mentioned in the comments, you cannot create new operators this way, so you cannot make a new o...
61,893,948
61,894,434
Why is template parameter deduction not working with a variadic template class where only the first two parameters are specified?
I have a variadic template class which takes two fixed template parameters and additionally a variable list of parameters. When I create an instance I want to specify the first two parameters and have the rest deduced from the arguments passed to the ctor. But it does not work, the variadic part seems always to be empt...
You might use template constructor, and std::function as factory: template <typename Interface, typename Implementation> class Wrapper { public: template <typename... CtorArgs> Wrapper(CtorArgs&&... args) : m_factory([=](){return std::make_unique<Implementation>(ctorArgs...);}) {} Service& GetService() {...
61,894,024
61,894,209
C++ Classes Importance of Public and Private Domains
I'm fairly new to C++ and just recently learned about classes. When you define something in the private domain of a class, such as a class function, how exactly is it limited to that class? For example: class Example { void dosomething(param1, param2); }; Would that mean that you can't access the class function in...
Would that mean that you can't access the class function in the main function? Yes. If so, what's the point of doing that, wouldn't that mean you can't use it at all? Of course you can use it. From within other functions of this class: class Example { void dosomething(int a, int b) { std::cout << "dosom...
61,894,128
61,894,213
C++ runtime_exception with string + integer
In C++ I am throwing a run time exception like below, throw std::runtime_error("abcdefghijklmnopqrstuvq"+12); The exception that is thrown doesn't have the initial few characters. terminate called after throwing an instance of 'std::runtime_error' what(): mnopqrstuvq Aborted (core dumped) Can someone explain this...
One of the definitions for runtime_error takes a const char*, which is what you are passing it. This section of code: "abcdefghijklmnopqrstuvq"+12 Takes the pointer to this const char* and increments it by 12 (which happens to be m in the string). When you do this: "abcdefghijklmnopqrstuvq"+std::to_string(12) you ar...
61,894,417
61,894,492
What causes the following difference in implicit lambda capture behavior?
The following compiles fine, N is implicitly captured in the lambda fn (C++17): void f() { const int N{42}; auto fn = []() { return N; }; } (https://godbolt.org/z/JpyZHC) The following does not compile (delay is not captured), and I have a hard time figuring out what the exact reason is. Because delay is not a PO...
std::this_thread::sleep_for takes it's parameter by reference. This means that it needs to ODR-use delay and that requires that the lambda capture delay. In your first example you do not ODR-use N so it's not required that it be captured.
61,894,698
61,928,844
Will c++ functions/methods implemented in *.cpp file be NEVER inline expanded?
There are already many good explains about "inline" in c++, such as this and this... But generally most of them are talking about "even though a func with inline prefix, may or may not be expanded", or about "it's up to the compiler...". When I am refactoring my old codes recently, I need to decide whether keep or mov...
Will c++ functions/methods implemented in *.cpp file be NEVER inline expanded? This is an implementation issue, specific to your particular C++ compiler. If you use a recent GCC as your C++ compiler, you could be interested by compiler flags such as -Wall -O0 -fno-inline (or, on the opposite, optimizing with -flto -f...
61,894,744
61,895,308
Converting a bitmap (bmp) to png with transparency (Windows c++)
I need to convert bmp files to png files while treating one of the colors in the bmps as transparent. My app uses MFC, but I am not tied to using MFC in the solution. I am doing this while porting from gdi to Direct2D, so I do have access to Direct2D (although I'm a true novice with Direct2D). I would like to avoid gdi...
This should do: void CImageCopy(CImage& dest, CImage& src) { // rescale user image dest.Destroy(); dest.Create(src.GetWidth(), src.GetHeight(), 32, CImage::createAlphaChannel); HDC hdc = dest.GetDC(); src.AlphaBlend(hdc, 0,0,src.GetWidth(), src.GetHeight(), 0,0,src.GetWidth(),src.GetHeight()); ...
61,894,784
61,894,863
Why "*** stack smashing detected ***: <unknown> terminated Aborted (core dumped) " error is showing in this code?
I am implementing a simple selection sort code in this way: int* in_sort (int a[], int l) { int i, j, k, m; for (i = 0; i < l - 1; i++) { m = a[i]; k = i; for (j = i; j < l; j++) { if (a[j] < m) { k = j; m = a[j]; } } ...
I think it's this code: if (i != k) { int t = a[i]; a[i] = a[j]; a[j] = t; } You probably meant a[k], not a[j] here. j will equal l, and so a[j] is just outside the bounds of the array.
61,894,920
61,895,583
Are C++ nested classes the right approach for encapsulation?
I have a global class TRK that has many members and methods. I wanted to organize these by sorting them into different named categories, e.g. Fitting, such that the namespace of the main class isn't overcrowded. In a perfect world, I would want this example to work: class TRK { public: // constructors ...
Constructing instances of nested classes If you want the constructor of TRK to in turn cause the construction of a TRK::Fitting variable, the definition of TRK::Fitting must be completely known to it, a forward declaration is not enough. However, once you do that, you can intialize member variables of the nested class ...
61,894,983
61,895,289
Converting from std::string to const unsigned int
My payload is stored in a std::string xyz (holds binary data), and I need to pass it to a function that takes it as const unsigned int*. How would I convert from std::string to const unsigned int*? I tried reinterpret_cast<const unsigned int*>(&xyz.front()) but it is not working! The function prototype is as follows: v...
Don't use std::string to store binary data; that class is specifically designed for working with strings. It feels like there was original C code that was using a char array to store a sequence of bytes and translated that to std::string for C++. In this case, it's not being used as a string, so it doesn't make sense...
61,895,236
61,900,134
Why does each member function get its own .text.* section?
I understand that name mangling happens. What I don't understand is this: class MyClass{ public: int doStuff(int a){ return a+1; } }; int main(){ MyClass myclass; myclass.doStuff(2); return 0; } > g++ -c -O0 blah.cpp && objdump -h blah.o blah.o: file format elf64-x86-64 Sections: Idx Name ...
Not quite a duplicate but see my answer to this related question for deeper detail. g++ (or clang++) compiles the inline definition of a class member function such as int MyClass::doStuff(int) as the inline definition of a weakly global symbol, e.g._ZN7MyClass7doStuffEi1 in the object file whenever the translation unit...
61,895,388
61,922,989
pointer is changing its address after a function call
I have a question about this portion of code: const float *dest = (float*)varPtr1.memoryPointer; float temp; ReadFromMemory(temp); . . continue the rest of treatment with 'dest' and 'temp' Everything works fine and when reaching the second line the 'dest' have the correct value, but, after calling the function ReadFr...
The solution for this problem is to not pass temp as reference, instead, i pass its pointer. So the function declaration becomes like following: void myClass:: ReadFromMemory(T *var, int var_pos)
61,895,546
61,903,767
Is it possible to manage with Azure Pipeline net core projects with dependencies on c++ projects?
I've tried to compile c++ projects with VSBuild@1 or with CMake@1 but when I try to publish or test net core projects, I' ve got many problems. here part of the pipeline - task: VSBuild@1 displayName: 'Build projects cpp' inputs: projects: '$src/**/*.vcxproj' platform: 'x64' configuration: 'release' ...
Is it possible to manage with Azure Pipeline net core projects with dependencies on c++ projects? The answer is Yes. However it's recommended to use Msbuild task or VS build task instead of DotnetCore task to build your .net core project in this specific scenario. (Add a nuget restore/dotnet restore task before bui...
61,895,932
61,896,019
How to append to a file in C++?
I want to print some data to a file with a few separate calls. I noticed that the default behaviour for a write overwrites the previously written data. #include <iostream> #include <fstream> using namespace std; void hehehaha (){ ofstream myfile; myfile.open ("example.txt"); myfile << "Writing this to a file....
Open the file in app mode instead myfile.open("example.txt", std::ios_base::app);
61,896,004
61,897,858
How to make an enum recognized by other classes
I'm creating an enum called RiskFactor in my SimulationEngine base class. class SimulationEngine { public: enum RiskFactor { interest_rate, equities, volatility }; SimulationEngine(double horizon, Wrapper<valuationFunction>& theFunction_, RiskFactor simulatedRiskFactor); virtual void DoOnePath(double vol, d...
The declaration of RiskFactorMultiply needs to qualify the enum name with the enclosing class name. class valuationFunction { // ... virtual void RiskFactorMultiply(double factor, SimulationEngine::RiskFactor risk) = 0; // ... }; The same applies to the enum values, if for example RiskFactorMultiply wanted to make...
61,896,178
61,896,416
C++ program compiled without problems but doesn't run
There is my code. It does compile without any errors, but it doesn't output anything. When I open program.exe it instantly is closed even if I add "cin.get()" at the end of program. When used in terminal it doesnt cout anything. echo $? returns a false value. I have other similar programs (for testing OpenMP) which are...
The problem is here: long double pi, sum[num_threads]; num_threads must be a compile time constant and it is not, since you're getting its value at runtime. If you want to get its value at runtime create a dynamic array, like so: int i, nthreads; long double pi; long double* sum = new long double[num_threads]; then ex...
61,896,203
61,896,254
Unable to use virtual function in C++ child Class
I am making a virtual function program where there are three classes Person, Professor and Student. Person is inherited by both Professor an Student publicly. Here I want to input some parameters in professor and student. To input and output them I have made getdata and putdata in each class. In person class these func...
This function: void pushdata() { cout<<name<<" "<<age<<" "<<publications<<"\n"; } does not override the pure virtual function putdata in Person. Instead do: void putdata() override { cout<<name<<" "<<age<<" "<<publications<<"\n"; } Note that if you put override on the functions you wa...
61,896,229
61,896,430
EXC_BAD_ACCESS error while running merge sort recursion algorithm
I tried to run my merge sort algorithm using recursion program on Xcode11 for MacOSx but I'm getting the following error - Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ffeef3ffff8) I'm not able to find the solution for this. Please find below the code that I used. #include <iostream> #include <vector> using namespac...
You have infinite recursion. Your mergeSort function always calls itself (twice), leading to a stack overflow. At the very least you should put something like if (arr.size() <= 1) return arr; at the beginning of your function. But you may well have other problems too. It took me about two minutes to find this problem...
61,896,299
61,896,963
How to resolve the sonarqube static code analysis error "Explicitly define the missing copy constructor, move constructor .." in C++
I am getting the below sonarqube static code analysis error: Explicitly define the missing copy constructor, move constructor, copy assignment operator and move assignment operator so that they will not be implicitly provided. I am getting the above message at the below Destructor declaration in the header file: ~CCPSD...
Here do I need to follow the rule of 5 by providing the Destructor, copy constructor and the copy-assignment operator, move constructor and the move-assignment operator? Depends on what you do in the destructor. In most cases, if you need a destructor, then you need to follow rule of 5 because in most cases the impli...
61,896,612
61,896,692
Cannot convert from 'const std::string [3]' to 'std::string'
Here is my code: #include <iostream> #include <vector> #include <string> using namespace std; template<int N> class Arguments { protected: string arguments[N]; public: Arguments(const string(&arg)[N]) : arguments{ arg } {} string operator[](const int &i) const { return arguments[i]; } }; int main() { ...
Arrays are not copyable in C++. So this is never going to work Arguments(const string(&arg)[N]) : arguments{ arg } {} You could use std::array<std::string, N> instead, or you could copy the array element by element in the body of the constructor.
61,896,666
61,898,288
Function call leads to no output
This is my first time posting here, I'm new to c++ and was trying to implement maximum subarray problem Problem: When the function max_subarray is called, it never returns resulting in no output What I have Tried: I have narrowed the problem down to cross_max_subarray function because when I remove the function call fr...
There were a few errors that combined to make it a bit harder to debug your program. A quick tip is to try to build your code in as many small pieces as you can and test each one as you are making it. This helps you find problems early on. The first issue that I had to change was that I had a problem with assigning the...
61,896,938
61,897,119
How this reading of std::vector works?
I've seen this block of code that is supposed to read a vector in a very strange method to me. I want to know what does mean: for(auto &it: a) cin >> it; I already know that this for loop iterates trough whole vector, but the part: auto &it and cin >> it; confuses me; because, I'm used to reading vector elements usi...
You may be being tripped up by somebody's poor naming. The it in for(auto& it:a) is not an iterator but an element of the vector. Walking through the program one line at a time int n; Declared a new int to store the size of the vector. cin >> n Gets the size of the vector from the user. vector<int> a(n); Declares ...
61,897,076
61,897,220
Merge tuple and integral instances into tuple of references
I've encountered strange behavior when trying to construct a tuple of references from a mix of tuples and integral values. Given the following: struct A { int v = 1; }; struct B { int v = 2; }; struct C { int v = 3; }; A a; std::tuple<B,C> tpl; I'm trying to create a third tuple which holds references to all instances...
This is a simple typo: constexpr auto as_ref_impl(Tuple t, std::index_sequence<Is...>) { Tuple is taken by value, so a local copy is made, and the reference is made relative to it. You should take Tuple by reference instead, constexpr auto as_ref_impl(Tuple& t, std::index_sequence<Is...>) {
61,897,197
61,897,560
How to show localized text and custom icons in context menu shell extensions using IExecuteCommand and verbs?
I was considering developing a context menu shell extension following the new Windows 7+ approach based on IExecuteCommand, as described in this blog post: Simplifying context menu extensions with IExecuteCommand instead of the classic IContextMenu approach I'm more familiar with. I have a couple of questions about t...
IExecuteCommand is used for shell verbs that are registered statically in the Registry and have a "DelegateExecute"="{clsid}" value associated with them. The menu text for a static verb is taken from the display text that is registered for the verb, and that text is displayed as-is, it cannot be localized, as there is...
61,897,238
61,897,290
How are inherited data placed (arranged) in a derived class?
Im inheriting multiple variables from a super class to a base class and I want the class to have all the variables packed in the descending order (largest types are on the top and the smaller types are on the bottom) but since im inheriting a considerable amount of data, I have no clue on arranging them so that the fin...
Is there any order which the inherited data get packed to the base class or is it randomly placed or does it get aligned before it is being packed to the final base class? The order of sub objects in memory is not random. Members that are declared first are before members with same access that are declared later. Ord...