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
66,679,330
66,679,955
Convert unicode codepoint to utf-16
In C++ on Windows how do you convert an xml character reference of the form &#xhhhh; to a utf-16 little endian string? I'm thinking if the hhhh part is 4 characters or less, then it's 2 bytes, which fit into one utf-16 character. But, this wiki page has a table of character references and some near the bottom are 5 dig...
Unicode code-points (UTF-32) are 4 bytes wide and can be converted into a UTF-16character (and possible surrogate) using the following code (that I happen to have lying around). It is not heavily tested so bug reports gratefully accepted: /** * Converts U-32 code point to UTF-16 (and optional surrogate) * @param utf3...
66,679,569
66,680,564
Adding many data in QListView without "not responding"
for a project I need to integrate a lot of data in a QListView, I get the data from a QThread and store it in a QMap<QString, QString>, until then I have no problem of crash or freeze. But when in my QThread I browse my QMap to call for each element the function that will add the QString in the QListView, then I have a...
If your dataset is large, you probably need to implement your own model that uses the data in the fashion you're storing it. Models in Qt are tricky, but once you've done a few they begin to make sense. I've got an example on my github: https://github.com/jplflyer/qt-TreeViewDemo. It's probably not perfect. I wrote it ...
66,680,291
66,680,993
recursively finding arithmetic mean of vector
Just an academic exercise but it doesn't work with many inputs for some unknown reason. #include <iostream> #include <vector> using namespace std; double sum (const vector<double>&, size_t = 0); int main () { vector<double> in; double temp{0}; while (cin >> temp) in.push_back(temp); cout << sum(in) << end...
You're running out of stack due to the deep recursion. If you rewrite to be tail-recursive, gcc will replace the recursive calls with jumps if you enable any optimization, and only use constant space: double sum_t (const vector<double>& v, size_t it, double acc) { if (it + 1 >= v.size()) return acc; return su...
66,680,627
66,680,826
Inline assembly to bytecodes during preprocessing/compilation?
I have a program which I would like to patch during runtime that is composed of many long functions. I figured it would be easier if I could patch specific ranges of instructions inside the functions instead of just completely rewriting them. To do this, I'd like to create a function which, given the inline assembly, s...
You can use asm outside a function to assemble any sequence of instructions you like, and create labels to mark the start and end. Then you'll have these bytes in memory, and can copy them where you like. asm(".text \n\t" ".global my_code \n" "my_code: \n\t" "frob %rax \n\t" "grind $12345, %rbx \n\t" ...
66,680,732
66,680,845
Inherited class needs parameter for base class constructor
I made 2 managed classes in C++ clr, and I have a constructor on the base class. The derived class is inheriting from the base one, and I believe that since my constructor on the parent class has parameters not equal to void, that when I call it to be inherited it needs a parameter for the constructor. I believe this b...
Your subclass doesn't need a constructor with arguments, but all constructors need to call the base class constructor properly. As the base class doesn't have a default constructor, you need to do something like this: class Query : public ConnectDB{ private: public: Query(): ConnectDB("") { ... } }; The thing...
66,680,768
66,680,906
How to convert a specific element of a String into an int Arduino/C++
I was working on a converter project using Arduino/C. At a certain point in my code, a String sequence of 0's and 1's is generated, as an example: my_string = "01101";. I want to process this data in a for loop like shown in this minimal example: String x = "01011", y = "00011"; // These variables necessarily must hav...
If you are sure that the characters of my_string will always be numerals, then the typical method of obtaining a char numeral's numeric value is by just subtracting '0'. This works because the ASCII values for the numerals are arranged in order, so by subtracting '0', you're subtracting their offset (48) from the actu...
66,681,326
66,681,391
Making a circle with '*' C++
I am making a circle and the code works fine but the problem is that even though it is working the circle is not perfect, or close as it can be. My code: #include <iostream> #include <math.h> int main() { int radius = 6; int i,j; for (i=0; i<=2*radius; i++) { for (j=0; j<=2*radius; j++) ...
std::cout << "*"; std::cout << " "; You're printing one asterisk but two spaces. These statements need to print the same number of characters. With the right font, two asterisks "**" looks pretty good: As does asterisk-space "* ":
66,681,529
66,723,346
Subtracting two CV_64FC3 matrices and keeping the negative values
As far as i know, subtracting two non-float matrices yields expected results but subtracting two CV_64FC3 (and CV_32F for that matter) matrices clips the negative values to 0.0 and normalizes the result between 0.0 and 1.0. I know these limitations and read related documentation but still couldn't subtract two matrices...
The problem was in this part; lowpass1 = (-high_b1 * lowpass1 + high_a0 * pyramid[i][j] + high_a1 * pyramid[i][j-1]) / high_b0; lowpass2 = (-low_b1 * lowpass2 + low_a0 * pyramid[i][j] + low_a1 * pyramid[i][j - 1]) / low_b0; Since lowpass1 and lowpass2 are used in the formula and the left hand side of t...
66,681,634
66,681,824
How can I fix double deleting of dynamically allocaated memory caused by using an object of a class in another class?
I have the following code, in which I dynamically allocate memory, and then it deletes it two times in the destructor, causing an error. How can I go about fixing this? (Nothing wrong, see edit below). class Song { private: char *name; public: Song (char *name = "") { this->name = new char[strlen(name)...
It doesn't delete your char array two times, it creates two instancies of your class, so it allocates memory for two strings, then it deletes this memory at destructor. There isn't any double free in your code, what could be the source of your problem (but shouldn't crash your program) is that you assign a string litte...
66,682,103
66,682,943
Segmentation fault when running an OpenMP parallel for loop
For the following code, I only want to parallelize its last part which calculates the second norm of each vector (length of each vector is different) but I am getting an error of segmentation fault. Also, I am not sure whether I am using reduction for the sum in the right place or not. Another point is that I think I o...
The segmentation fault is caused by the private clause which does not copy the vectors. It initializes them to default empty vectors. Use firstprivate instead if you want to perform a copy from the "master" thread. That being said, c can be shared here. Furthermore, here is several important points: sum must be initia...
66,682,261
66,682,364
Can a vector contain stacks?
I know that you can have a vector as the storage container for a stack though I'm wondering if you can have the data types stored in a vector as stacks. So if I had a vector named vector1, could vector1.at(2) return a stack instead of a data type such as int or double? I'm hoping that when the vector doubles in size, i...
The answer is yes, and the answer for your question in comment is: stack_name.push(element); Also, look at this example: #include <iostream> #include <vector> #include <stack> using namespace std; int main() { stack< int, vector<int> > stckk; stckk.push(2); stckk.push(21); stckk.push(45); stckk.push(76)...
66,682,321
66,682,592
How to set and out imaginary numbers in c++
I have an assignment to show the roots of a quadratic equation, which usually are imaginary numbers. I am wondering how can I produce two roots and what to do in the case of an imaginary root. Here is what I have done so far. (first time using this site so I am not too familiar with etiquette and the tools yet so forgi...
When you #include <complex> you are just telling the compiler to include a type template that is part of the standard library that implements complex arithmetic. You then need to actually instantiate the template and use that type for it to do anything for you. For example, #include <iostream> #include <complex> #inclu...
66,682,349
66,805,622
How can you specify a custom GCC/G++ compiler location using Gradle's cpp-library and cpp-application plugins?
We need to specify a custom GCC/G++ compiler location using Gradle's cpp-library and cpp-application plugins. According to the docs tool chain section: Linux To build on Linux, install a compatible version of GCC or Clang. The C++ plugins will discover GCC or Clang using the system PATH. Prepending the PATH environme...
Finally found that this worked: model { toolChains { gcc(Gcc) { path '/custom/path/to/gcc-7.1.0/bin/' } } }
66,682,615
66,682,655
How can i solve Was not declared problem in my code?
Hello i am a newbie on C++. I tried to run my first Class code but it didn't work it what is my problem please help me. #include <iostream> #include <string> using namespace std; class Car { public: string brand; string model; int year; }; int main() { Car carobj1; carobj1.brand = Ford; carobj1....
You forgot to put your model names and brand names in quotes, so the compiler does not understand that these are strings. Car carobj1; carobj1.brand = "Ford"; carobj1.model = "Mustang"; carobj1.year = 1969; Remember, in C++ all text must be surrounded by " otherwise the compiler will think it is a name of something (c...
66,682,681
66,682,776
i don't understand the prototype of unordered_set constructor
in constructor of unordered_set : explicit unordered_set ( size_type n = /* see below */, const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& alloc = allocator_type() ); i don't understand the line const hashe...
hasher, key_equal, and allocator_type are all template parameters with default types assigned in the declaration of the template class. For example, hasher defaults to std::hash<Key>: template< class Key, class hasher = std::hash<Key>, class key_equal = std::equal_to<Key>, class allocator_type = std::al...
66,682,909
66,687,238
Last Element in my Array is a large number that I never inputted
I'm storing the results of a "Dice Roll" in an Array. Everything seems to be working fine, except the last value of the Array is a ╠ (-858993460)? I tried troubleshooting and its happening right in the beginning and I don't know why. const int QDice = 3; int Domain = 6 * QDice; int CD[6 * QDice]{}; do { cout << "Ar...
C++ array index starts from 0, so the array CD[] range is from 1 to 17. When the Domain becomes 18, the array is out of bounds. I suggest that you could modify the code to the following code. do { cout << "Array CD[" << i << "] = " << CD[i] << "\n"; i++; } while (i <= Domain - 1);
66,683,621
66,683,898
Does the current standard guarantee to invoke the destructor for subobject when the initialization of the complete object throws an exception
In section except.ctor, the rule states: As control passes from the point where an exception is thrown to a handler, objects with automatic storage duration are destroyed by a process, specified in this subclause, called stack unwinding. [...] If the initialization or destruction of an object other than by delegating...
By the plain wording of [except.ctor]/3, it applies to objects with any storage duration, as long as they are subobjects of an object whose construction was terminated by an exception. This should not be controversial. However, the wording of [except.ctor] has changed over time, and this seems to have created some issu...
66,683,772
66,687,381
What is the rules of type deduction while passing pointer to template argument
I'm learning how to use template in C++11 and I just read an article about template, it showed me the rules of type deduction with reference. For example, template<typename T> void f(const T& param); int x = 27; const int cx = x; const int& rx = x; f(x); // T is int, param's type is const int& f(cx); // T is int, pa...
As you know, type deduction in templates falls in three different categories, wherein parameter type of the template function is either a 1) reference or pointer, 2) a forwarding (a.k.a universal) reference, or finally 3) neither pointer/reference or forwarding reference. So, if you have a pointer, type deduction is wo...
66,683,831
66,684,266
-std=c++11 undefined reference to vtable for -- Chess
I've an issue and I can't solve it (with google). As practice I write a program about chess. There is a general piece class: pieces.h : #ifndef PIECES_H #define PIECES_H [...] class piece{ public: bool dark; //0 = light, 1 = dark virtual std::vector<position> sovereign_movement(); types identify; // enum ...
When you include a header file, the contents of that file replace the #include line. So when pieces.cpp starts like this: #include "pieces.h" #ifndef PIECES_H #define PIECES_H std::vector<position> piece::horizontal(position a){ std::vector<position> sol; for(int i = 1;i<=8;i++){ sol.push_back(position...
66,684,041
66,684,108
Is there a way to initialize an object after it had already been declared
In C++, I'm looking for a way to call a constructor after it had already been declared with a specific type, or something with similar behavior. The code: #include <iostream> using namespace std; class Class1 { public: Class1() { } } class Class2 : public Class1 { } int...
The answer to the question is YES. One can "re-initialize" the object:- [...] Class1 Object; //Instantiation of the object Object = Class1(); //Re-initialize [...] The challenge would be with the assignment operator.
66,684,380
66,685,133
stranger "may be used uninitialized in this function [-Wmaybe-uninitialized]"
Any idea? this is the log: util.h: In function ‘bool BusyBees()’: util.h:162:17: warning: ‘bestHashBee’ may be used uninitialized in this function [-Wmaybe-uninitialized] data[1] = x >> 8; ~~^~~~ miner.cpp:512:14: note: ‘bestHashBee’ was declared here uint32_t bestHashBee; ^~~~~~~~~~~ this is ut...
Let's take a look at the code: uint32_t bestHashBee; // at this point bestHashBee is an integer, but it could be any integer // you have not told it what value it should have. It might be 0 it might be // 2879872. It depends entirely on what was in that memory location before. unsigned char beeNonceEncoded[4]; // bee...
66,684,762
66,684,982
How to get a registry read function to work properly? (c++)
When I compile and run the following code snippet (in visual studio 2019), it runs but returns an incorrect value of Key Value: 000000D1E14FF920 and actual bytes read was: 12 instead of Key Value: 18363 and actual bytes read was: 6 here is the code #include <Windows.h> #include <iostream> #include <string> #include <...
You are mixing char and TCHAR APIs. It is clear that RegGetValue() is returning a Unicode wide string, because 12 bytes is correct for a 6-character null-terminated wchar_t string. So TCHAR is mapping to wchar_t in your build, and thus RegGetValue() is calling RegGetValueW(). You are trying to print out that wide st...
66,684,898
66,685,129
Why does a pointer change address when I call a function?
I am trying to implement a linked list in C++. int main() { ListaEnlazada <int> l1 (5); //l1.imprimir(); l1.insertar(10, 0); l1.imprimir(); } template<typename T> class ListaEnlazada { public: ListaEnlazada(T inicial) { cabeza = new Nodo <T> (inicial); tamano = 1; } void ins...
The problem lies in your insert function - nuevo_nodo is being declared as a local variable. As long as you're in insertar, it will appear to be functioning as normal, but once you leave, your new node is lost and the head points to junk data. Changing this to new Nodo<T> (and altering the references to it later in the...
66,686,189
66,688,813
share list between process c++
I'm new to c++ and have a little problem. So I have a UdpServeur which receives messages and I would like another program I wrote to use them. So I used FIFO tube but it's very heavy for the code. Then I used locks with a simple .txt file but it's not very clean and not good for the project. For my project people told ...
Using lock guard is not complex, and you even do not need to care about releasing it. std::mutex list_mutex; // Access from thread 1: { std::lock_guard guard(list_mutex); // Work with the list } // Access from thread 2: { std::lock_guard guard(list_mutex); // Work with the list } Both list and list_mute...
66,686,294
66,819,921
how to put all odd number in left an even number in right on array
Given two arrays of integers A and B of sizes N and M respectively. Write a function named MIX with four arguments, which will produce and return a third array named C. such that the following sequence is followed. -All odd numbers of A from left to right are copied into C from left to right. -All eve numbers of A from...
#include <vector> #include <algorithm> static bool is_odd(int n) { return n % 2 == 1; } // Let a == {3, 2, 1, 7, 6, 3} as example static std::vector<int>::iterator order_odds_first_and_reverse_evens(std::vector<int> &a) { // a == {3, 2, 1, 7, 6, 3} const auto first_even{stable_partition(a.begin(), a.end(), is...
66,686,616
66,687,463
CodeForces stones on table, code cannot pass one test case I cannot understand why
This is the question - There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. Input - The fi...
int main() { string s; size_t q, a, c; cin >> q; cin >> s; a = s.length(); // You may not use q here, because you are modifying the string length, so when the // loop enters the next iteration, q is no longer valid. // Since you are comparing it with the next item, you must reduce the c...
66,686,629
66,686,720
Pointer arithmetic and arrays in C++
I tried to make a new char array and add to it chars. I wanted it to do by pointer. I know that is possible to move pointers in array by pointer arithmetic , so I wanted to use it. However it doesn't work and I don't know really why. Any idea why i can't use pointer arithemtic in array? #include <math.h> #include <iost...
This is very convoluted *++temp1 = 0; *--temp1 = ch; temp1++; The idiomatic way would be this: *temp1++ = ch; *temp1 = 0; But most importantly print(temp1); is wrong, because temp1 does not point to the string but it points to the end of the string. You want this: int main() { int max = 128; char* thestring = new...
66,686,636
69,451,592
.clang-format: avoid formatting between @code and @endcod
Our code documentation also includes code examples like \** Example * @code * int main() * { * return 0; * } * @endcode After calling clang-format the parts between @code and @endcode are also formatted, which I do not like. Is there a way to force clang-format to avoid formatting statements between @code and @endcod...
I have not found other solution, I think we are obliged to add //clang-format on and //clang-format off comment
66,686,991
67,230,715
fileapi::WriteFile() doesn't send an input, if processthreadsapi::STARTUPINFO::hStdError is set (ffmpeg)
I'm trying to capture my screen using ffmpeg in a different thread (which I create using processthreadsapi::CreateProcess()) so I'd be able to do something else in the main thread, and redirect ffmpeg output, so it wouldn't pop up in the console for the user to see. To stop filming, I send a 'q' input using WriteFile()...
To answer my own question, the issue was that when the handle pipe, where the ffmpeg output is going to, fills up, it stops the ffmpeg process, until I'd clear some space for new text to come in. This is happening, because ffmpeg continiously outputs recording info. I hope this will be useful for someone :)
66,687,103
66,687,270
Why does a calculation error occur when this double value is multiplied by 2 in C++?
#include <iostream> #include <stdint.h> #include <bitset> #include <sstream> #include <string> #include <iomanip> using namespace std; int main() { uint64_t int_value = 0b0000000000001101000011110100001011000000110111111010111101110011; double double_value = (*((double *)((void *)&int_value))); printf("doub...
You are running into denormalised numbers. When the exponent is zero, but the mantissa is not, then the mantissa is used as is without an implicit leading 1 digit. This is done so that the representation can handle very small numbers that are smaller than what the smallest exponent could represent. So in the first two ...
66,687,416
66,687,445
Deleting an object by function in C++
I'm a bit curious about a pointer's behaviour in C++. So I have this little program to test out and unfortunately it run well. #include <iostream> class Test{ public: Test(){ std::cout<<"Test Created!\n"; } ~Test(){ std::cout<<"Test Destroyed!\n"; } }; void ...
Yes, the delete operator only calls the destructor and frees the memory occupied by the object that the pointer points to. The pointer itself is a local variable like any other and cannot be (and does not need to be) deleted. It may be worth noting that calling delete ptr; does not change the value of ptr, so after del...
66,687,629
66,687,694
Why does the C++11 random generator use reference or non-reference parameter has different list?
Can anyone explain why the function foo1 returns the same value? #include<iostream> #include<random> #include<ctime> using namespace std; int foo(default_random_engine& random, uniform_int_distribution<unsigned int>& dis1){ return dis1(random); } int foo1(default_random_engine random, uniform_int_distribution<un...
foo1() takes its parameters by value, so copies of them are made each time foo1() is called. It generates the same number on every call because it is using the same generator state (ie, the same seed) every time, any updates made to the copies are not reflected back to the caller's original objects. That is not the ca...
66,687,631
66,687,938
Define a child class from an abstract parent class, which inherits from an abstract parent class
The situation is (hopefully) clear with the code. We have two (in this example pure abstract, but that isn't necessary) classes. Is this possible to define the class C? What happens to the pointer c_ptr? Do I need to delete it in the class B destructor? class C : public B { private: public: C(); ~C(); int d...
In short, no, this is not possible. In your example we have the following constraints: B is child of A C is child of B is child of A For every super class, there must be an object created as well. So for the instantiation of a B, there will be created an A first. The same way for a C there will be constructed a B which...
66,687,838
66,690,257
_mm256_loadu_epi64, _mm256_storeu_epi64 require avx512vl?
Playing with avx2 intrinsics for the first time (on a system which supports avx2, but not avx512). Neither from the prototype or the information I got from the intel intrinsics reference, would I assume, that _mm256_loadu_epi64 and _mm256_storeu_epi64 are avx512 functions. But if I compile the code with only -mavx2, I ...
Use _mm256_loadu_si256((const __m256i*) ptr) and _mm256_storeu_si256, and see also How to emulate _mm256_loadu_epi32 with gcc or clang? Those intrinsics with nicer arg types (void* instead of __m256i*) were introduced with other AVX-512 intrinsics, but the most efficient way to do a 256-bit load is using AVX1 vmovdqu ...
66,688,857
66,689,088
How to get decoded String from UTF16 encoded String
I'm trying to get decoded String from UTF16 encoded String. Current value of UTF16 is \u5f00\u53d1\u8005 and original string is 开发者 In other words, \u5f00\u53d1\u8005 ==> 开发者 using C++`. How can I do this using C++?
Assuming you have it stored in a wchar_t array or std::string it's just a matter of correctly setting your environment to deal with wide chars, take this console example: #include <iostream> #include <fcntl.h> int main(){ _setmode(fileno(stdout), _O_WTEXT); const wchar_t str[] = L"\u5f00\u53d1\u8005"; //std::ws...
66,688,919
66,688,944
Why is the output as follows for this piece of code?
#include <iostream> #include<list> using namespace std; int main() { list<int *>l; for(int i=0;i<3;i++) { int a = i; l.push_back(&a); } cout<<endl; for(auto i=l.begin();i!=l.end();i++) { cout<<**i<<" "; } return 0; } The output I get is 2 2 2. I...
a is a local variable in the scope of for loop, it'll be destroyed when iteration ends. That means the pointers push_backed into l are dangling. Deference on them like **i later leads to UB, anything is possible. EDIT What is the difference between the two? Isn't also the pointer destroyed after the loop runs once?? ...
66,689,002
66,713,714
xtensor's "operator/" slower than numpy's "/"
I'm trying to transfer some code I've previously written in python into C++, and I'm currently testing xtensor to see if it can be faster than numpy for doing what I need it to. One of my functions takes a square matrix d and a scalar alpha, and performs the elementwise operation alpha/(alpha+d). Background: this funct...
A problem with the C++ implementation may be that it creates one or possibly even two temporary copies that could be avoided. The first copy comes from not passing the argument by reference (or perfect forwarding). Without looking at the rest of the code its hard to judge if this has an impact on the performance or not...
66,690,841
66,691,675
std::setprecision sets the number of significant figures. How do I use iomanip to set the precision?
I have always found iomanip confusing and counter intuitive. I need help. A quick internet search finds (https://www.vedantu.com/maths/precision) "We thus consider precision as the maximum number of significant digits after the decimal point in a decimal number" (the emphasis is mine). That matches my understanding too...
You can try using this workaround: decltype(std::setprecision(1)) setp(double number, int p) { int e = static_cast<int>(std::abs(number)); e = e != 0? static_cast<int>(std::log10(e)) + 1 + p : p; while(number != 0.0 && static_cast<int>(number*=10) == 0 && e > 1) e--; // for numbers like 0.001: thos...
66,690,939
66,691,122
Is it possible to pass a dynamically allocated array to a function that requires an array reference?
A note upfront: I know that it's not a good idea to do what I ask for here. This is just a question arising from morbid language curiosity, not from practical use. The rules that I apply here are completely arbitrary. Let's say we have a function that is exactly defined as the following. It must not be changed to anyth...
You can use reinterpret_cast for this. Using an alias for the array type to make the code easier to read, you would have something like: void my_func(int (&arr)[10]) { for (auto e : arr) std::cout << e << " "; } int main() { using array_t = int[10]; int* my_arr = new int[10]{1,2,3,4,5,6,7,8,9,10};...
66,691,776
66,691,959
std::is_same else static assert
I like to to specialize a function with respect to a template type. This works fine with std::is_same. Now, I like the code to not compile, if a not specialized type is given. template <typename T> constexpr double get(const T& item) const { if (std::is_same<T, SOME_TYPE>::value) return item.get(); if (...
Simplest way is doing something like this: template <typename T> constexpr double get(const T& item) const { static_assert( std::is_same<T, SOME_TYPE>::value || std::is_same<T, SOME_OTHER_TYPE>::value, "Getter not implemented for Type"); if constexpr (std::is_same<T, SOME_TYPE>::value) { ...
66,691,886
66,692,170
Why can't I construct a string_view from range iterators?
C++20 adds a constructor for basic_string_view which takes two iterators. However, when I try to construct a string_view with the iterators from a common range I get an error. #include <iostream> #include <ranges> using namespace std::views; int main() { auto words = "the quick brown fox" | split(' ') | transform...
Notice the requirements imposed on the iterator constructor for std::string_view: This overload only participates in overload resolution if It satisfies contiguous_iterator, End satisfies sized_sentinel_for for It, std::iter_value_t and CharT are the same type, and End is not convertible to std::size_t. Your range ...
66,691,938
66,691,973
My c++ compiler is giving the correct output but the codeforces compiler for c++ is giving a wrong output
Question - A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay i·k dollars for the i-th banana). He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas? Input - The ...
You used the value of the variable s without initializing it. s is non-static local variable, so it is default-initialized and it means no initialization will be performed for int. Initialize it to proper value before the loop to fix the problem.
66,692,130
66,692,397
A general question about pointers and dynamic memory
I'm currently dealing with total of 21 megabytes of plain text data that is written onto several files. It consists of some strings and integers. Containing them properly is important for me to be able to loop through them in various ways so I'm using a fairly complex typedef for my container such as typedef std::tuple...
Now assuming that stack memory is 1 megabyte and inserting 131072 pointers into this vector could fill it up since the vector itself is allocated in the stack. That is false. The vector variable itself is on the stack, but not its elements. sizeof(vector) is roughly 3 pointers, no matter what it contains. The backing...
66,692,252
66,692,662
Error when compiling: passing (something) as 'this' argument discards qualifiers
I am writing a code and this is a small part of a method i want to implement in a class that inherits from a base class: const string & getType() const override { this->type = "Greedy"; return type; } and this is the private part of the class: private: const string type; }; Also this is the method im ove...
The first problem is that const string type; is a const member. That means, after it's initialization you can't assign any new value to it. The second problem is, that the getter is also marked const: // VVVVV const string & getType() const override Meaning you can't modiy member data from insid...
66,692,254
66,692,452
"initial value of reference to non-const must be an lvalue" can be valid when returning from function?
Recently I was studying lvalue and rvalue concept. When I do int&z = 0 ; I get an expected error like : initial value of reference to non-const must be an lvalue However, when I do this with a function that returns lvalue reference like: int& get_value(){ static int x = 10; return x; } //This line turns out...
The error message makes it quite clear: initial value of reference to non-const must be an lvalue (emphasis mine). So long as the reference is initially bound to an l-value, everything is fine (so long as you don't use a reference to a stack local variable, of course). The reference returned from get_value is bound t...
66,692,453
66,692,661
Create diagonal matrix in Rcpp but the result is wrong
The code is supposed to create a diagonal matrix with value 1. // [[Rcpp::export]] NumericMatrix filterOne(int g_size){ NumericMatrix filter(g_size, g_size); int ptr, ptr2; for(ptr=0;ptr<g_size;ptr++){ Rcout << ptr << endl; filter[ptr, ptr] = 1; } // the following pr...
I think the issue is with how you have accessed the NumericMatrix elements. You should use ( ) instead of [ ]. The following works: // [[Rcpp::export]] NumericMatrix filterOne(int g_size){ NumericMatrix filter(g_size, g_size); int ptr, ptr2; for(ptr=0;ptr<g_size;ptr++){ filter(ptr, ptr) = 1; } ...
66,692,943
66,693,054
Override method with shared_ptr Base type with shared_ptr Derived type
I am attempting to create an abstract method for cloning classes derived from base and returning them as a shared_ptr like so: class Base { public: virtual std::shared_ptr<BaseSymbol> clone() = 0; }; class Derived : public Base { public: Derived(const Derived& derived); std::shared_ptr<Derived> clone(); }; ...
covariance is only possible with pointer/reference. For smart pointer, you have to "duplicate" the interface: class Base { public: std::shared_ptr<Base> clone() const { return std::shared_ptr<Base>(vclone()); } virtual ~Base() = default; protected: virtual BaseSymbol* vclone() const = 0; };...
66,692,966
66,713,307
Memory corruption error on Windows build of MPIR
I'm running into a memory corruption error with the Windows version of MPIR, which shows up in the following minimal test case. Microsoft (R) C/C++ Optimizing Compiler Version 19.25.28610.4 for x64 Compiled MPIR from the github checkout (have verified just now that the problem still reproduces with the very latest vers...
I never did track down the exact cause of the problem, but I think it had something to do with the build process, which used MSBuild via many layers of abstraction, making it almost impossible to be sure exactly what was really going on. I've put together a distribution of MPIR using a simple transparent build process,...
66,693,008
66,693,164
Is it possible to have C struct as a member of C++ class?
let's say I have following plain C struct typedef struct { uint16_t id; uint32_t address; uint8_t type; } Config; typedef struct { Config cfg; uint32_t ready; } Instance; My question is whether it is possible to define a C++ class which has an attribute of Instance type i.e. class A { public: A()...
No, you don't need to use the constructor to initialize. Compiler knows it's a "struct" data type because you defined it that way. Plain C structures also valid c++ structures so there's nothing called as plain c structure. Learn more about compilers here: https://www.freecodecamp.org/news/c-compiler-explained-what-is-...
66,693,305
66,694,374
How to place input value in arrays c++?
New to c++. I want to take the input values in scoreCurrent and place them into different arrays depending on whether they're above the average or below the average. I tried looking for solutions from different websites and youtube but none worked so far. How do I do this? I apologize if my whole code is a mess and tha...
My guess is that scorecurrent is an array (and index the offset in scorecurrent)? If you think that this will work std::cin >> scoreCurrent; then the problems are: where in scorecurrent will the input be placed (you don't use index)? (if you want to give scores for all indices) when does the input stop? Apart from t...
66,694,144
66,695,878
C++11 enable_if on return type of subscript operator of template parameter
I'm working with vector classes containing either integer or floating point types. I'd like to choose one or the other function template accordingly, but the only way to deduce the type is through the subscript operator []. Is there a way to use enable_if<is_integral< ... on the return type of the [] operator of the te...
Some general suggestion I would avoid using namespace std which your code implies (almost) that you use. You can shorten and make more readable std::enable_if<T>::type and std::is_integral<T>::value by writing them as std::enable_if_t<T> and std::is_integral_v<T> respectively (search for "Helper types" here, for instan...
66,694,192
66,694,398
Using push_back for vector<vector<string>> correctly with a for & while loop in C++?
Basically I have image coordinates in the form of strings. I have a vector of those 2 strings and and I am parsing it using some delimiters. The parsing is being done correctly and the first push_back to the vector"<"string">" vector1 as well. But when I apply a push_back again after the while loop to store vector1 in ...
At first grance, it looks like you forgot to clear vector1 before each iteration. To clear vector1, add call to clear() here: for(int i=0; i<resulvec.size(); i++) { vector1.clear(); // add call to clear() here while ((beg = resultvec[i].find_first_not_of(delims, pos)) != string::npos) { ...
66,695,039
66,695,299
c++ using namespace std causes errors with bind () and a waiver with the iterator
I have the problem when I add using namespace std; that the compiler says that there is no confection to long for bind. simple example: #include <winsock2.h> #include <mutex> #include <iostream> using namespace std; int main() { WSADATA wsa; long rc = WSAStartup(MAKEWORD(2, 0), &wsa); SOCKADDR_IN addr; ...
Don't use using namespace std;. You've run into the main problem it causes: There exists a function in the std namespace called bind. There exists a function in the WinSock2 Sockets library called bind. By including using namespace std, the compiler does not know which one to pick. Regardless, using using namespace s...
66,695,111
66,695,502
Getting negative outputs for large enough inputs in vector
I was writing an algorithm for a problem that goes as follows: Consider an algorithm that takes as input a positive integer n. If n is even, the algorithm divides it by two, and if n is odd, the algorithm multiplies it by three and adds one. The algorithm repeats this until n is one. For example, the sequence for n=3 ...
You can see how this works with this simple example #include <limits.h> #include <iostream> int main() { int n = INT_MAX; std::cout << "n=" << n << '\n'; std::cout << "n+1=" << n + 1 << '\n'; unsigned m = UINT_MAX; std::cout << "m=" << m << '\n'; std::cout << "m+1=" << m + 1 << '\n'; } giving...
66,695,192
66,695,451
Binary search tree removal -- iop implemented with while loop instead of recursion
In this video (https://youtu.be/WgdzNyhj6BU) showing the implementation of a dictionary ADT, recursion is used to find the inorder predecessor. Around the 47 minute mark, the speaker says that a while loop could also be used. My question is can a while loop be used with the same function signature as was used for the r...
There are several solutions. One is to use a double pointer. TreeNode *& rightMostChild(TreeNode*& root) { TreeNode **n = &root; while ((*n)->right != nullptr) n = &(*n)->right; return (*n)->right; } If you don't like the double pointer, you can do it with a single pointer: TreeNode *& rightMostChi...
66,695,462
66,696,753
Modifying WSARecv data
It is necessary to modify the unencrypted data that the server sends before it is received by the client. int WSAAPI __WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount, LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, LPWSAOVERLAPPED lpOverlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine) { ...
WSARecv logic is complex, the easiest usage scenario is when it receives data immediately (overlapped not used) and the caller reads only to one buffer (dwBufferCount == 1). This function handles this scenario, rewriting the receive buffer and updating number of bytes received accordingly: int WSAAPI __WSARecv(SOCKET s...
66,695,570
66,695,780
how to print on the same line inside function, avoid flush
I want to display a progress bar however putting the printing code inside a separate function seems to invoke an std::flush as each time the progress bar is printing in a new line. This did not happen when the code was used inline The code: #include <iostream> #include <unistd.h> void load(int curr, int total) { s...
The first line in your function outputs \n, which is what makes it print on a new line every iteration. Fix: #include <iostream> void load(int curr, int total) { std::cout << '['; int pos = 50 * curr/total; for (int i = 0; i < 50; ++i) { if (i < pos) std::cout << '='; else if (i == pos) s...
66,696,053
66,696,169
passing nullptr to std::stoi
For the stoi function documented in the below reference, http://www.cplusplus.com/reference/string/stoi/ int stoi (const string& str, size_t* idx = 0, int base = 10); It is then used as int i_hex = std::stoi (str_hex,nullptr,16); Here the idx is not defined as constant pointer (size_t * const idx =0), why can we pas...
nullptr is not a pointer at all. It is a prvalue of type std::nullptr_t. But, it can be implicitly converted to any pointer type. Whether the pointer type is const, volatile, etc does not matter. So, the above code is fine.
66,696,680
66,696,735
Can't seem to allocate vector properly
I am attempting to write a program that takes hex string input and converts it to binary. For the life of me, I can't seem to write this properly. The main culprit so far is that I can't initialize the output vector in the hex_decode function properly. See the gdb output. I don't normally use c++ stl and string str...
You invoked undefined behavior by reaching at the end of non-void function hex_decode without executing return statement. add return output; before the } that represents the end of function body of the function hex_decode.
66,696,740
66,701,943
Is there a cleaner way to add an additional switch statement to this code?
#include <iostream> using namespace std; int main() { char grade; cout << "What grade did you earn in Programming I ?" << endl; cin >> grade; switch (grade) // This is where the switch statement begins { case 'A': cout << "an A - excellent work !" << endl; ...
If you must do it with just switch and nothing else, you could nest them to handle the 'A'-'D' and 'F' cases separately (at the expense of a redundant grade check). switch (grade) { case 'A': case 'B': case 'C': case 'D': cout << "YOU PASSED!" << endl; switch(grade) { case 'A': cout << "an...
66,697,289
66,697,781
Typecasting structs or classes to each other both ways
I'm fairly new to C and C++. For practice I created Vector structs (Vector2 & Vector3). Now I want one to be dynamically casted to the other. struct A { operator B() const { return B(); } } struct B { } works just fine, but as soon as I add operator A() const { return A(); } to struct B it throws all kinds...
You need to forward-declare the structs, and define conversion operators out-of-line, after the types have been fully declared. Here is an example which illustrates the idea: struct B; struct A { operator B(); }; struct B { operator A() { return A(); } }; inline A::operator B() { return B(); } B foo() {...
66,697,557
66,697,622
Arduino static progmem cannot be accessed via variables
I cannot reference a 3d array of bytes stored in memory via variables letter[18][0]=letters[L][18][0]; letter[18][1]=letters[L][18][1]; letter[19][0]=letters[L][19][0]; letter[19][1]=letters[L][19][1]; for(int i = 20;i<32;i++){ static int test = i; letter[i][0]=letters[L][i][0]; letter[i][1]=lette...
You cannot access variables marked as PROGMEM like standard variable. You have to use special functions to read values from them. PROGMEM - Arduino Reference It will be like this: letter[18][0]=pgm_read_byte_near(&letters[L][18][0]); letter[18][1]=pgm_read_byte_near(&letters[L][18][1]); letter[19][0]=pgm_read_byt...
66,697,866
66,700,036
Is it possible to pass char* between COM objects
I need to modify application that is written on Delphi and C++ and uses COM. And I've seen quite often that COM wrappers always use WideString and BSTR, even though in the end dll that is used works with plain char*. So it's impossible to communicate between COM objects without unicode strings? Some links for further r...
To pass around an 8-bit char string in COM, you can either: use SysAllocStringByteLen() to create a binary BSTR that holds the raw char characters as-is. The receiver can then copy the char characters as-is from the BSTR. use SafeArrayCreate()/SafeArrayCreateVector() to create a SAFEARRAY holding VT_UI8 elements, and...
66,698,168
66,698,572
Strange behavior in GCC: rvalue ref and lvalue ref are covariant return types
I have this little piece of code: struct Res { }; struct A { virtual Res &&foo(); }; struct B : A { Res &foo() override; }; It compiles in GCC, but not in Clang: https://godbolt.org/z/65rffW . According to the standard language quoted here, the lvalue reference is not a covariant return type for an rvalue re...
This was actually the subject of a standard defect report, a quite old one: Covariant functions and lvalue/rvalue references Section: 11.7.3 [class.virtual] Status: CD2 Submitter: James Widman Date: 1 September, 2009 [Voted into WP at March, 2010 meeting.] 11.7.3 [class.virtual] paragraph 5 requires tha...
66,698,994
66,699,133
Using rand() in switch statement
I've been writing a randomizing program, but when I put a randomizing function, rand() into it the output is always the same. It's written in c++. Example: #include <iostream> #include <stdio.h> #include <stdlib.h> #include <time.h> using namespace std; int main() { srand(time(NULL)); int genre, rVal, rCat; cin...
Are you sure that genre is a char ? Your switch test '1' not 1..
66,699,028
66,825,306
Matching variadic template arguments using an AST Matcher
I have the following sample code. template<class T, class... Args> T add(T first, Args... rest) { return first + add(rest...); } int add(int a, int b) { return a + b; } When I run it through clang-check -ast-dump, I get the following tree. FunctionDecl 0x4df0b08 <tmp.cpp:2:1, line:4:1> line:2:3 add 'T (T, Arg...
For future reference, I found a solution to this. It is actually possible to define custom matchers within a check. namespace { const AstTypeMatcher<PackExpansionType> packExpansionType; const internal::VariadicDynCastAllOfMatcher<Stmt, PackExpansionExpr> packExpansionExpr; } // You can also use the macros fro...
66,699,249
66,699,437
string subscript out of range error when assigning variable to function
In order to become more familiar with cpp I began making a program that takes the derivative of simple polynomials using the power rule. So far, it is working fine for polynomials such as 5x^2+4x. However, if the polynomial contains a constant (like 5x + 3) I get a string subscript out of range error. I used the debugg...
You're not checking the return value from find correctly in differentiateTerm. This causes inputTerm[varPos] to access out of bounds. The correct check is if (varPos == std::string::npos) In the subsequent if statements, since you have a valid subscript in varPos, you should check that against the size of the string. ...
66,700,479
66,700,930
C++: Reuse operator+() in derived class
Is there a way to reuse the operator+(...) method of the base class in a similar manner that the assignment operator operator=(...) is used in the example below? IMPORTANT: I don't want to use abstract classes/virtual methods, I'm only curious about the example below for me to fully understand the "basic" usage of inhe...
My initial comment, while a bit flippant, still holds true. With that said, I re-implemented your problem into something that will compile to demonstrate a solution. First, your class (as shown) does not need an assignement operator overload. It also does not need a copy constructor, destructor, move constructor, or mo...
66,700,746
66,700,917
glfw not working in sublime text in linux
when i run the code it says Segmentation fault (core dumped) [Finished in 1.5s with exit code 139] i do not know what to do but i remove it runs well without crashing unsigned int buffer; glGenBuffers(1, &buffer); glBindBuffer(GL_ARRAY_BUFFER, buffer); glBufferData(GL_ARRAY_BUFFER,6* sizeof(float), posotions, GL_STATI...
You didn't initialize GLEW. It can be done with glewInit(); GLEW is the library that gives you those OpenGL functions.
66,700,796
66,701,022
Why is Deleting a Heap Allocated Byte Array Causing a Heap Corruption
I am trying to create something like the stack but it is heap allocated. However, when the program tries to exit, it says that there is a heap corruption detected. I am using visual studio 2019. Here is a file with a class called vstack that uses a heap allocated byte array: #pragma once #include<iostream> #include<str...
int main() { Vstack stack; At this point, stack.capacity is 2, from the default constructor. stack.Create("x", 15); At this point, stack.capacity has doubled to 4, and you just wrote a long long, which is guaranteed to be at least 8 bytes. Hence, you just overwrote the end of your buffer. Perhaps instead of i...
66,701,047
66,701,124
Implementation of binary search
I am trying to implement a version of binary search that is a function template. It is to take two iterators that define the range, and the value it is searching for. If the value is found in the range, the function template is to return an iterator to the value. If not found, it is to return the off-the-end iterator. ...
{ if (beg==end) return end; handles the empty range correctly. That is the right answer, fundamentally, to the question you are asking. The next step is to back up and see how the std library handles it. The std library exposes two functions, lower bound and upper bound, plus one that does both -- equal range. Low...
66,701,132
66,701,250
Why is a `std::remove_cv<_Iter>::type` not a type?
I have two versions of the what I'd expect to be the same function but gcc says version 1 is valid while version 2 gives a expected a type, got 'std::remove_cv<_Iter>::type' I don't quite understand this error, as I'd expect that the using statement required a type, and wouldn't automatically promote a 'std::remove_cv...
You need to use the keyword typename to tell that the dependent names std::remove_cv<V>::type is a type. return std::is_same<u_underlying, typename std::remove_cv<V>::type>::value; // ^^^^^^^^ In the using statement typename is not needed again since C++20. In some contexts, only type n...
66,701,840
66,750,947
bazel test vs direct execution
I'm using GoogleTest with bazel and when I run bazel test :tokens_test (rule defined below) I have a failing test, but when I run the compiled tests I see the expected result. It is failing because the test can not open the test data file. The directory layout and the BUILD rule for the test I'm running look like this:...
Define your data as data = ["test_data/test_input1.txt"] Use absolute path: ./tokens/test_data/test_input1.txt To find it run your test with a bazel test --sandbox_debug -s. The last command will looks like that one: SUBCOMMAND: # //:hello_test [action 'Testing //:hello_test', configuration: faff19e6fd939f490ac11578d...
66,702,171
66,702,221
Calling std::thread() around a function works differently
Is there any reason why this code here: int main(int argc, char* argv[]) { Main::Init(); std::thread worker(Main::Mainloop); worker.join(); Main::Free(); return 0; } should work differently to this code here: int main(int argc, char* argv[]) { Main::Init(); Main::Mainloop(); Main::Fr...
All of those libraries in some way interact with OpenGL and therefore are very sensitive to what thread they're being executed on. The current OpenGL context is thread-specific; each thread has its own current context, and a context can only be current within one thread at any time. Creating a GLFW window creates an Op...
66,702,275
66,713,335
Cannot open source file "d3dx9.h" With DirectX installed
EDIT: It was a cache issue I had to restart Visual Studio code It says its not included but I use this code #include <d3dx9.h>; and here are my Directories (Include Directores: $(DXSDK_DIR)Include;$(IncludePath)) (Library Directories: $(DXSDK_DIR)Include;$(IncludePath)) I see a lot of people ask this question but no on...
It was a cache issue with VSC 2019
66,703,177
66,703,597
Time complexity in C++
what is the time complexity of converting a vector into set in c++. Can it can be done in O(n). if i am copying vector into set like this, set s(v.begin(), v.end()); then what is its time complexity
It is O(N * log(N)) from the documentation. It is linear if the vector is already sorted (also in the documentation). You may be interested in std::unordered_set. It's constructor taking two iterators is O(N) on average (see here).
66,703,725
66,743,888
Templated Q_OBJECT base class
I have a couple of classes: A.h class Abase_obj : public QObject { Q_OBJECT Q_PROPERTY(QAction* playAction READ playAction CONSTANT) public: Abase_obj(QObject* parent = nullptr) : QObject(parent) {} virtual QAction* playAction() = 0; signals: void someSignal() slots: virtual void baseSlot() = 0...
The code is correct. The mistake was in my qbs dependencies. File A.h just haven't been compiled and haven't been correctly included to the B_inh.h, so I had these linker errors
66,703,989
66,706,184
C++: Is it safe to change value of iterator of a while loop?
#include <iostream> using namespace std; int main() { int x = 10; while (x>0) { x = x-1; cout << x << "\n"; } return 0; } In this simple program, I change value of iterator of a while loop. But is it safe to do that? Will the program run into segmenta...
I'm guessing now, but if your loop look something like the second example you provide, the segmentation fault could be caused by the check in the while statement. ... index = 0; while (all_vectors[index].size() > 0) { ^-- This, this could be the problem ... index += 1; } The reason being ...
66,704,105
66,704,195
What is "Expression must have class type"
I used std::malloc() on a pointer which is a member of an object. And in a method, it threw an error. [...] class SomeClass { public: void method() { this.ptr = std::malloc(4); } int* ptr; } [...] And it throws an error saying: Error: Expression must have class type What is the problem in my ...
It's probably because this is a pointer and to try to access it using .. Moreover malloc returns a void* so you must cast Try writing this instead : this->ptr = static_cast<int *>(std::malloc(4));
66,704,151
66,704,366
C++ Unresolved External with class method
I am trying to make a function which randomly generates a certain number of Circle objects, depending on the parameter. I have implemented the function, but am getting Unresolved External Symbol errors. Can I not generate objects in a class method? The professor wanted us to implement it in a class method, I think. The...
Your code is missing the Circle:: specifier in front of the method, meaning you declared a function not a method: std::vector<Circle*> generateCircles(int numberOfCircles) { //uses dynamic memory allocation to generate a desired number of Circle instances std::vector<Circle*> circles(numberOfCircles); for (...
66,704,596
66,705,623
Converting lambda(int)->int to std::function<int(float)>
Why C++ compiler doesn't give warning or error for this code? std::function<int(float)> f = [](int x) -> int { return x*x; }; std::cout << f(4.2) << '\n'; Is there a way to prevent this kind of implicit conversations? (to write a wrapper or a helper methods for example to generate an error)
Why C++ compiler doesn't give warning or error for this code? The compiler option for gcc for cases of this category is commonly -Wconversion, but it doesn't seem to work for your particular case. I tried a lot of other flags but without success. You can obtain a comprehensive warning with MSVC on warning level 4 for...
66,704,672
66,706,404
How to avoid swapping negative numbers when arranging for all negative and positive numbers in array
This is the question I am looking at: Given an unsorted array Arr of N positive and negative numbers. Your task is to create an array of positive and negative numbers without changing the relative order of positive and negative numbers. So, here's what my naive mind thought! I use a variation of insertion sort. Here ...
Note that the assignment says "Your task is to create an array"... so if I understand correctly, you are not asked to modify the input array, but to create one. So then the solution is quite trivial: Create an array of the same size as the input array Iterate the input array and copy negative values into the new array...
66,704,693
66,705,363
printing vowels in c++ char array
i made this code to print out vowels from array. i have wrote code before but back then only error was that it was printing whole array instead of just vowels. i wrote it today again i dont think that 2nd time i have made any change in code than the previous one(if i made i cant see) but now it takes blank input of arr...
Try this: #include <iostream> using namespace std; int main() { int size = 0; cout << "Enter the size of array="; cin >> size; char *arr= new char[size]; /*Requires a pointer to declare a dynamic array or a vector*/ cout << "Enter the letters array " <<endl; for (int i = 0; i < size; i++) { ...
66,705,070
66,705,400
Casting all members of struct automatically
I have a template class which has a lot of variables, all of the same type template<typename T> struct Location { T lat; T lon; T alt; // and roughly 20 variables more of type T }; In my code T is either float or double, depending on the precision I need. Sometimes I need to cast between these two stru...
I'm afraid there's not such a way. I would probably write templated copy constructor and assign each variable manually. You'll do it just once now, and then everytime you add a new variable - it's not a big deal IMO.
66,705,571
66,705,689
creating a segment tree but it remains null. I am unable to find error?
basically I am trying to pass the pointer where address of new block needs to be stored void buildseg(class node *p,int a[],int l,int r) { class node *temp; temp=createnode(); int sum=0; for(int i=l;i<=r;i++) { sum=sum + a[i]; } temp->val=sum; temp->leftrange=l; temp->rig...
Your function prototype void buildseg(class node *p,int a[],int l,int r) makes it impossible that the function changes the first parameter from the caller. When you call it like that: class node *x = NULL; void buildseg(x,a, 4, 5); The line p=temp; only changes the copy p in the function, but not x at the caller. You ...
66,706,974
66,707,011
If statement still going through when my condition should be false
I am attempting to write a Caesar encryption program. I have written two functions. The first (sanitize) allows me to make sure that all strings are fully capitalized, here is the source code. string sanitize(string message) { for(int i; i < message.length(); i++){ message[i] = toupper(message[i]); } ...
if (direction = 'R') { } else if (direction = 'L') { These lines are wrong. = in C++ is an assignment operator and it sets the value of a variable in lefthand to the value of righthand. Then, it is evaluated to the new (righthand) value. Another point is that nonzero values are considered as true when used as ...
66,707,105
66,707,434
Where can I find official documentation on reading OutputDebugString() messages?
I am writing my own version of DebugView using this article: https://www.codeproject.com/Articles/23776/Mechanism-of-OutputDebugString as a starting point. According to the article OutputDebugString() first locks a mutex named "DBWinMutex" and the writes to a 4096 bytes area of shared memory named "DBWIN_BUFFER" and th...
This is asking about implementation details, that are deliberately not publicly documented. The documented way to receive data from a call to OutputDebugString is to call WaitForDebugEventEx and evaluate OUTPUT_DEBUG_STRING_INFO DEBUG_EVENTs. The documentation comes with a full sample on how to write the debugger's mai...
66,707,127
66,707,246
How to simplify the operator< for a class with some members for the use in std containers
I have a simple class with 4 Ids. I want to use this class as a key in a std::map, std::set or any other std container. So I just implemented the operator< as seen in the sample code. The sequence should by like an SQL ORDER BY m_lIdTicket, m_lIdUser, m_lIdAddress, m_lIdRole struct S_DATA_CRMTICKETROLES { public: ... ...
std::tie helps before operator <=> of C++20 and bool operator==(const S_DATA_CRMTICKETROLES&) = default. struct S_DATA_CRMTICKETROLES { public: auto as_tuple() const { return std::tie(m_lIdTicket, m_lIdUser, m_lIdAddress, m_lIdRole); } bool operator<(const S_DATA_CRMTICKETROLES &r) const { ...
66,707,364
66,707,527
c++ how to use constexpr value with operator []
The origin problem is I want to use const char* or char [] in template non-type arguments. Of course it is not supported now. So I want to write some code to convert char[] to std::integer_sequence. But I found a seriously problem. #include<utility> template<typename T, std::size_t n> constexpr auto f3(T (&a)[n]) { ...
constexpr functions might be called in non constexpr context, so parameters are never constexpr: a is not constexpr, so f2/f3 cannot use it in constexpr context. f1 is fine, a[3] is not used in constexpr context. and f1 can be used in constant expression with appropriate argument.
66,708,074
66,708,161
How does std::greater<> wоrk in a set?
I know how std::greater works. But when I read the API of std::greater since C++14 it has a default type of void. So, if we don't pass any template argument to greater it defaults to void as below. But the result is as expected in descending order. #include <iostream> #include <set> template< class T = void > struct g...
It works by having the call operator be a function template instead of a function. Compare the old version to the new specialisation: // greater<T> bool operator()( const T& lhs, const T& rhs ) const; // greater<void> i.e. greater<> template< class T, class U> auto operator()( T&& lhs, U&& rhs ) const; What makes th...
66,709,351
66,709,423
No output is shown when option 2 is chosen in C++
So after I enter my input in option 1, then I chose to continue. My input information are gone when choosing the option 2. I just started my programming course so please give me a lot of advice. This is the output enter image description here struct Human { string name; string foods; string date; }; char ...
You create a new Human me; in every iteration of the do-while loop. When you read input for that me in one iteration, the me in the next iteration won't know about that. Read about "scope" and moving the declaration Human me; outside of the loop will probably do what you expect.
66,709,398
66,710,384
Emscripten: fatal error: 'tr1/unordered_map' file not found
So I am trying to compile the following code using emscripten: // this is test.cpp #include<iostream> #include<string.h> #include<fstream> #include<tr1/unordered_map> //needed to use unordered maps in C++. not needed C++11 onwards #include "C:\Users\<myusername>\Documents\PROGRAMMING\examplefolder\pugixml-1.11\src\pug...
Why is this file not found by emcc? Is there an alternate way to handle unordered_maps in C++? Because it moved to <unordered_map> in 2011. If it is in neither place, you have a very old clang, and it has no unordered_map.
66,709,417
66,923,360
Linking a shared library to an executable using CMAKE
Below is a simple CMake project. On Linux, everything compiles, and running main gives expected output. On Windows, the compilation is successful as well, main doesn't give any output, though. I can't really explain the error, but the moment I call getNumber() function from main, main no longer works. I can't even put ...
To make it work on Windows, dll and executable has to be in the same folder. You can either copy them manually or set output directory in your top CMake file like this: set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "yours_output_directory"). This way, both executable and dll will end up in yours_output_directory.
66,709,705
66,712,776
C++20 std::source_location yield different column numbers between free function and template functions
Consider the template function g() and free function f(): #include <iostream> #include <source_location> auto g(auto...) { std::cout << std::source_location::current().column() << "\n"; } auto f() { std::cout << std::source_location::current().column() << "\n"; } int main() { g(); f(); } Compiled with GCC-trunk get...
I file a PR 99672 to GCC Bugzilla. Jakub Jelinek (one of the GCC contributor) reply me: I think the standard doesn't specify anything about what exactly the column should be, so using different columns isn't standard violation. but he still did a patch to fix it.
66,709,918
66,709,969
Reading .txt using ifstream and writing to new .txt file with ofstream, but only first line works
I am trying to read a textfile, text.txt with text representing hexadecimal values: 0123456789abcdef 0123456789abcdef 0123456789abcdef 0123456789abcdef 0123456789abcdef 0123456789abcdef 0123456789abcdef I am supposed to read this file and use ofstream to write to a new file output.txt to write the binary equiavalent...
You used ofstream outfile; outfile.open("output.txt"); inside the loop. This makes the file opened in each iteration and this will clear the contents of file. You should move this befoer the while loop. Also note that your condition while (!myfile.eof()) is wrong. Instead of this, you should mo...
66,709,922
66,741,076
How to access js window object in emscripten's EM_JS method?
Basically I want to access window.location in a EM_JS method to call this javascript method from c++. I tried like this EM_JS(const char*, getlocation, (), { let location = window.location; let length = lengthBytesUTF8(location) + 1; let str = _malloc(length); stringToUTF8(location, str, length); re...
The above code in the question just worked, just that I need to wait until the main is loaded to call this method, it seems.
66,709,944
66,710,019
Difficulty in understanding c++ string literals
Here the below code is my some part of my program. It doesn't execute it says c++ forbids converting string constants to char*.How can I fix this error? #include <cstring> #include <iostream> using namespace std; class Bank { private: char name[20]; int acc; float amount; public: Bank() { ...
std::strcpy("", name); needs to be std::strcpy(name, ""); Although, setting aside the fact that std::string would be a far better type for name (the future King of England, Charles Mountbatten-Windsor, would not be able to be a customer), writing name[0] = 0; would be sufficient.
66,709,992
66,710,232
Forward declaration with Inheritance and include | incomplete type or expected class name
Can somebody help? Suppose, I have the following C++ files: Room.h #ifndef ROOM_H #define ROOM_H #include "Console.h" ... class Room { public: void room(); }; #endif // ROOM_H Room.cpp #include "Room.h" void Room::room() { Console::print(); } Console.h #ifndef CONSOLE_H #define CONSOLE_H #include "Room.h" ...
The includes are all goofed up. Delete the superfluous include directives from the files where they are irrelevant. Add include directives on the files where they are depended upon. Room.h #ifndef ROOM_H #define ROOM_H /* DELETE: because Room.h does not depend on it. #include "Console.h" */ // ... class Room { publi...
66,710,145
66,710,533
JSON data processing in c++14 (Boost)
I am new in C++ (I use most of the time embeded c). I have something like this JSON data: [10, "Session" , {"currentYear":"2048","accidents":10,"status":"Accepted"}] I am trying to process this data: boost::json::value testVal; boost::json::error_code ec; testVal = boost::json::parse(data, ec); So I have multiple it...
The straightforward would be Compiler Explorer for (auto& element : testVal.as_array()) { if (!element.is_object()) continue; if (element.as_object()["currentYear"].as_string() == "2048") { std::cout << element << std::endl; } } Though I recommend using the conversion facilities in the libr...
66,710,625
66,710,815
How has the second algorithm become more efficient than the first one and how is the right side of the subarray moving in the second algorithm?
Question - Given an array of n numbers, our task is to calculate the maximum subarray sum, i.e., the largest possible sum of a sequence of consecutive values in the array. The problem is interesting when there may be negative values in the array. The array = {-1,2,4,-3,5,2,-5,2}. First algorithm - int best = 0; for...
The first version does a brute force comparsion of all subarrays sums for subarrays starting at index a till index b, lets call those subarrays sums subsum(a,b). The second version is also rather brute force but uses the fact that subsum(a,b+1) == subsum(a,b) + array[b+1]. In other words: To know the sum of the first s...