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
69,792,470
69,792,605
How does this loop work? I am unable to understand it
for(int i=1;i<=n;){ f++; if((i++==p) || (i++==p)) break; } example1 : n=7,p=3,f=0; so the value of f should be 1, right? But it is giving f=2 as output example2 : n=7,p=4,f=0; it is giving output as f=2 example3 : n=7,p=5,f=0; it is giving output as f=3 Help me understanding this.
Case 1 When n=7,p=3,f=0 . Lets look at values of different variables while going through the for loop. Iteration 1 for(int i=1;i<=n;) //here n = 7 { f++; //here f becomes 1 that is now we have f = 1 if((i++==p) || (i++==p)) // variable i is incremented by 1 and becomes 2 because of the //first i++. But note t...
69,792,537
69,792,565
Limitting the number of numbers using substrings cpp
I'm having trouble limiting the number of letters I wasn't appearing. I'm trying to get just the last two but that has been a difficulty. This is what I did; if (year.length() > 2) { year = year.substr(0, 2); } For example, if you have the year 2016, just 16 is selected.
subString first parameter is the starting position and second is the number of strings from that position, so first, we take out the length of the string subtract -2 from it. the second parameter is 2 because we need two characters. eg : 2016 , first parameter is year subString(4-2,2); year.substr(year.length() - 2,2) ...
69,792,804
69,793,458
Why delegated constructor doesn't work as expected UE4
I am having issues with loading the asset for several weapons in the game, such as AK 47, M11, and so on, the issue here is that I created a c++ class for doing that work which will be header UCLASS() AWeapon_core : public AActor { private: USkeletalMeshComponent* m_skeletal_mesh; ...
Do you realize what you did here? static ConstructorHelpers::FObjectFinder<USkeletalMesh> WEAPON_MESH(*(mk_weapon_mesh_path + _path)); It's a STATIC LOCAL variable. It is initialized once. Only once as there is only one instance of AWeapon_core::AWeapon_core() function. All subsequent call to t...
69,793,032
69,793,056
How to pass ostream operator<< as a function in C++?
Is there any way I can pass an std::ostream operator<< as an argument in other function call? For example: #include <iostream> template <typename Visitor> void print(Visitor v, int value) { v(value); } int main(void) { std::cout.operator<<(5); // This works std::cout << 5; // This works print(std:...
You can pass a lambda instead. print([](int value) { std::cout << value; }, 5);
69,793,492
69,793,649
My "Roman numerals to integer" code wrong
Can someone tell me why my code is not working and giving the wrong output? I think the logic is correct so I'm not sure which errors I'm making. Thanks int romanToInt(string s) { unordered_map<char, int> map ={{'M',1000},{'D',500},{'C',100},{'L',50},{'X',10},{'V',5},{'I',1}}; int result = 0; ...
The thing that's wrong with your code is that you are comparing the ASCII values of characters rather than their numeric values. Also, you should not be adding map[s[i+1]] as you will be adding that value twice (once at step i and at step i + 1). Furthermore, you should be more careful with s[i+1], as the index may be ...
69,793,746
69,793,808
Why "iscntrl" returns 2?
I want to know why, when I print the instruction iscntrl, the return value is always 2? I also want to know why the result of the isalpha statement is 1024. For example: #include <iostream> using namespace std; int main() { char lettera = 'c'; char numero = '1'; isalpha(lettera)? cout << lettera << " è un ca...
The iscntrl() function return value: A value different from zero (i.e., true) if indeed c is an alphabetic letter. Zero (i.e., false) otherwise. The isalpha() function return value: A value different from zero (i.e., true) if indeed c is a control character. Zero (i.e., false) otherwise. So, it returns non-zero val...
69,793,811
69,793,872
How to test if member is integral in concept?
I'm trying to define a concept that tests if a particular member variable (in the example, 'x'), exists and is an integral type. I'm getting stumped though, since v.x returns an int& and thus the std::integral check fails. How can I make this work? #include <concepts> template <typename T> concept isIntegralX = requir...
You can change the concept as: template <typename T> concept isIntegralX = std::is_integral_v<decltype(T::x)>; decltype(T::x) yields the exact type int here. For multiple members you can template <typename T> concept isIntegralXandY = std::is_integral_v<decltype(T::x)> && std::is_integral_v<decltype(T::y)>;
69,793,888
69,794,413
Unresolved external symbol but the function is defined and implemented
I have a header file, defining the chunk class: #pragma once #include <vector> #include "Tile.h" #include "Numerics.h" namespace boch { class chunk { public: chunk(); static const uint defsize_x = 16; static const uint defsize_y = 16; std::vector<std::vector<tile*>> tilespace; ...
Thanks sugar for the answer. I deleted both header and .cpp files and readded them, and it worked like a charm. I suppose I have added either header or .cpp file just by directly adding a new file to the header/source folder instead of adding it to the project (RMB click on the project > add new item).
69,794,336
69,794,831
When initialising member with temporary, how to ensure a single call to temporary's constructor?
Suppose I have a wrapper: template<typename T> struct Outer { T inner; ... }; , and I want to create an Outer wrapping an Inner, like so: Outer<Inner> wrapper(Inner(...)); // Inner object is a temporary Is it possible to declare Outer/Inner such that creating an Outer object from a temporary Inner involves th...
I guess you are looking for this: #include <stdio.h> #include <utility> template <typename T> struct Outer { T inner; // Outer(T &&inner) : inner(std::move(inner)) {} template <class... Args> Outer(Args &&...args) :inner(args...) {} }; struct Inner { int x; int y; Inner(const int x, const int...
69,794,538
69,794,629
Function to pick a seemingly random index from an array<string>
I'm having a problem figuring out how to pick a random index from an array<string>. It's for a card game. Instead of shuffling the deck I wanna use the srand function, inside a function to seemingly pick a random number. But every thing that I try just fails. Here is part of the array: array<string, 52> cards = { "Ess...
int index = rand() % 52; string card = cards[index]; Use card variable as you wish.
69,794,817
69,806,149
How to share cv::Mat for processing between cpp and python using shared memory
I am using shared memory provided by boost/interprocess/ to share the cv::Mat between model and client (both C++). Now I need to use a model in Python. Can you please tell which is the best way to share the cv::Mat between C++ and Python without changing the present client. Thanks.
The task was completed using mapped memory to share the cv::Mat between C++ and Python process. C++ - use boost to copy cv::Mat to a mapped shared memory #include <boost/interprocess/shared_memory_object.hpp> #include <boost/interprocess/windows_shared_memory.hpp> #include <boost/interprocess/mapped_region.hpp> #incl...
69,794,825
69,795,542
C++ Project has triggered a breakpoint in Visual Studio 2019
I am new to using pointers (and Visual Studio too) and I'm trying to make a function which deletes the spaces ' ' from a const array. The function should return another array but without the spaces. Seems pretty simple, the code works in Codeblocks, but in Visual Studio it keeps triggering breakpoints. Any idea what am...
"It works" is the most devious form of undefined behaviour, as it can trick you into believing that something is correct - you're writing outside your allocated memory, and strcpy is undefined when the source and destination overlap. You used the wrong form of memory allocation: new char(100): a single char with the v...
69,794,826
69,795,589
How to provoke crash with c++ futures and reference to local variables?
I would very much like to understand Eric Niebler's warnings about c++ futures and dangling local references (in the section titled "The Trouble With Threads"). I, therefore, wrote a little program, repeated below: #include <iostream> #define BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION #define BOOST_THREAD_PROVIDES_FUTUR...
Like everyone says, believing that Undefined Behaviour would lead to a crash is misguided. It's a dangerous believe, because the consequences of UB are much more dire when there is silent data corruption, deadlocks, or indeed nothing easily observable for years (until your program suddenly launches that nuclear missile...
69,795,658
69,795,841
How to implement deep and shallow copy constructors without using a boolean parameter?
I have the following class: class A { int small; std::shared_ptr<B> big; }; Here, B is a class whose objects are expected to have a very large size. In my program, I have an original object of class A and then make multiple copies of it, then copies of the copies, etc. Sometimes, I need to make a deep copy, be...
Assuming B has a copy constructor, just add: class A { int small; std::shared_ptr<B> big; public: A clone() const { return { small, std::make_shared<B>(*big) }; } }; So clone() becomes the only way to deep-copy your data. That's the method used in OpenCV and Eigen for matrices: the copy is sh...
69,796,012
69,796,224
How to correctly use invoke_result_t?
I am having an issue with type traits that I don't understand, I have created the below minimal example. Why does the second call to foo not compile? It gives the error: from C:/msys64/mingw64/include/c++/10.3.0/bits/nested_exception.h:40, from C:/msys64/mingw64/include/c++/10.3.0/exce...
The error indicates that the function is not invocable with the given arguments. std::invoke_result automatically adds && to argument types, unless they already have &. Your function is not invocable with a bool && argument. Even ignoring invoke_result, this couldn't work because foo receives parameters by const refere...
69,796,302
69,797,364
C++ constructor or recursive member function when using templates
I am writing a matrix library, and when I tested the determinant of the matrix, I found this error I rarely use templates and can’t find the reason for the error template<int n> struct Vec{ double data[n]{0}; Vec() = default; explicit Vec(int value) { ... } }; template<int row, int col> struct Mat{ Vec...
If your compiler supports at least C++17, then the solution is using if constexpr: double Det() const{ static_assert(row == col); if constexpr(row == 1 && col == 1) return data[0][0]; else { double ret = 0; for(int i = 0; i < col; ++i){ ret += data...
69,796,979
69,797,018
what is the meaning of this line of code?
Here is the code. std::shared_ptr<MyType> f() const { return f_; } I understand that std::share_ptr is a smart pointer. MyType is a template parameter. f() is a function, right? const here means this function will be read-only. And then what is the relation between the function definition/body and this smart pointer? ...
The above code snippet can be read as: f is a const member function that returns a std::shared_ptr<MyType> that is it returns a shared_ptr<> to MyType object. As you already mentioned that the function is read-only, is there something else you want to ask, if there is you can edit your question. Also,note that the v...
69,797,538
69,797,641
How do I destruct a dynamically allocated array of dynamic object?
I write a class vector whose member is a dynamically allocated array template <typename T> struct vector{ T* elem;int capacity; /* *capacity is the size of array, not number of elements in the array . *the default capacity is 3. */ vector(int c=3,T e=0){ /* initializing all elements as e */...
Is it necessary to delete all the objects in the destructor of vector? like this Technically yes but what if you want a vector of pointers that does not represent ownership? You could easily end up either double-deleting an object, or trying to delete a stack-based object: obj obj_a; obj* obj_b = new obj; vector<obj...
69,798,309
69,798,587
Applying memoization makes golom sequence slower
I am trying to wrap my head around memoization using c++, and I am trying to do an example with the "golom sequence" int main(int argc, char* argv[]) { std::unordered_map<int, int> hashTable; int value = 7; auto start = std::chrono::high_resolution_clock::now(); std::cout << golomS(4, hashTa...
On top of the other answers, I would like to add that this could really benefit from proper benchmarking. In order to get reliable results you want to run the tests multiple times, and take steps to ensure that memory caches and other system-level shenanigans aren't interfering with the results. Thankfully, there are l...
69,798,894
69,799,319
K-Nearest Neighbors program always reports same class value
I've written a short implementation of the KNN algorithm to determine a sample point {5.2,3.1}'s class according to a brief snippet of the iris dataset, however the class is always reported as 1 (Virginica). It is not immediately obvious to me where the issue arises in my code. Can someone please help me figure out whe...
If you enable warnings, you'll see that test.cpp|33 col 32| warning: array subscript 3 is above array bounds of ‘double [3]’ [-Warray-bounds] || 33 | train_data[i][3] = Distance(train_data[i][0],train_data[i][1],5.2,3.1); Array indexes start at 0. Later on, you also subtract (class - 1) to index the...
69,800,105
69,804,564
c++ combine multiple std::find & std::find reverse starting in the middle of the vector
Im having trouble to find some elements the most speedy way. Given the two vectors I want to start searching elements starting at a previously given position (3), and compare them to another vector. Because i know the "valid" values are 99% around the starting point im trying to build a mechanism, that has 4 steps: Val...
First, your code is a bit confusing because in the condition you compare to vec2[5] but in the message you say Vec1[5]. Second, I'm not really sure why do you use std::distance instead of just de-referencing the iterator: if (down1 != vec1.rend() && vec2[5] != *down1) And finally, your last std::find doesn't work as y...
69,800,678
69,800,865
Complexity of a function with 1 loop
Can anyone tell me what's the complexity of the below function? And how to calculate the complexity? I am suspecting that it's O(log(n)) or O(sqrt(N)). My reasoning was based on taking examples of n=4, n=8, n=16 and I found that the loop will take log(n) but I don't think it'll be enough since sqrt also will give the ...
The sequence j goes through is 1 3 6 10 15 21, aka the triangular numbers, aka n*(n+1)/2. Expanded, this is ( n^2 + n ) / 2. We can ignore the scaling ( / 2) and linear ( + n) factors, which leaves us with n^2. j grows as a n^2 polynomial, so the loop will stop after the inverse of that growth: The time complexity is O...
69,801,126
69,801,186
Doesn't constraining the "auto" in C++ defeat the purpose of it?
In C++20, we are now able to constrain the auto keyword to only be of a specific type. So if I had some code that looked like the following without any constraints: auto something(){ return 1; } int main(){ const auto x = something(); return x; } The variable x here is deduced to be an int. However, with the in...
A constraint on the deduced auto type doesn't mean it needs to be a specific type, it means it needs to be one of a set of types that satisfy the constraint. Note that a constraint and a type are not the same thing, and they're not interchangeable. e.g. a concept like std::integral constrains the deduced type to be an ...
69,801,325
69,801,634
Error: The operation completed successfully (Command Line Game Engine in C++ using Windows API)
As described in the title I want to write a game engine using the command line console. Following closely the project of oneLoneCoder, the code that I have written so far is the following. It creates a command console after it checks that the dimensions given by the user are correct. #include <Windows.h> #include <iost...
Your error reporting in CheckConsoleSize() is wrong. GetLastError() is only meaningful if GetLargestConsoleWindowSize() returns a COORD containing all zeros, which you are not checking for. What you have described sounds like the COORD is simply containing sizes that are smaller than you are expecting, but are not zero...
69,801,387
69,801,834
How to find all the words that contain a given character the most times
Input: char (need to find the most number of occurrences of this char in words which is in array) Output: print word which has the highest number of occurrences of given char or words if there are the same number of occurrences. Need to find word or words which have the most number of occurrences of given char. I wrote...
Here is a solution to your problem that attempts to change your code the least possible: #include <iostream> #include <cstring> #include <list> using namespace std; int main() { char array[]="this is text. Useuuu it for test. Text for test."; char* buf = strtok(array," .,!?;:"); std::list<const char*> word...
69,801,420
69,804,907
QT Chart doesn't fill entire ChartView causing a mirroring effect
I am essentially trying to make a Gantt Chart in Qt. I was going to plot bars on a image. I am able to plot a Bar(green) starting at the beginning of a Chart but I also get a second Bar(green) closer to the end of the Chart. I think the plottable area of the Chart doesn't fill up the entire ChartView so it's doing s...
I made the 2 changes: paint the background in a slot function. emit the slotAreaChanged signal. Here is the code #include<QGridLayout> #include<QLineSeries> #include<QChartView> #include<QChart> #include<QApplication> int main() { int a = 0; QApplication b(a, nullptr); QWidget w; QGridLayout* gridLay...
69,801,719
69,801,777
Valgrind and ostream operator
Why is Valgrind showing error in this code? // const char * constructor String::String(const char* s) { size = 0; while(s[size] != '\0') ++size; capacity = 0; str = new char[size]; for (int i = 0; i < size; ++i) { str[i] = s[i]; if (size > capacity && capacity == 0) { ++capacity; } else...
Why is strlen showing here if I haven't used it anywhere? return std::operator<<(os, other.str); This is the same function that is called when you do: void foo(std::ostream& stream, const char * ptr) { stream << ptr; } How else is the stream supposed to know the length of the passed null-terminated string if not ...
69,802,357
69,802,446
convert enum class too std::tuple
I would like to be able to create a std::tuple based on the enum value passed as a template argument, if possible without using global variables. #include <tuple> enum class Type { eInt, eFloat, eDouble }; template <Type... type> class Test { public: private: std::tuple < ? > m_data; }; int main() { Test<...
Step one, figure out how to convert one constant to a type: template <Type> struct MakeType {}; template <> struct MakeType<Type::eInt> {using type = int;}; template <> struct MakeType<Type::eFloat> {using type = float;}; // ... This lets you do e.g. MakeType<Type::eInt>::type to get an int. Now you can do std::tuple<...
69,802,392
69,802,482
Why is the Dereference operator used to declare pointers?
Why is the * used to declare pointers? It remove indirection, but doesn't remove any when you declare a pointer like int *a = &b, shouldn't it remove the indirection of &b?
Many symbols in C and C++ are overloaded. That is, their meanings depend on the context where they are used. For example, the symbol & can denote the address-of operator and the binary bitwise AND operator. The symbol * used in a declaration denotes a pointer: int b = 10; int *a = &b, but used in expressions, when app...
69,802,578
69,802,937
how to return the number of words in the string "sentence"
I am new to coding and I want to know how to count the number of words, in the "sentence". This function uses a class, what variable should I use to return? Do I have to increment "i" to move to the next character? int Directive::words(const char* sentence) { int i, word = 0; for (i = 0; sentence[i] != '\0'; i...
The sentence must end with a '\0' #include <iostream> using namespace std; int GetWordsCount(const char * Sentencee){ int Count = 0; int LetterCount = 0; while (*Sentencee++){ if (isspace(*Sentencee) || *Sentencee == '.' || *Sentencee == ',' || *Sentencee == '\0'){ if (LetterCount) ...
69,803,296
69,803,674
Overloading istream operator
I have a String class. I want to overload operator >>. Found the following way, but as far as I understand, the zero character is not added at the end (line terminator). How can I write a good operator >>? class String { public: char* str; size_t size; size_t capacity; ~String(); String(const char*); frie...
Let's start with the obvious part: your operator>> needs to actually create a valid String object based on the input you read. Let's assume you're going to read an entire line of input as your string (stopping at a new-line, or some maximum number of characters). For the moment, I'm going to assume that the str member...
69,803,425
69,803,450
C++ should I use forwarding references?
I have functions that take values and pass them to other functions. Nobody down the chain will ever care if it's an rvalue reference and they just want to read the value. Do I need to use forwarding references or can I just use const& like this? template<class Arg> void printOne(std::string& str, std::string_view fmt, ...
No, you don't have to use forwarding references. const references bind to temporary rvalues, so in general when move semantics or perfect forwarding is not required, a plain, garden-variety const reference will work.
69,803,659
69,808,412
What is the proper way to build for macOS-x86_64 using cmake on Apple M1 (arm)?
I'm using a library that I cannot compile for Apple M1, so I have decided to compile it and use it using (Rosetta 2) for x86_64 which I successfully did following this to install brew and clang for x86_64. However when I compile my project and try to link it against this library I get this error: ld: warning: ignoring ...
After checking CMake source code, I found that it is enough to set CMAKE_OSX_ARCHITECTURES to x86_64: set(CMAKE_OSX_ARCHITECTURES "x86_64") This is the cleanest way so far to solve this issue, and work straight forward with CLion too.
69,804,017
69,804,107
Why are function calls in this parameter pack evaluated backwards?
Recently I found this StackOverflow answer about unrolling a loop with templates. The answer states that "the idea is applicable to C++11", and I ended up with this: namespace tmpl { namespace details { template<class T, T... values> class integer_sequence { public: static constexpr size_t size() { ...
The evaluation of function arguments in a function call may be from left to right, right to left, or any other order, which is not required to be predictable. However, when you have a single expression of the form e_1, e_2, ..., e_n where the subexpressions e_1, e_2, ..., e_n are separated by comma operators, then the ...
69,804,068
69,804,116
Convert C++ for loop to python
I am new to python. So, I converted C++ for loop to python. Please check if I have done it correctly. If not, then please inform me how to do it. If I am correct, then please inform me if there's any better and optimized way to do it. C++ Code: void printunorderedPairs(int[] array) { for (int i=0; i<array.length;i+...
In python it's more idiomatic to use for loops, and you can use an array slice for the inner loop. for i, el1 in enumerate(array): for el2 in array[i+1:]: print(el1, el2)
69,804,246
69,804,316
"Red Heart ❤️" unicode character in ncurses
Currently using WSL2, C++20, with the preprocessor directives #define _XOPEN_SOURCE_EXTENDED 1, #include <panel.h>, and flags -lpanelw -lncursesw. Using the code provided below when I try to add the "Red Heart ❤️" character in ncurses, it causes weird bugs on the terminal window, especially when I encase it with a box....
The "character" "❤️" you are using is not actually a single character. It is composed of two Unicode characters, "❤"(U+2764) and a modifying U+FE0F, "VARIATION SELECTOR-16" which gives the red style of the emoji. You can verify the encoded form of a string by typing echo -n ❤️ | hexdump -C in WSL console, which should ...
69,804,387
69,874,543
Bones rotate around parent - OpenGL Animation/Skinning
I am having an issue with my bone skinning where instead of my bones rotating around their local origin, they instead rotate around the their parent. Left - my engine. Right - blender There are two locations in the pipeline that I suspect are at fault, but I cant tell where exactly it is. First, I have this bit of code...
My issue was bad matrix math. I swapped out my matrix::mul function for glm's and got intended results.
69,804,675
69,804,781
'go' was not declare in this scope (C++)
I've tried declaring but still wrong and I've tried several other ways but still error, Can you help me?Sorry I new to Programming 'go' not declare in this scopewhat do i have to do? this code #include <iostream> #include <stdio.h> #include <conio.h> void push (void); void pop (void); void gotoxy(int x, int y); int x,...
First of all, there is no go to keyword in C++. It's goto with no space. Second, your goto sentence isn't right in syntax. goto syntax looks like this: dothisagian: // this is a statement label // code goto dothisagian; It doesn't magically jump into what line you wrote. It jumps to the statement label. Third, yo...
69,805,021
69,806,864
How to remove duplicates from vector by iteratting though?
I'm doing an assignment for my computer engineering class where we have to remove duplicates from a vector. I found solutions elsewhere, but I can't figure out how to iterate through without including the algorithm library #include <vector> using namespace std; vector<int> deleteRepeats(const vector<int>& nums); // D...
So, the requirement is to not use the algorithm library and do it manually. Also no problem, because your teacher gave you already a strong hint by writing: vector<int> deleteRepeats(const vector<int>& nums) { vector<int> res; bool foundRepeat; //my code here return res; } You have an input vector num...
69,805,476
69,817,060
Probably a simple question about a c++ loop
I would like to start off by thanking everybody that attempts to help give me guidance through this issue. I am creating a snake clone to give myself real problems and situations. I have gotten through a lot on my own but unfortunately I have felt like I hit a brick wall and don't want to waste anymore time not underst...
What the posted code is doing is basically the following for (size_t i = 1; i < a.size(); i++) { // Given a container, e.g. {1, 2, 3, 4} a[i] = a[i - 1]; // the result would be {1, 1, 1, 1} } You should traverse the container in the ...
69,805,553
69,805,659
How to constraint a template to be iterable ranges using concepts?
Say I have some template function that returns the median of some iterable object passed into it. Something like: template<typename T> decltype(auto) find_median_sorted(T begin) { // some code here } Now I want to make sure I constrained T to always be iterable. I am trying to learn how to use concepts in C++, so is...
I am trying to learn how to use concepts in C++, so is there some way I can use concept here to make sure T is iterable? You can have standard concept std::ranges::range from <ranges> header here. With that your function will look like: #include <ranges> // std::ranges::range template<std::ranges::range T> decltype...
69,805,789
69,929,939
How to run Yolov5 tensorflow model.pb inside c++ code?
I have trained a model using yolov5 and I got the model.pt I convert it using the export file to TensorFlow compatible model.pb now I want to use this model with c++ instead of python I did a lot of research but I did configure it out how to do this, so where can I find an example that uses model.pb inside c++ code? I...
I did not find a way to run model.pb directly but after a long research I've been able to run the saved_model. There are the important lines of the code // the input node is: const string input_node = "serving_default_input_1:0"; // the output node is: std::vector<string> output_nodes ={"StatefulPartitionedCall:0"}; ...
69,806,067
69,806,168
Is a parameter name neccesary for virtual method definition in C++?
Here is the code: virtual bool myFunction(const Waypoints& /*waypoints*/) { return false; } For my understanding, virtual function is for late / dynamic binding. bool is the return type. const Waypoint& is a constant reference. When it is used to formal parameters, it avoids value copy and forbids being changed by...
The method has one formal parameter of type const Waypoints&. It is unnamed, because it is not used in the method body. This might make sense, because other implementations of the same method might use it (note that the method is virtual). Whether the name of the parameter /*waypoints*/ is commented out, left there or ...
69,806,193
69,806,264
Problems to understand the size of malloc parameter
Can anyone explain how does below code work? Cuz I found myself don't know what |malloc(inputNim+1)andexit(1)` stands for in below code... buffer = (char*) malloc (inputNum+1); if (buffer==NULL) exit (1);
This line tries to allocate inputNum + 1 bytes of memory: buffer = (char*) malloc (inputNum+1); The below line checks if the above allocation succeeded. If malloc fails, it returns nullptr (NULL) and the decision is then to exit the program with return value 1. A common convention is to exit with 0 on success and some...
69,807,116
69,807,184
Can not-copyable class be caught by value in C++?
In the next program, struct B with deleted copy-constructor is thrown and caught by value: struct B { B() = default; B(const B&) = delete; }; int main() { try { throw B{}; } catch( B ) { } } Clang rejects the code with an expected error: error: call to deleted constructor of 'B' ca...
Clang is correct. (Thanks for @NathanOliver's comments.) [except.throw]/3 Throwing an exception copy-initializes ([dcl.init], [class.copy.ctor]) a temporary object, called the exception object. An lvalue denoting the temporary is used to initialize the variable declared in the matching handler ([except.handle]). [exc...
69,807,142
69,807,220
Why Eigen doesn't need template keywords for using template function call of Matrix?
MWE with c++17 and Eigen 3.4.0 #include <Eigen/Dense> using namespace Eigen; int main() { Matrix<float, 2, 2> m; m << 1.0, 2.0, 3.0, 4.0; m.cast<double>(); // m.template cast<double>(); return 0; } After reading Eigen document TopicTemplateKeyword and popular SO answer where-and-why-do-i-have-to-put-the-tem...
m is not a dependent name. You can only have dependent names inside of a template, if they depend on the template parameters of the enclosing templates. Example: template <typename T> void foo() { Matrix<T, 2, 2> m; // Note that `T` has to be involved. m << 1.0, 2.0, 3.0, 4.0; m.template cast<double>(); }
69,807,205
69,808,959
How to cast a QML object as QQuickWindow from c++ code?
I am using QQmlVTKPlugin, which allows me to directly access to VTKRenderWindow and VTKRenderItem with QML. To setup this I need to give to my QQMLApplicationEngine a QQuickWindow and a QQuickItem. If I just do this initialization from the main.cpp everything works correctly but for some reason I need to do that by cal...
Solution : Don't decide to show the window from c++ but only set visible parameter in QML.
69,807,222
69,807,365
Adding comment in raw string literal
I have a raw string literal: const char* s1 = R"foo( Hello World )foo"; I would like to add a comment inside this string literal, e.g.: const char* s1 = R"foo( Hello // Say hello to the whole world because we don't know who will run the program. World )foo"; This comment is actually used as part of the string. Is...
I think the closest thing is to "escape it" with the raw string end and start delimiters: const char* s1 = R"foo( Hello)foo" // Say hello to the whole world because we don't know who will run the program. R"foo( World )foo";
69,807,478
69,807,784
How do you connect to a server and login trough console in C++?
So lets say I want to connect to a website and I want to login to the website without accessing it using a search engine. Can someone tell me how I should do that and what libraries to use using C++? Thanks.
i.e. if you want to log into your gmail, you'll need Gmail's login API from their website. Try and look in the communications sections of this website to find what you need : https://en.cppreference.com/w/cpp/links/libs Once you've downloaded the most suitable library for you, do these steps: Make sure you have a vali...
69,807,502
69,807,728
Type deduction for lamda wrapped in template function
I implemented custom alternative of std::bind version like below: template <typename F, typename ... Ts> constexpr auto curry(F &&f, Ts ... args) { return [&](auto&& ... args2) { ...
First, your curry is dangerous because the lambda inside captures local arguments by reference. As soon as curry return you've got dangling refs. Correct version is: template <typename F, typename ... Ts> constexpr auto curry(F &&f, Ts ... args) { ...
69,807,592
69,807,966
Why does returning a vector initialized with curly braces within normal brackets cause a compilation error?
I just wrote a simple method to return a vector made with two int arguments. However, when I return the initialized int vector within normal brackets, it causes compilation error. std::vector<int> getVec(int x, int y) { return({x, y}); // This causes compile error return {x, y}; // This is fine } The error me...
From return statement: return expression(optional) ; (1) return braced-init-list ; (2) Remember the {..} is not an expression, has no type. There exist some contexts which allow {..} to be deduced in some type. There is a special case for return {..} (2) and uses copy-list-initialization to construct the return v...
69,808,012
69,810,307
How to generate LLVM IR without optimization
I am writing an LLVM PASS to analyze info in registers. It seems that IRBuilder optimized my code automatically, making an expression to be an operand. For example, I write down below code to generate LLVM IR. // %reg = getelementptr inbounds ([128 x i256], [128 x i256]* @mstk, i256 0, i256 0 std::vector<llvm::Value*> ...
I solved this problem by disabling the constant folder of IR builder. See Disable constant folding for LLVM 10 C++ API
69,808,364
69,809,011
C++ object initialization with copy-list-initializer
// Example program #include <iostream> #include <string> class T{ public: int x, y; T(){ std::cout << "T() constr called..." << std::endl; }; T(int x, int y):x(x),y(y){ std::cout << "T(x,y) constr called..." << std::endl; } void inspect(){ std::cout << "T.x: " <<...
Do I understand it correctly, that if I have a constructor defined, it will not perform a zero initialization? Yes. Note that T is not an aggregate because it contains user-provided constructors. As the effect of value initialization: if T is a class type with no default constructor or with a user-provided or delet...
69,808,786
69,808,911
Why are these 2 cout statements giving opposite result?
I can't understand why the statements are giving different results as According to Me a==b is same as b==a #include<iostream> #include<cmath> using namespace std; int main() { cout<<(pow(10,2)==(pow(8,2)+pow(6,2)))<<endl; cout<<((pow(8,2)+pow(6,2))==pow(10,2))<<endl; return 0; } OUTPUT IS- 1 0
This is double comparison issue. You can use something like: cout<<(fabs(pow(10,2) - (pow(8,2)+pow(6,2))) < std::numeric_limits<double>::epsilon() ) <<endl; cout<<(fabs((pow(8,2)+pow(6,2))-pow(10,2)) < std::numeric_limits<double>::epsilon() ) <<endl; Ref: What is the most effective way for float and double com...
69,808,948
69,809,296
Setting up SWV printf on a Nucleo STM32 board (C++)
I am using an STM32G431KB, which compared to other stm32 Nucleo, has the SWO wired. I found this question Setting up SWV printf on a Nucleo STM32 board and followed the first answer. Thereby, I got the SWV running under C. But as soon as I switch to C++, there is no output. I used a new project for C, switched Debug to...
Because your _write function is not _write anymore as its name was mangled by the C++ compiler. So you link with the "old" one which does nothing You need to declare it a extern "C" extern "C" { void ITM_SendChar(char par); int _write(int file, char *ptr, int len) { int DataIdx; for (DataIdx = 0; DataIdx < l...
69,808,960
69,808,961
Get bash $PATH from C++ program
In the Terminal app my $PATH is: /usr/local/opt/python/libexec/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Apple/usr/bin If the user starts my C++ application using Dock, its $PATH is: /usr/bin:/bin:/usr/sbin:/sbin I would like my app to always has the same $PATH as terminal (bash) has. Is there an easy...
If you don’t like your solution of calling bash, here’s a stub to exercise more control over invoking shells and perhaps test if the user default shell isn’t bash all from within a c++ program: setenv("PATH", "/MyCustomPath:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin", 1); To Read bash's path: std::string exec(const c...
69,809,252
69,810,095
Locating a file by path/name in a zip using libarchive
I'm using libarchive in c/c++ to create a zip archive of files and I'm trying to find if there is a good way to find if a file name (or rather file in a path) already exists in a file. Currently, my only way is to cycle through all the headers and compare the filenames to the one I am looking to put into the zip, based...
As libarchive's README suggests, the library is intended for handling streaming archives, rather than randomly-accessed ones. It therefore stands to reason that, in order to locate a file in the archive, you have to "roll the tape", so to speak, until you reach it. You could cache its contents in memory, like @kiner_sh...
69,809,407
69,813,379
How are variables related when using an allocator in C++?
I'm studying this piece of code and what I don't understand is how p, q and r are related. We assign p to q and p to r, then display r, even though we do the increment on q. Then this do ... while loop: do { cout<< "here" << *r << endl; } while (++r != q); How does it work? What are r and q equal to? This is the f...
p is a std::string * const, aka "constant pointer to mutable string". q and r are initialised to copies of p, meaning they are std::string *, aka "mutable pointer to mutable string". p always points to the first element of the allocated array. q and r are modified to point to other elements of the array. The first bloc...
69,810,225
69,810,294
How to convert integer to string, preserving leading zeroes in C++ ? (Using to_string)
When I am trying to convert the given integer to string through to_string function, It simply omits the leading zeroes of the integer. Why ? & how to overcome this? #include<iostream> using namespace std; int main(){ int n; cin >> n; string s = to_string(n); cout << s; }
Integers doesn't have leading zeroes. If you want a specific number of digits for the number, with leading zeros, you need to use I/O manipulators like set::setw and std::setfill: std::cout << std::setw(8) << std::setfill('0') << n << '\n'; That will print (at least) eight digits, with leading zeros if the value of n ...
69,810,813
69,810,950
Variadic templated type as return type, MSVC weirdness
Given the following code: class DummyOK { public: template <typename U, typename... Args> class AThing { public: }; public: template <typename U, typename... Args> AThing<U, Args...> GetAThing(); }; template <typename U, typename... Args> typename DummyOK::template AThing<U, Args...> ...
I would say msvc bug, as workaround, you might use trailing return type: template <typename T> template <typename U, typename... Args> auto DummyKO<T>::GetAThing() -> AThing<U, Args...> { // ... } Demo
69,811,461
72,196,373
not recognized as a supported file format ECW gdal api
I'm trying to use ECW files in my application. I've built GDAL Library whit this command: ./configure --with-ecw:/usr/local/hexagon after completion of build process, when I Entered: gdalinfo --formats | grep ECW I got: ECW -raster- (rw+): ERDAS Compressed Wavelets (SDK 5.5) JP2ECW -raster,vector- (rw+v): ERDAS JPEG2...
I found the answer. This problem occurs if the gdal_bin binary package is installed before creating GDAL. Just make sure gdal_bin is deleted before installing the version you created.
69,811,788
69,811,888
Calculate total gross pay of 10 employees. (C++ - Array in Struct)
The result of this question, it should have a payroll record consists all of these things. But i have a problem in calculating the TOTAL GROSS PAY FOR ALL EMPLOYEES by using arrays in struct (C++) but I am stuck. The total gross pay should be printed at bottom of the payroll record. I feel like something is missing in ...
You have an uninitialized array double gross[10]; So its elements have indeterminate values. As a result this loop for (int i = 0; i < 10; i++) { totalGrossPay = sum + gross[i]; } invokes undefined behavior. Also the variable sum has not changed in the preceding code. So its using in this for loop does not make a...
69,811,934
69,812,485
Would it be possible to call a function in every instance of a class in C++
#include <iostream> #include <string> class Game { public: virtual void Tick() { // Somehow call the tick in every instance of "Object" or any derived class } }; class Object : public Game { public: std::string Name; Object(std::string name) : Name(_name){ } void Tick(){ // Do something every ...
Yes it is possible, but you probably do not want that. First, you are using inheritance between Game and Object. Inheritance is a is a relation. Are your really sure that all Object instances are also Game instances? If you want to call a method on a bunch of instance, then you need a container for those instances and ...
69,812,337
69,812,467
Accessing private member from derived class
This might be a trivial question. Have below code, class message { public: virtual void setMessage(const string& name, const int& age, const string& title) const; virtual void getMessage(const string& name) const; private: void removeMessage(const string& name); }; class test : public message { public: ...
Private members can never be accessed on derived classes. If your intention is to have the derived class access the members of the base class then make those protected or public.
69,812,896
69,812,937
Why is this working in a normal for loop but not a range based for loop?
void set_fee(Patron p, int fee) { for (Patron x : patrons) { if (p.get_name() == x.get_name()) x.set_fee(fee); } for (int i = 0; i < patrons.size(); i++) { if (patrons[i].get_name() == p.get_name()) patrons[i].set_fee(fee); } } So patron is just some class I made and none o...
Your x in the range based for loop is a copy of the element in the vector. You need to have reference there for (Patron& x : patrons) // ^^^^^^^^ { // .... } or else x.set_fee(fee); will be called on the copy.
69,814,275
69,819,146
Why aren't my Microsoft Visual Studio 2017 debugging toolbar commands showing?
I can't see neither my breakpoints or any debugging commands. I have installed Microsoft Visual Studio 2017 and I'm currently editing a c++ source file and i'm having big troubles with debugging. Does anyone know a fix?
Reinstall VS should be the last resort, you can try below suggestions first. Please try to restart VS 2017 and if it doesn’t work, try to reboot your machine. Please try to repair Visual Studio like Alan mentioned, in Visual Studio Installer > find Visual Studio 2017 > More > Repair. Make sure that you are not using so...
69,814,356
69,814,606
std::move on const char* with perfect forwarding
I have an interesting issue on the MSVC v19.28 compiler (later versions fix this problem) where a const char* being passed to a variadic template class fails to resolve correctly. If the const char* is passed to a variadic template function then there are no errors. Here's the code for clarity: #include <type_traits> ...
What is std::move doing to a const char [12] and what are the potential side-effects? The ordinary array-to-pointer implicit conversion, and none. Pointer types don't have move constructors or move assignment operators, so "moves" are copies (of the pointer the array decayed to). Aside: I don't think your template do...
69,814,384
69,814,494
How to read memcpy struct result via a pointer
I want to copy a struct content in memory via char* pc the print it back but here I have an exception (reading violation) struct af { bool a; uint8_t b; uint16_t c; }; int main() { af t; t.a = true; t.b = 3; t.c = 20; char* pc = nullptr; me...
You need to allocate memory before you can copy something into it. Also, pc is already the pointer, you need not take the address of it again. Moreover, the byte representation is very likely to contain non-printable characters. To see the actual effect the following copies from the buffer back to an af and prints its ...
69,814,585
69,826,545
C++ iterator argument in abstract class
I want to have an abstract class with a read and write method like: template<typename Iterator> virtual void read(uint64_t adr, Iterator begin, Iterator end) const = 0; template<typename Iterator> virtual void write(uint64_t adr, Iterator begin, Iterator end) const = 0; is there a way to achieve something like th...
Is one of these ways a clean one? Yes: use static polymorphism instead of virtual functions. When a type is passed via a template, it is not erased and therefore needs no pre-generated virtual tables, so you can cause further template instantiation - that's what your use-case begs for. Solution 1 (recommended) So, if...
69,814,706
69,815,009
__declspec(dllexport) on nested classes
Code: #ifdef BUILD_DLL #define MY_API __declspec(dllexport) #else #define MY_API __declspec(dllimport) #endif class MY_API A { public: void some_method(); class B { public: void other_method(); }; }; Do I have to add my macro (MY_API) to the B class?
Do I have to add my macro (MY_API) to the B class? If that B class is also exported/imported (which, presumably, it is), then: Yes, you do. Try the following code, where we are building the DLL and exporting the classes: #define BUILD_DLL #ifdef BUILD_DLL #define MY_API __declspec(dllexport) #else #define MY_API __d...
69,815,016
69,815,087
I need to print static matrix overloading "<<" operator
I need to print static matrix overloading "<<" operator. Here is my code: class Matrix { public: int matrix[3][3]; friend std::ostream& operator<<(std::ostream& out, const Matrix& e); }; std::ostream& operator<<(std::ostream& out, const Matrix& e) { for (int i = 0; i < 3; i++) { for (int ...
I don't know how to use in main function my overloaded operator to print matrix A First, you need to create an instance of your Matrix class, then you can print it: int main() { Matrix A = {{{1,1,1}, {1,0,0}, {0,0,1}}}; std::cout << A; } Side note: I suggest replacing all out << std::endl; with out << '\n'; ...
69,815,497
69,815,582
int count{0}. Can I initialize a variable using curly braces in C++?
I am in first year in BSc Computer Science. I received a comment from my Professor on my recently submitted assignment . I initialized an int variable to zero : int count{0};. The book assigned to us in the course gives only one way to initialize a variable by using an assignment statement. int count = 0; I don't remem...
Here is how you may initialize the variable count of the type int with zero int count = 0; int count = { 0 }; int count = ( 0 ); int count{ 0 }; int count( 0 ); int count = {}; int count{}; You may not write int count(); because this will be a function declaration. If to use the specifier auto then these declarations...
69,815,597
69,815,862
How to shuffle an array in C++?
I have an array: names[4]={john,david,jack,harry}; and i want to do it randomly shuffle, like: names[4]={jack,david,john,harry}; I tried to use this but it just shuffled the letters of the first word in the array: random_shuffle(names->begin(), names->end()); Here is the full code, it reads names from a .txt file an...
Here's your code with what I felt were the smallest amount of changes. One could argue that I didn't need to change your first for loop as much, but I figure that if you have the prescience to know how many names you're reading, you might as well use the knowledge. #include <algorithm> #include <fstream> #include <iost...
69,815,719
69,818,455
Eigen::VectorXd constructor desires MatrixXd when compiling
Have a straightforward problem with testing out some Eigen functionality. I'm creating a constructor that takes 3 Eigen::Vector by reference. When I construct those 3 in my main and call the Interp object (the class I created) constructor, I get that the constructor desires Eigen::MatrixXd (see the compile error at the...
For the answer, please see @rafix07 in the comments below my initial question: "You are not compiling Interp.cpp try add_executable(test1 main.cpp interp.cpp)" -- rafix07
69,816,039
69,816,135
Constructor with multiple parameters throws 'expression list treated as compound expression in initializer' when array of classes declared
I created the following test program to demonstrate an error I can't seem to resolve. I have searched and read several articles, but none that I've found explain how to resolve this particular problem. I created a class with multiple constructors, one of which has multiple parameters. I can declare instances of the c...
Such an initialization of an array KClass kc5[2]('r',4); is allowed by the C++ 20 Standard. In this case the constructor with one parameter will be called for each element. If the compiler does not support the C++ 20 Standard then it will issue an error. Otherwise in C++ 20 you could else write KClass kc5[2]( { 'r',4 ...
69,816,126
69,816,748
c++ nested while loop runs only once
Please can you advise, why the inner loop runs only once? I'd like to add suffix to each line of input file and then store the result in output file. thanks For example: Input file contains: AA AB AC Suffix file contains: _1 _2 Output file should contain: AA_1 AB_1 AC_1 AA_2 AB_2 AC_2 My result is : AA_1 AB_1 AC_1 ...
IMHO, a better method is to read the files into vectors, then iterate through the vectors: std::ifstream word_base_file("combined_test.txt"); std::ifstream suffix_file("suffixes.txt"); //... std::vector<string> words; std::vector<string> suffixes; std::string text; while (std::getline(word_base_file, text)) { words...
69,816,140
69,816,514
How to keep count of right answer and wrong answers in C++?
Currently working on addition program that will loop until the user enters "n". It will generate two random numbers and display to the user to add them. The user will then input the answer and the program with check if the answer is right or wrong. My code is working fine however I need help for my code below to keep c...
To make life easier, let's use two variables: unsigned int quantity_wrong_answers = 0U; unsigned int quantity_correct_answers = 0U; (This should go before the do statement.) When you detect a correct answer then increment one of these variables: if (answer = (x+y)) { ++quantity_correct_answers; } else { ++quan...
69,816,274
69,817,853
Is there a Python fstring or string formatting equivalent in C++?
I'm working on a project in C++ and I needed to make a string that has elements of an array in it. I know in python you have things like sting formatting and fstrings, but I don't know if C++ has any equivalent. I have no earthly idea as to whether or not that's a thing, so I figured this is the best place to ask. I'm ...
I would just return the type that you use to hold the board. In your case you started with char[3][3]. I would write that using the C++11 array: using Row = std::array<char, 3>; using Board = std::array<Row, 3>; Now you can make all kinds of functions: void move(char player, Board const& b, int row, int col); bool i...
69,816,400
69,816,432
Segmentation fault (core dumped) - Use of uninitialised value of size 8
#include <iostream> #include <string> #include <list> #include <algorithm> using namespace std; class Node{ private: Node *parent; string name; public: Node(){ } Node(string nodeName, Node *nodeParent){ setName(nodeName); ...
Child1 *child1; child1->setName("Child1"); child1->setParent(root); Child2 *child2; child2->setName("Child2"); child2->setParent(node1); With both of these, you're taking an uninitialized pointer (child1 and child2) and trying to dereference it. You probably want something on this order: Child1 *child1 = new Chil...
69,816,670
69,817,473
Cmake Commandline parameters only - Linking external library using
I am new to Cmake and learning. I am using Ubuntu 20 I am not allowed to make changes CMakeLists.txt file. I am trying to use -DIMPORTED_LOCATION=/home/map/third_party for linking external library(libdlt.so) which is present in a user-defined location instead of the default location. But with this command, I am getting...
You can't do this only with command line parameters. The IMPORTED_LOCATION is a target property. This means it only has meaning to CMake when applying it to a CMake target. Dependencies in CMake usually are managed with imported targets, which has the IMPORTED_LOCATION property. It would be done like this: find_path(DL...
69,816,903
69,816,955
How to loop the getline function in C++
Can anyone explain to me why my getline() statement from my code is not looping as I could expect, I want the code inside the while loop to execute forever but then my code only loops the code but skips the getline() function. I'll provide the screenshot...my code is: #include <iostream> #include <string> using namespa...
Try this: while(true) { cout << "Enter your name: "; getline(cin, name); cout << "Enter your age: "; cin >> age; cout << "Age: " << age << "\tName: " << name << "\n\n"; cin.get(); //<-- Add this line } Edit: std::cin.ignore(10000, '\n'); is a safer solution sinc...
69,817,327
69,817,369
What is the difference between these two snippets of c++ code
These are my answers for a codeforces problem and I don't know why the first snippet gives a wrong answer. The second is accepted though. I want to know if there is a problem with the judgment test cases because they seem to give the same output. The problem says the following: Given the boundaries of 2 intervals. Pri...
In the first program you are checking only one condition if(c > b) { cout << -1; } But you need to check also the following condition if ( d < a ) { cout << -1; } For example if(c > b || d < a ) { cout << -1; } else { //... }
69,817,496
69,941,966
DLL reference vs DLL Implicit Linking
I just recently learn about linking an executable to a DLL either through implicit linking or explicit linking; however, it got me confused with project (or DLL) reference. Why use implicit linking when you can add it as a reference in Visual Studio? Implicit linking requires you to export function by marking it __decl...
Why use implicit linking when you can add it as a reference in Visual Studio? Visual studio does implicit linking under the hood, when you reference it, as far as my knowledge goes. I think you're a bit confused about these 2 ways. Let me explain this clearly and separately: Implicit Linking: Here, you have a set of ...
69,817,743
69,817,782
Skipping every M elements when iterating through an array in CUDA
I am new to Cuda programming and I have been trying to figure out how to convert the following code into Cuda code. for (int i = 0; i <= N; i += M) { output[i].x = signal[i].x; output[i].y = signal[i].y; } following a vector_add example, I was able to get this: __global__ void dec(const complex * signal, int ...
Something like this should work: __global__ void dec(const complex * signal, int N, int M, complex * output) { int i = blockIdx.x * blockDim.x + threadIdx.x; i *= M; // add this line if (i <= N) { output[i].x = signal[i].x; output[i].y = signal[i].y; } You should also make sure...
69,817,841
69,832,778
SDL2 PointInRect If Statement not working
I'm making a little game as a small project but I can't get an if statement to do anything. If I make it !statement it works though. I run this if statement to find which cube on the "grid" (An array or cubes I render in a for loop I didn't show) the mouse clicked on. I use C++ and SDL2 on a Mac. This is my code: #incl...
I have fixed this. I had to change my method of drawing since it was drawing over the rect and then showing after I changed its color. There was also an issue with generating the Rects that was probably effect it.
69,818,651
69,819,040
Using standard layout types to communicate with other languages
This draft of the standard contains a note at 11.2.6 regarding standard layout types : [Note 3: Standard-layout classes are useful for communicating with code written in other programming languages. Their layout is specified in [class.mem]. — end note] Following the link to class.mem we find rules regarding the layou...
The standard can’t meaningfully speak about other languages and implementations: even if one could unambiguously define “platform”, all it can do is constrain a C++ implementation, possibly in a fashion that would be impossible to satisfy for whatever arbitrary choices that other software makes. That said, the ABI can...
69,818,739
69,818,774
C++ class instances returned by value not acting like rvalues
I had an interesting typo in some code the other day which led to a lengthy and frustrating debugging session, before I finally noticed the stray character on a much earlier line. The issue was that I had a stray '-' in my code, which the compiler was turning into a call to unary .operator-() on a member variable many...
if 'a' was defined as an int rather than as a class, and the attempted assignment should generate a compile error Class types behave differently with build-in types in this case, the copy assignment operator is allowed to be called on the temporary object here. As you said, you can change the return type of operator-...
69,818,770
69,819,170
Byte allocation different for dynamic vs. static char array of same size?
So, I ran this code in my IDE. Can anyone explain the reason why the same amount of memory isn't allocated to both of these arrays when they should be the same size? char* dynamicCharArr = new char[15]; //allocates 8 bytes cout << sizeof(dynamicCharArr) << endl; char staticCharArr[15]; //allocates 15 bytes cout << siz...
new[] returns a pointer to the memory it allocates. You are printing the size of the pointer itself, not the size of the allocated memory being pointed at. There is no way for sizeof() to query the size of that allocated memory. If you pass in the pointer itself, you get the size of the pointer. If you pass in the de...
69,818,875
69,818,909
Avoiding circular references with forward declarations, but unable to access class members
So, I've got several classes, two of which need to reference each other. I solved circular references with forward declarations in Entity.h, just included Entity.h in my Timeline.h class declaration. Entity has a subclass Human which would hopefully call a method in Timeline which is timeline->addEvent(...). Timeline.h...
Forward declaration only works if you have pointer member, but not actually trying to dereference it. From a look at your code structure, if Human is subclass of Entity, then in the source code of Human.cpp where you dereference the pointer to Timeline, you need to actually include Timeline.h (instead of fw declaration...
69,819,729
69,872,284
Creating a thread safe atomic counter
I have a specific requirement in one of the my projects, that is keeping "count" of certain operations and eventually "reading" + "resetting" these counters periodically (eg. 24 hours). Operation will be: Worker threads -> increment counters (randomly) Timer thread (eg. 24 hours) -> read count -> do something -> reset...
Why are you writing a ThreadSafeCounter class at all? std::atomic<size_t> is a ThreadSafeCounter. That's the whole point of std::atomic. So you should use it instead. No need for another class. Most atomics have operator++/operator-- specializations, so your main loop could easily be rewritten like this: static std...
69,819,844
69,820,202
Which stage in C/C++ compilation process makes it system-dependend?
Am going through this tutorial. Is only the linking stage that makes the compilation of c/c++ code system dependent? Isn't assembly language code generation also system dependent? Isn't system, machine and processor the same thing in this context?
I guess you mean this bit: Linking is very system-dependent, so the easiest way to link object files together is to call clang on all of the different files that you wish to link together. What they mean is that the command-line syntax of linking is very system-dependent. You may have to tell the linker explicitly wh...
69,820,220
69,823,386
Jumping into C++: Ch 5 Problem 7 using vertical bar graph
I am in need of assistance to create an vertical bar graph with required limitations of learning experience. Such as, using only the fundamental basics listed: if statement, boolean, loop, string, arithmetic and comparison operators. Basically giving an idea of how limited my experience is in the language for clarifica...
using only the fundamental basics listed: if statement, boolean, loop, string, arithmetic and comparison operators. Those are enough to write a sort of scanline algorithm: Establish a maximum height for the bars and scale all the (three) values accordingly. This isn't mentioned in your requirements, but it seems bet...
69,820,402
69,820,907
How to Retrieve a Scalar Value from a Compute Function in Apache Arrow
In am looping over the elements of an Arrow Array and trying to apply a compute function to each scalar that will tell me the year, month, day, etc... of each element. The code looks something like this: arrow::NumericArray<arrow::Date32Type> array = {...} for (int64_t i = 0; i < array.length(); i++) { arrow::Result<...
Arrow's compute functions are really meant to be applied on arrays and not scalars, otherwise the overhead renders the operation rather inefficient. The arrow::compute::Year function takes in a Datum. This is a convenience item that could be a Scalar, an Array, ArrayData, RecordBatch, or Table. Not all functions acc...
69,821,036
69,821,116
Which header file or definitions to use for using char8_t data type in C++?
So I want to use char8_t data type in my code. But my compiler shows me that it could not find an identifier like char8_t , which probably means it could not find required header file or definitions for it. So can anyone tell me what header files / definitions should I use to get the char8_t data type? The language is ...
char8_t is a keyword. It's built into the language, so you don't need any headers. If it doesn't work, either your compiler doesn't support it, or you forgot to enable C++20 support (e.g. -std=c++20 in GCC).
69,821,511
69,821,761
sequence-point warning using pack expansion when assigning to tuple
// https://godbolt.org/z/e7ebq6hYE int print(std::string str, int i){ std::cout << i << str << std::endl; return i; } template<typename ... Args> void concat(Args ... args) { int i = 2; std::tuple<int, int, int, int> ret { print("ss", -22), print(args, i++) ... }; // gcc warning std::vector<int> r...
The warning is wrong, see rule (10) here: In list-initialization, every value computation and side effect of a given initializer clause is sequenced before every value computation and side effect associated with any initializer clause that follows it in the brace-enclosed comma-separated list of initalizers. The rule...
69,821,744
69,821,964
Assigning a char value to an int
I am a beginner in C++, and I saw this function below for adding a word to a trie, and got confused on the line I commented with a question mark. Is the author assigning a char value to an int here? What int value would be assigned? struct TrieNode { struct TrieNode *children[ALPHABET_SIZE]; // isEndOfWord is ...
char is just a 1-byte number. The computer encodes those numbers to a character using whatever character encoding your computer uses (mostly ASCII). In ASCII, a has a value of 97, b has a value of 98, ... , z has a value of 122 So: If key[i] is "a", value = 97 - 97 = 0 If key[i] is "b", value = 98 - 97 = 1 If key[i] is...
69,821,782
69,822,081
reinterpret_cast and explicit alignment requirement
Given this (bold part) about reinterpret_cast, I was expecting that the piece of code below would generate different addresses when casting X* to Y* since the latter is more striclty aligned than the former. What am I missing here? Any object pointer type T1* can be converted to another object pointer type cv T2*. Thi...
Quoting from [expr.reinterpret.cast]/7: An object pointer can be explicitly converted to an object pointer of a different type. When a prvalue v of object pointer type is converted to the object pointer type “pointer to cv T”, the result is static_­cast<cv T*>(static_­cast<cv void*>(v)). Then, from [expr.static.cast]...
69,821,876
70,493,457
How to decode AAC network audio stream using ffmpeg
I implemented a network video player (like VLC) using ffmpeg. But it can not decode AAC audio stream received from a IP camera. It can decode other audio sterams like G711, G726 etc. I set the codec ID as AV_CODEC_ID_AAC and I set channels and sample rate of AvCodecContext. But avcodec_decode_audio4 fails with an error...
Did you check data for INVALID_DATA? You can check it according to RFC RFC3640 (3.2 RTP Payload Structure) AAC Payload can be seperated like below AU-Header | Size Info | ADTS | Data Example payload 00 10 0c 00 ff f1 60 40 30 01 7c 01 30 35 ac According to configs that u shared AU-size (SizeLength=13) AU-Index / AU-In...
69,822,870
69,823,063
Must `throw nullptr` be caught as a pointer, regardless of pointer type?
The following program throws nullptr and then catches the exception as int*: #include <iostream> int main() { try { throw nullptr; } catch(int*) { std::cout << "caught int*"; } catch(...) { std::cout << "caught other"; } } In Clang and GCC the program successfully print...
Looks like a bug in Visual Studio, according to the standard [except.handle]: A handler is a match for an exception object of type E if [...] the handler is of type cv T or const T& where T is a pointer or pointer-to->member type and E is std​::​nullptr_t.
69,823,031
69,825,104
Converting LPCSTR to LPCWSTR in C++, ATL not available
Before I start, Please do understand that this question is not a duplicate. There are questions out there with the same header : Convert LPCSTR to LPCWSTR However, I did some research before asking this question and came across ATL or Active Template Library. However the compiler I use, doesn't come with ATL, which doe...
Since the title is usually constant, you can simply call SetConsoleTitle(L"My Title"); //or const wchar_t* title = L"My Title"; SetConsoleTitle(title); In general, use MultiByteToWideChar to convert ANSI or UTF8, to UTF16 #include <iostream> #include <string> #include <windows.h> std::wstring u16(const char* in, int ...