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,396,248
66,396,281
Why does the C++ 'int arr[n];' such that n is variable works in one environment and doesn't work in another?
When I type: int n; cin >> n; int a[n]; It works on VS code but doesn't work on Visual Studio. I expected it not to work at all because of memory-related stuff. So, any explanation why it does work on VS code ?
a[n] is variable-length array (VLA) which is a C99 feature. It is not a C++ feature. Some C++ compilers, never the less, accept the syntax as a compiler extension.
66,396,651
66,400,371
What is the most efficient way of converting a std::vector<std::tuple<>> to a torch::Tensor?
I have a vector of tuples that I need to convert into a torch::Tensor. What I have come up with so far, is the vanilla approach which is as follows : std::vector<torch::Tensor> anchors; std::vector<std::tuple<float, float, float, float>> anchors_raw; //... for (auto& rows: anchors_raw) { auto& [cx, cy, s_k...
I am not aware of any libtorch feature to do that easily. I would have suggested to use torch::from_blob, hoping for the data to be stored contiguously, but I have found this thread that says otherwise. So if possible, my suggestion would be to replace your tuple<float, float...>by std::array<float, 4> (for which memor...
66,396,820
66,396,938
Print whether a certain number is Palindromic or not in C++
I have this code in my my C++ dev console that is supposed to check if a given input number is palindromic(when reversed, its still the same number). The problem is that i don't know how to iterate through the calculations to check whether its true and print the required statements #include <iostream> using namespace s...
You are destroying the original input x in while loop. Simply copy it in a temporary variable, and it should fix your code. like bool isPalindrome(int x) { int rev=0; int tmp = x; while(tmp>0){ rev = rev*10 + tmp%10; tmp = tmp/10; } return (x== rev); }
66,396,903
66,397,283
Variable Argument Functions, with classes as arguments. C++
How to create a function that can pass a variable number of arguments that are pointers to objects of the same class? It is desirable that it would be impossible to pass other data types. (Its quantity will be passed too) There are no problems when working with standard types of variables, but no examples of such use c...
class C { public: void DoSomething(int n, C* ptrs[]) { // do something with n number of pointers from ptrs array... } }; C c1, c2, c3, c4; C* arr[] = {&c2, &c3, &c4}; c1.DoSomething(3, arr); Alternatively: class C { public: template<size_t n> void DoSomething(C* (&ptrs)[n]) { // do some...
66,396,905
66,396,949
Const dynamic_pointer_cast when is needed
It's not clear for me when is needed to use dynamic_pointer_cast or dynamic_cast with const. Please someone explain it to me. I made a const object of type A but as far as I've seen there's no need to use dynamic_pointer_cast with const at downcast, so when would be needed a const downcast ? #include <iostream> #includ...
Constness of a pointer is unrelated to constness of what it points to. If a was a pointer to const A: std::shared_ptr<const A> a = std::make_shared<const B>(); // or const std::shared_ptr<const A> a = std::make_shared<const B>(); , then dynamic_pointer_cast<B> wouldn't work, but dynamic_pointer_cast<const B> wou...
66,397,249
66,398,593
Why is the move constructor called from the default one when it is passed to async?
i have a class like this: class move_only { public: int valut; move_only() {} move_only(move_only&&); void operator()(); }; move_only::move_only(move_only&&) { cout << "here"; } void move_only::operator()() { } i wonder why when you call: auto flow = std::async(move_only()); first called move_on...
The backtrace of gcc 10.2 at the moment the move constructor is invoked: 1 move_only::move_only 2 std::_Head_base<0ul, move_only, false>::_Head_base<move_only> 3 std::_Tuple_impl<0ul, move_only>::_Tuple_impl<move_only> 4 std::tuple<move_only>::tuple<move_only, true, true> 5 std::thread::__make_invoker<move_only> 6 std...
66,397,440
66,397,579
What is the memory/runtime efficiency of std::vector, and what is its memory allocation strategy?
I am reading "C++ Primer", and in the chapter about containers, the book suggests to always use std::vector whenever possible, eg when there is no demand to insert or delete in the middle or front. I tested a bit with std::vector and noticed that every time it needs to reallocate, it always reallocates a piece of memor...
why would it execute in such a way Because even though this wastes some memory, it makes insertions faster, by reducing the number of reallocations. It keeps push_back complexity at amortized O(1), while increasing the size by 1 and reallocating each time would make it O(n). reallocates a piece of memory that is thr...
66,397,688
66,467,528
Changing if a HWND Is topmost in run time
So I have a question. how can I make it so my HWND window is topmost on a toggle? Would It be something like HWND Flags = HWND_TOPMOST; SetWindowPos(LOADER_HWND, Flags, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); // if (toggle) Flags = HWND_NOTOPMOST; else Flags = HWND_TOPMOST; I've tried something like...
I found a solution. I was not updating the window.
66,397,929
66,397,986
C++: Segmentation fault when inserting pointer into a struct's double pointer array
I have a TreeNode class with the following definition, containing a double pointer that points to an array of TreeNode pointers: #include <iostream> #include <fstream> #include <string> using namespace std; typedef struct TreeNode { int key; int val; bool flag; int num_children; TreeNode **children; } ...
node1->children = &node2; So, node1->children contains the address of node2. node1->children[2] = node4; This doesn't make sense. Since node1->children contains a pointer to node2 and not an array, node1->children[2] doesn't exist -- no space has been allocated for it, so its value can't be set. You want an array of ...
66,398,707
66,399,522
c++20 Sorting Vector of structs with structs member variable and std::ranges
I have a simple struct struct MyStruct { int x; } I have a vector of MyStructs. vector<MyStruct> myStructs; int n = 10; for(auto i = 0; i < n; i++) myStructs.push_back(MyStruct{.x = n - i}); How will I sort myStructs according to member variable .x using std::ranges?
using projection: std::ranges::sort(myStructs, {}, &MyStruct::x); //< sort by x
66,398,736
66,400,738
How to return read-only C++ std::vector by value for consumption by C?
What are the best practices for returning read-only std::vector<uint8_t> by value from C++ API for consumption by C? // cpplib.hpp struct A { std::vector<uint8_t> getHash() const; }; // c-api.h typedef struct A A_t; ??? A_get_hash(); // c-api.cpp extern "C" { ??? A_get_hash() { // return std::vector<uint8_t...
Where does your A instance live? What you can do is to return the struct you defined by value, pointing to the data held by a vector - no dynamic allocation needed. You need however to keep that C++ vector somewhere and there is no way around that - vector is by definition dynamically allocated. In your example code it...
66,398,954
66,399,078
How to overwrite all the free disk space with 0x00?
how to overwrite all free disk space with zeros, like the cipher command in Windows; for example: cipher /wc:\ This will overwrite the free disk space in three passes. How can I do this in C or C++? (I want to this in one pass and as fast as possible.)
You can create a set a files and write random bytes to them until available disk space is filled. These files should be removed before exiting the program. The files must be created on the device you wish to clean. Multiple files may be required on some file systems, due to file size limitations. It is important to use...
66,399,438
66,399,513
Can't use lambda inside `std::generate`. Where did I mess up?
I got the following code which should fill a std::vector<int> with the binomial coefficients for a given n (see below). I don't think the binomial function is wrong, since it does what it should do. The error message I get is the following: In file included from /usr/include/c++/9/algorithm:62, from <f...
generate requires a callable that takes no arguments: std::generate(v.begin(), v.end(), [&]{ return binomial(n, cnt++); });
66,399,579
66,492,659
Can't make TensorFlow 2.4.1 (CPP) compile on Windows
I am trying to build TensorFlow 2.4.1 C++ API on Windows 10 and I am having issues. What I've done so far: Download TensorFlow Source from the official repo https://github.com/tensorflow/tensorflow and switched to the official v2.4.1 tag Download and install Python 3.6.8 x64 Created a virtual env with python 3.6.8 Cre...
As I was running out of ideas I decided to go take a look at the Bazel build scripts for CUDA In <REPO>\tensorflow\third_party\gpus\cuda_configure.bzl I saw that cuDNN path is read from env variable CUDNN_INSTALL_PATH and if not present it will default to /usr/local/include? Anyway, tried set CUDNN_INSTALL_PATH=D:/code...
66,399,675
66,400,592
MPI_Reduce C/C++ - Signal: Segmentation Fault (11)
I don't understand well how the MPI_Reduce works with array. I need to do an element wise sum. To test the MPI_Reduce function I wrote this simple code and it works: double a[4] = {0,1,2,(double)process_id}; double b[4]; MPI_Reduce(&a, &b, 4, MPI_DOUBLE, MPI_SUM, p-1, MPI_COMM_WORLD); if(id == p-1) { for(int i = 0;...
I don't understand well how the MPI_Reduce works with array. I need to do an element wise sum. From source about MPI_Reduce one can read: Reduces values on all processes to a single value int MPI_Reduce(const void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype, MPI_Op op, int root, MPI_Comm comm) In your...
66,400,063
66,400,258
How to compare iterator value with an integer?
The function removeAll(vector<int>& v, const int& x) intends to remove all elements that equals to int x except the first one. For example originally v = [2,2,3,5,5,6,2,8,6] after removeAll(v, 2) the output should be [2,3,5,5,6,8,6] But my code seems fail to compare if (*it == x), so does anyone know the reason? I d...
There are several problems: count must be declared outside of the loop, otherwise it's reset to 0 on every iteration. it must be incremented only when you chose to not erase an element. When you do erase an element, the return value of erase should be assigned to it. (Failing to do so would formally cause UB, but in...
66,400,244
66,427,262
vkGetPhysicalDeviceSurfaceCapabilitiesKHR not returning
I'm trying to implement Vulkan to my game but I'm stuck at vkGetPhysicalDeviceSurfaceCapabilitiesKHR because the function not returning it just crash inside function. I'm sure both VkPhysicalDevice and VkSurfaceKHR are initialized as they are used in other that works as expected. I'm running Linux on X11 and I've an In...
Ok my problem is solved, it was related to my setup. I'm running a linux laptop and the support for hybrid graphics is poor. But my program is working !!
66,400,413
66,400,644
Does updating VkGraphicsPipelineCreateInfo after the pipeline creation affect the currently rendering scene?
I'm currently working on a graphics engine and I wish to update the pipeline state at runtime. Creating a new pipeline for each single resource update (ie: enabling depth clamp, enabling color blend) at runtime and then re-binding everything to the command buffer takes up a considerable amount of performance. So what I...
No, this does not work that way. The structures that specify pipeline creation state information (like blending, multi sampling, vertex input state, etc.) are consumed at pipeline creation time and baked into the pipeline. So changing these after the pipeline has been created, won't update the pipeline at all. This mea...
66,400,687
66,400,834
Operator Overloading behaves differently for classes and primtives
The following code when compiled and run using g++ outputs 22. #include <iostream> int main(){ int a = 5; int c = ++a + ++a + ++a; std::cout << c << std::endl; return 0; } Floats also evaluate to the same value. Whereas the following integer wrapper class outputs 24 #include <iostream> class Int{ pub...
Both int c = ++a + ++a + ++a; and Int c = ++a + ++a + ++a; result in undefined behavior. You should avoid coding like that. See https://en.cppreference.com/w/cpp/language/operator_incdec#Example, and see the Undefined behaviour section of cppreference.com's Order of evaluation page: Undefined behavior If a side effec...
66,400,841
66,400,914
Index error while moving on a matrix object C++
I am trying to fit a word to a matrix by iteration but when I enter a row = 0, the function tries to check arbit_mat[r][c - 1] == '-' in the while loop and gives error. How can I fix this issue? if (rotation == "CW") { switch (direction[0]) { case 'l': // left situation ...
You want while ((c - 1 >= 0) && (arbit_mat[r][c - 1] == '-')) { & is the bitwise and operator && is the logical and operator
66,400,967
66,401,251
How to Display an Output and End the Program at the Same Time if the User Enters 0 or Less
Hi so I want to end my program if t1, t2 or t3 <= 0. But I want to display this error message before it ends : cout << "Error!\n\n" << "Runner's time must be greater than 0.\n" << "Rerun the program and try again.\n"; I have tried doing it with while but it just makes my program output window go on forever if 0 isn't e...
cout << "Enter the name of the first runner : "; cin >> runner1 cout << "Enter the time taken for the first runner to finish the race in seconds : "; cin >> t1; if(t1 <= 0){ cout << "Error!\n\n" << "Runner's time must be greater than 0.\n" << "Rerun the program and try again.\n"; exit(1); } cout << "\n"; You've sai...
66,401,127
66,401,188
Constraing template parameter by another template with any specialization type
I started playing around with templates and came up with idea of writting simple header-only unit library. I came accross a problem with defining a constaint on parameter type. The type itself is also a template. My requirement is to constraing the type to type 'Meter' of any template specialization type 'Prefix'. I ho...
You can do it like this: template<class OtherPrefixType> Meter operator+(const Meter<OtherPrefixType>& meter) { ... }
66,401,190
66,401,434
What is the proper format of writing raw strings with '$' in C++?
I'm learning about raw strings in C++ from a cplusplus.com tutorial on constants. Based on the definition on that site, a raw string should start with R"sequence( and end with )sequence where sequence can be any sequence of characters. One of the examples of the website is the following: R"&%$(string with \backslash)&%...
From C++ reference: delimiter: A character sequence made of any source character but parentheses, backslash and spaces (can be empty, and at most 16 characters long) Note the "any source character" part here. Let us look at what the standard says: From [gram.lex]: raw-string:   "d-char-sequenceopt(r-char-sequenceopt...
66,401,346
66,401,749
Proper Global Variable definition/declaration
This is probably a pretty straight forward question but for some reason I haven't been able to find an answer on the great interwebs so far. When using global variables, I know global variables are bad and should for the most part be avoided, but on those rare occasions where a global variable gets the job done best, s...
You want to initialize variables at the point they are declared whenever possible, regardless of their scope. For global variables, if you don't initialize them when they are declared, you need to initialize them after your program starts running, which leaves open the possibility that the global will be used before th...
66,401,368
66,401,801
Accessing elements of the std::string array
How to access the below array elements and print the elements of type uint8_t in hex format in C++? std::string arr[] = {"0x01","0x02","0x03","0x04","0x05","0x06"} How to print each element using c_str()?
If your goal is to parse strings, here is how you do it: #include <cstdint> #include <cstdio> #include <string> int main() { std::string arr[] = {"0x01", "0x02", "0x03", "0x04", "0x05", "0x06"}; std::uint8_t arr2[6]; for (std::size_t i = 0; i < 6; ++i) arr2[i] = std::stoi(arr[i], nullptr, 16); for (auto e :...
66,401,821
66,401,938
Is there a way to modify Google C/C++ formatter in Visual Studio Code?
I like Google formatting option for C/C++ extension in VCS. However, there is one aspect I would like to change. I prefer associating a pointer or a reference to the type declaration: int& a = b; int* c = d; However, Google formatter changes it to: int &a = b; int *c = d; I am wondering if there is a way to override ...
From the clang-format-reference: DerivePointerAlignment (bool) If true, analyze the formatted file for the most common alignment of & and *. Pointer and reference alignment styles are going to be updated according to the preferences found in the file. PointerAlignment is then used only as fallback. Consider an exampl...
66,401,837
66,402,775
Compilation flags to build runtime on linux machines
What compiler flags are used to build standard c/c++ libraries like glibc and libstdc++? Are they same across the distributions like debian, fedora, archlinux etc? On debian machines there is dpkg-buildflags but I'm not sure if they are overridden for critical runtime libraries.
The one common factor is -O2, with -O2 -g (enabling gdb debugging symbols) being the most common. -O2 is definitely the expected optimization level maintainers assume packages should be compiled at. If you look at debian/rules in Debian source packages (or -debian.tar.* tarballs), you'll usually find HOST_CFLAGS and H...
66,402,060
69,610,563
How do I create a templated template specialization of a function in c++/c++20?
I have written my own fixed point numeric class which is intended to be used like float or double: template<typename T, unsigned Precision> struct fixed {...} T must be int8_t, int16_t, int32_t or int64_t and it will use Precision bits for the fractional part. There is no exponent part. I have implemented the necessar...
This is possible using c++20. Consider the following template function my_sqrt. template<class T> T my_sqrt(T x); Full specialization is straightforward (e.g. for double). template<> double my_sqrt(double x) { return sqrt(x); } Partial specialization can be implemented using a requires clause that constrains the type...
66,402,251
66,402,772
Conditionally defining method for container class
Is it possible (and is it a good idea) to conditionally define methods for some container class (template<typename ThingType> class Container) depending on the type of its elements? I first thought it was possible after reading about std::enable_if, but now I am not certain I understand. Below is my attempt (click here...
I don't intend for this method to be overloaded. I want it to be available to the end user whenever it makes sense for it to be available. There will only be one of these p methods, and it should take only one (relatively simple) signature. This simplifies the exercise quite a bit. The solution is... to do nothing sp...
66,402,373
66,402,439
Best way to have an 'complex' operation function with two C++ vectors as arguments
To make things simple, may I ask whats the best way to write the following code in C++ with the following Python code import numpy as np X = np.array([1,2,3,...]) Y = np.array([10,11,12,...]) def funct(X,Y): return 0.5 * X + 0.5 * 3 * Y Alternatively, to explain without Python, is there a way to: #include <vector>...
Perhaps valarray is what you need: #include <iostream> #include <valarray> int main() { std::valarray<double> Z {}; std::valarray<double> X {1,2,3,4}; std::valarray<double> Y {5,6,7,8}; Z = 0.5 * X + 0.5 * 3 * Y; for(auto v : Z) std::cout << v << '\n'; } Output 8 10 12 14 Note from std::valarray...
66,402,652
66,402,803
C++ - friend operator cannot access private data members
I am trying to overload an operator for a class: #include <iostream> using namespace std; class Complex{ float re, im; public: Complex(float x = 0, float y = 0) : re(x), im(y) { } friend Complex operator*(float k, Complex c); }; Complex operator*(float k, Complex c) { Complex prod; prod.re = k * ...
In the first operator* case, re and im are completely unknown to the compiler as the function operator* in this case is in a global space (scope). In the second example of operator* you're giving re and im meaning by using an object of a class Complex c - in this case the definition of a class Complex is known to the c...
66,402,736
66,402,918
Which types of memory_order should be used for non-blocking behaviour with an atomic_flag?
I'd like, instead of having my threads wait, doing nothing, for other threads to finish using data, to do something else in the meantime (like checking for input, or re-rendering the previous frame in the queue, and then returning to check to see if the other thread is done with its task). I think this code that I've w...
The memory ordering you're using here is correct. The acquire memory order when you test and set your flag (to take your hand-written lock) has the effect, informally speaking, of preventing any memory accesses of the following code from becoming visible before the flag is tested. That's what you want, because you wan...
66,402,881
66,421,029
Safe coding practices
I'm starting a new C/C++ embedded app and am trying to educate myself about safe coding practices like MISRA, AUTOSAR and my current favorite probably because it's the shortest, NASA's so-called Power of 10 (https://en.wikipedia.org/wiki/The_Power_of_10:_Rules_for_Developing_Safety-Critical_Code). I can see the logic ...
Does that mean for example that all variables need to be static? No, they can be local scope (automatic storage) too. If declared at file scope, they should generally be static (encouraged by MISRA-C and others). Just to make sure I understand correctly, are temporary variables defined inside methods declared on the...
66,403,662
66,403,692
missing default value on parmeter
I keep getting this error. error: missing default argument on parmeter 'm' Can please someone explain why do I get this? And how to fix it? int func(vector<int>& arr, int l, int r,int res = 0,unordered_map<int,int>& m) { if (l > r) { m[res] ++;; return; } // Subset includin...
You can't put a parameter without a default value after a parameter with a default value. So, you can fix it like this: int func(vector<int>& arr, int l, int r, unordered_map<int,int>& m, int res = 0)
66,403,795
66,404,154
Strange output printing char array
human header class human { char name[]; public: void setName(char nameValue[]); char* getName(); } human cpp void human::setName(char nameValue[]) { char name[] = "walter"; } char* human::getName() { return name; } main cpp int main() { human myHuman; char name[]...
First and foremost you are assigning nameValue to a variable local to the function setName, which means that the class variable name is still unitialized when you return it in getName, hence the strange output. The char name[]; declaration is also incorrect, C++ does not allow for variable length arrays or arrays with ...
66,403,968
66,404,752
Unable to Satisfy Constraint for ranges::count()
I'm exploring the ranges functions. struct User { std::string name; int age; std::string gender; template<class Os> friend Os& operator<<(Os& os, User const& u) { return os << "\n" << std::right << std::setw(10) << u.name << " - " << u.age << ", " << u.gender; } }; ...
In std::ranges::count_if you're providing a custom comparator. However, in std::ranges::count you're trying to use the default comparison, which doesn't. You need to provide that, and assuming you want member-wise comparison of the struct members, you can simply add: auto operator<=>(User const &) const = default; to ...
66,404,123
66,404,787
How to use boost unit prefixes in a constexpr
I am trying to defined a constexpr in terms of kilometers instead of meters using boost units. Everything I have read indicates that both lines below should work, but only the top line compiles for me in clang 10. Here's a godbolt link for the lazy: https://godbolt.org/z/38je3z #include <boost/units/systems/si.hpp> #in...
This is a workaround: static constexpr boost::units::quantity<boost::units::si::length> earth_radius_2{6371.0087714 * boost::units::si::kilo * boost::units::si::meters}; Why is this different than the code in the question? According to the c++17 standard, initialization with a = or direct initialization (as the soluti...
66,404,133
66,404,305
error: 'sort' is not a member of 'std::ranges'; did you mean 'std::sort'?
I ran the following code vector<int> randomIntegers = generateIntegers(10); // Generates 10 integers std::ranges::sort(randomIntegers); When I compile with g++ -std=c++20 file.cpp , I get error: 'sort' is not a member of 'std::ranges'; did you mean 'std::sort'? gcc --version: gcc 10.2.0 g++ --version: g++ 10.2.0 W...
To get access to std::ranges::sort you need to #include <algorithm>: #include <algorithm> #include <vector> int main() { std::vector<int> randomIntegers{9,8,7,6,5,4,3,2,1,0}; // some integers std::ranges::sort(randomIntegers); } Demo
66,404,418
66,404,618
MSVC cannot return an object that can be copied but cannot be moved
While fiddling around with copy elision I came across this strange behavior: class Obj { public: Obj() = default; Obj(Obj&&) = delete; Obj(const Obj&) { std::cout << "Copy" << std::endl; } }; Obj f1() { Obj o; return o; // error C2280: move constructor is deleted } Obj f2() { Obj o; return Obj(o); // ...
The lack of error on f1() is a bug in both clang and gcc. It is fixed in clang's tip-of-trunk. f1() is not eligible for mandatory copy elision. Deleted functions participate in overload resolution. If they are chosen as the best overload, the program is ill-formed. In f1(), the deleted move constructor is chosen by ...
66,404,695
66,405,029
C++ Constructor is ambiguous with std::map of the same key/value types
Here's a class definition as an example. #include <string> #include <map> template <class T> class Collection { private: std::map<std::string, T> data; public: Collection() {} Collection(std::map<std::string, T> d) { data = d; } }; This works fine when initializing Collections with ints, chars, and ev...
This is a fun one. A map can be constructed from two iterators: template<class InputIterator> map(InputIterator first, InputIterator last, const Compare& comp = Compare(), const Allocator& = Allocator()); Notably, this constructor is not required to check that InputIterator is an iterator at all, let alone tha...
66,404,721
66,404,840
error: no match for call to '(const std::ranges::__sort_fn)
I was practicing vectors and ranges in c++ 20 was stuck at following state. #include <iostream> #include <vector> #include <random> #include <ranges> #include <algorithm> namespace ranges = std::ranges; struct Model { double next_event_time; }; std::vector<Model> generate_examples(int number) { // A uniform ...
Your function should be as this: Model get_next_model( std::vector<Model> models) { ranges::sort(models, ranges::less{}, [](const Model &x) { return x.next_event_time; }); return models[0]; } There were two problems: You cannot sort const object (so remove const&) The signature of sort requires way of sort...
66,404,751
66,404,884
"Variable shadowed" warning in lambda (when not captured)
Let's consider this code: int main() { int a = 1; auto f1 = [a]() { int a = 10; return a; }; auto f2 = []() { int a = 100; return a; }; return a + f1() + f2(); } When using flag -Wshadow with gcc (tested on 10.2), we get these warnings: <source>:26:13: warning...
You are correct, lambda a doesn't shadow main::a because main::a isn't captured in the lambda, thus is not on scope there. However I think about what the purpose of the shadow warning is: to avoid programmer confusion. If a long body of code if the programmer sees the outer declaration, but doesn't see the inner declar...
66,404,768
66,413,313
Unable to start program 'MYPATH.exe'. The system cannot find the file specified. When i try to run a new 'hello world' console application
i am new and i was trying to learn c++, so i open my visual studio 2019, then create a new console application and click the run button. This is the autogenerated code: #include <iostream> int main() { std::cout << "Hello World!\n"; } any idea?
To fix the error, i go to Tools > Get Tool And Features... Then i installed Windows 10 SDK (10.0.19041.0) and now my program works! Someone know the reason why the SDK is not installed by default?
66,405,200
66,405,218
How does this recursive function "end" rather than loop indefinitely (or throw an error)?
I came across this subset_sum coding problem/solution and am trying to understand in depth how it works. To quickly summarize the problem: given an array of length n, find the largest number in the array and then find if there is any combination of numbers inside that array that, when summed, equal the largest number. ...
The recursion ends when i reaches length: void checkSubsets(int *arr, int i, int length, int *subset, int j, int max) { if (i == length) { // stuff return; // ends here. } // else recurse: checkSubsets(arr,i+1,length,subset,j, max); // i+1 subset[j] = arr[i]; checkSubsets(arr,i+1,length,subset...
66,405,409
66,405,589
C++ getline errors using char arrays
I keep getting an error saying " error: no matching function for call to 'getline(std::ifstream&, char [100])'| " on getline(Input, sentence). I might be missing something, Im not sure. What I'm trying to do is read an entire line from the input and insert it into char sentence[100] using getline. I have to use getl...
The problem is you are attempting to use std::getline instead of std::basic_istream::getline. (e.g. you are using the wrong getline()) The getline() you are attempting to use expects a std::string for destination storage, not a plain old character array. The second form above happily takes a character array and its siz...
66,405,916
66,406,131
How to find the value in a node using a double pointer when that node is passed through a function and accepted as a double pointer?
guys I am desperately trying to learn how to manipulate linked lists and I am having a hard time. I can't understand most of the tutorials online and they all don't seem intuitive to me. I have successfully tried to append a node at the beginning of a linked list using a double pointer, but the nature of this double po...
head contains the address of the first node. That is, the address of the beginning of the memory occupied by that node. That is also the address of the value member of that node, because that node and its value member start at the same place. head is a pointer, which is a variable. &head is the address of that pointe...
66,406,171
66,406,236
Hide callback prototype from a 3rd party library in C++
I'm using glfw3 library, which has this function glfwSetCursorPosCallback, to use that function you need to pass a GLFWwindow pointer and a pointer to fuction with this prototype void callback(GLFWwindow* window, double, double). I want to create a class WindowManager that encapsulate all operations with that library, ...
GLFW allows you to set a window user pointer, which can be any void*. You can then retrieve the void*, and cast it to whatever type you wish. I think the functions as glfwSetWindowUserPointer() and glfwGetWindowUserPointer(). What you can do is have the WindowManager register all the callbacks, and set the user pointer...
66,406,179
66,406,216
Implementing common char count in C++ for 2 strings but receiving vastly different char count for the same for loop on 2 strings
I'm trying to get an output something like for the first for loop where I cout << char << charcount but for my second loop, I'm getting very large counts and my string became "testfr" from my original input string "tester". I'm not sure whats went wrong. This is the code I have. int commonCharacterCount(string s1, stri...
This line: map1[s1[i]]++; s1[i] will typically be an ascii value between a and z. The ordinal values for chars in the a-z range are between 97 and 122. 65 - 90 for capitol letters. And other printable characters and digits will have ordinal values greater than 31. But the only valid indices in your array are between...
66,406,245
66,406,471
Why my C++ program is 100x slower than a Python Version?
I have wanted to make a comparison of some programming languages, and I took the C, the C++ and the Python. Here is my C++ code of a test loop : #include <iostream> int main(){ for(int i=0;i<10000;i++){ std::cout<<i; } } After compiling it with Code::blocks's GCC(I don't think it'll make a big difference, and it's...
On Windows, the default behavior is to not buffer stdout if the output is an interactive console. While other platforms do something similar, this coupled with the default Windows console being surprisingly slow, means if you output a lot of text to it, your program will be slow. Python, on the other hand, defaults to...
66,406,291
66,406,302
Static Member Variable, Qualified Name is Not Allowed
I've searched other answer's on SO and feel like I'm following the format correctly, so not sure what Im doing wrong and am at my wits end with this one.... class DBwrapper { private: static std::string DBfile; //static char DBfile[]; #include "DBwrapper.h" #include <string> int main() { std::s...
You need to define the static data member at namespace scope, not in a function like main: #include "DBwrapper.h" #include <string> // Static data members don't have anything to do with functions // and their scopes, so this must appear here: std::string DBwrapper::DBfile = "library.db3"; int main() { // Here, you...
66,406,916
66,407,191
From vectors of objects return one object as reference
#include <iostream> #include <vector> #include <random> #include <ranges> #include <algorithm> #include <chrono> #include <functional> namespace ranges = std::ranges; struct Model { double next_event_time; }; double timeit(int repeats, int items, std::function<void(int)> func) { auto begin = std::chrono::st...
The overload of std::ranges::min that accepts an arbitrary range returns by value. Because it returns a temporary value, you cannot bind a non-const lvalue reference to its return value. Even if you could, that reference would be dangling as soon as get_next_model2 returned. Use std::ranges::min_element instead. min...
66,407,215
66,407,292
c++ unit testing with dependency and file writing
I am a student and new for unit testing. I'm confused with testing problems when writing my project. I have three functions A(), B(string file) and C(). A() is used for initialization and it creates a directory temp to store files. B(string file) writes file in temp. C() transfer the current files in temp to another pl...
Typically every test environment provides something to initialize the test environment and shut this down after the test has run. For example, google test/gtest provides SetUp() and TearDown() for every fixture. In this fixtures you can do all needed initialization and shutdown functionality you need for testing your D...
66,407,357
66,407,862
How to change some keys in a std::map using extract and insert
I've recently read this question about node_type, and I learned that if I need to modify the key of a specific node in a map, I could extract the node, modify the key and insert the node back in the map (like in this example). Now, let's say I need to change the key of multiple nodes of this map, and to know which node...
The vector type is simple to address, since std:map specializations expose a type alias. std::vector<std::map<K,V>::node_type> tmp; The more involved point is the iteration. You cannot use a simple range-based for. That is because node extraction invalidates iterators to the extracted element. And that includes the it...
66,407,424
66,407,436
Why can't I use const when returning a reference?
For the sake of completeness, I want to provide me with a trivial unary + operator as well. The unary operators should be immutable, I think. If I make operator-() return a copy of the negated object, a statement -obj=other; (both obj and other are objects of type Complex) will not compile. However, if I make operator+...
You operator is marked const thus the *this is Complex const &. Your return type strips the const.
66,407,676
66,408,147
Why this linked list program to insert a node at the end is not giving any output?
This code is not giving any output. There can be different ways to implement linked list. But I want to find my error in this one. I can't find any error in this code. Here is my complete code #include <iostream> using namespace std; class node{ public: int data; node* next; node(int val){ data=...
But I want to find my error in this one. Following step by step of your insertAtTail function, you'll find that your head and your head->next pointers are pointing to the same memory location. After assigning your initial head pointer you are assigning the same value to the next node. A simple fix to your code is to ...
66,407,977
66,408,080
C++ variadic tempates with default argument
I'm trying to write a template that will measure the execution time of any function: template<typename Func, typename... Args> void measure(const Func& f, Args... args); I have a templated function with a default parameter compare: template<typename T, typename Compare = std::function<bool(T, T)>> void mergeSort(std::...
Wrap the function in a lambda with a single parameter: [](auto &vec){mergeSort<int>(vec);}. Also, typename Compare = std::function<bool(T, T)> is a bad idea, since the type erasure in std::function has some overhead. You should just use std::less<T> as the type.
66,408,258
66,408,592
'Overloading' function without input parameters based on template types
I'm started playing around with templates and came accross a problem with a need to call a function based on 2 template parameter types. I'm writting simple unit library that will have helper getConvertionFactor functions that will define ratio between units. I'd like to be able to pickup a function in template operato...
You can do it like this: template<class FromType, class ToType> double getConvertionFactor() { return 1; } template<> double getConvertionFactor<Kilometer, NauticalMile>() { return 1.852; } template<> double getConvertionFactor<NauticalMile, Kilometer>() { return 1 / 1.852; } template<class LHS_Unit, cla...
66,408,308
66,409,038
Getting std::valarray to (google/quick) bench properly
I'm trying to compare the performance of using std::valarray vs. std::vector/std::transform operations using Google Bench. I'm using QuickBench. My code (for QuickBench) is #include <random> class RG { public: double operator()() noexcept { return dis(gen); } private: std::mt19937 gen {std::random_device{}()}...
Line 36: std::valarray<double> v1{N}, v2{N}; This creates two one-element valarray-s, that is, each containing a single element whose value is N=1000. This is because the list-initialization syntax, {}, uses the constructor taking std::initializer_list: valarray(std::initializer_list<T> il); which constructs a valarr...
66,408,378
66,408,754
Clang AST: access member function templates from CXXRecordDecl
Say I have a dummy class like this: class Stack { public: template<typename T> void push(T val) { (void)val; } template<typename T> T pop() { return 0; } bool empty() const { return true; } }; The AST dump of which looks like: ... |-CXXRecordDecl 0x5610df147d60 <col:1, col:7> col:7 implicit class...
I believe I have now figured it out, I will answer my own question in case this is useful for someone else: The way to do this is to first cast the given CXXRecordDecl to DeclContext, iterate over the contained declarations and try to cast them to FunctionTemplateDecl, pseudocode: clang::CXXRecordDecl const *record = /...
66,408,544
66,408,677
Why does the resource remain accessible after it has been released and the program does not crash?
#include <iostream> #include <string> using namespace std; static inline string BoolToString(bool boolean_exp) { return boolean_exp? "True" : "False"; } class Foo { public: explicit Foo(int _size) noexcept : my_resource(new int[_size]) { cout << "Foo obj init, at: " << this << ", my_resource at...
After the function has finished running, the my_resource field in foo (declared in the main function) is still can be parsed and get value 1234567I would like to know why this is? It is undefined behavior, so it may work if you are unlucky. In typical C++ implementations, this has a good chance of not crashing, becau...
66,408,814
66,989,927
Running C++ Jupiter Notebook in VSCode Insiders
I have installed xeus, xeus-cling and jupyter extension. I changed the kernel to one of the C++ versions, the cell language to C++ but when I click run the cell never outputs. Can someone please help me solve this?
Running xeus-cling under vs-code Ceus works in the vs-code environment. You have to activate your conda environment and invoke vs-code from it (i use the code insiders edition). In linux this looks like conda activate xeus-cling # my env for xeus-cling; where i compiled cling then invoke code (insiders) in your proje...
66,408,868
66,409,109
why doesn't segmentation fault occur here?
if I don't define the size of my vector the segmentation fault will occur but in this way , I mean that I define the size lower than the size I use , the segmentation fault won't occur . but why? what is the difference between them ? #include <iostream> #include <string> using namespace std; #include <vector> int main(...
C++ has a notion of undefined behavior. Accessing a vector out-of-bounds is a typical example of undefined behavior (because vector::operator[] performs no bounds checking). Nothing meaningful can be said about the outcome of the program. But to explain what probably happens... A vector is a class that usually contains...
66,409,135
66,409,426
How to correctly link the cppgit2 library
Im trying for two days now to get cppgit2 working and I can not figure out how to do it. I have build it using cmake and make and am now trying to run one of the given examples. #include <iostream> #include <cppgit2/repository.hpp> int main() { auto repo = cppgit2::repository::open("/home/[...]"); repo.for_ea...
For everybody that might have this problem in the future: As pointed out by Tsyvarev in the comments, both the cppgit2 AND the git2 library have to be added to the cmake like so TARGET_LINK_LIBRARIES(cppgit2_error_solving ${CPPGIT2_LIBRARY} git2) That solved it for me.
66,409,270
66,427,058
How can I store objects of derived classes within a data structure from which can be accessed attributes which the base class does not have?
I am making a game and have different types for different "items", and want some way of storing them in an inventory. The issue I've got is that once they get put in the inventory, I cannot access attributes which the base class does not possess. Here's an example: class Item { public: std::string name; Item(...
I managed to solve this by storing the objects in the vector as type base class pointer Item* in this case, and creating virtual functions to retrieve the desired attributes: class Item { public: std::string name; Item(std::string n) : name{n} {}; virtual int getDamage() {return 0;} virtual int getArm...
66,409,871
66,410,070
arithmetic encoder symbol lookup
I have working simplish arithmetic encoder based on Drdobbs ARcoder. The de/encoding algorithm boils down to maintaining symbol probabilities in array and updating them. The problem is that I would like to expand it to support growing number of symbols than fixed +256 or so symbols. The current implementation of update...
Yes, you can arrange your counts into a tree. You have a leaf for every symbol that contains its probability (not cumulative), and then each internal node contains the sum of probabilities from the nodes beneath it. To update the model, you need to add 1 to the symbol's leaf and each of its ancestors. To search, you ...
66,410,202
66,410,292
Simple way of seperating large number into 2 numbers? c++
So I am trying to make a program that separates a large number like 123456 into 1234 and 56. The problem that I find is that I don't know how many numbers there will be, all I need is the last 2 digits and the first half. So basically I can get 12345678 and I need 1. 12345 2. 78 Maybe someone got an idea how should I t...
int x = 12345678; int x1 = x / 100; int x2 = x - x1 * 100; or int x2 = i % 100;
66,410,935
66,411,083
Question on entry point (beginner level )
I have started learning C++ according to a recommended list in Stack Overflow. There is book called "C++ primer" got me interested .Anyway in that book writer called "main" function an entry point. According to "Wikipedia" (what I understood) entry points are used to run a program .Does it give permission to OS to run ...
Does it give permission to OS to run my code? Nope. A program is a sequence of commands for the computer, commands such as std::cout << "Hello, world!\n";. The formal term for a such command (in C++) is statement. Statements are generally executed from top to bottom, but which statement should be executed first? Can'...
66,410,942
66,418,931
conflicting declaration error when making ACE 7.0.0 with Cygwin64
My operating system is Windows x64 When I try to make ACE using Cygwin I get the following compilation error: In file included from /cygdrive/c/resources/ACE_wrappers/ace/OS_NS_Thread.h:30, from /cygdrive/c/resources/ACE_wrappers/ace/Thread_Mutex.h:29, from /cygdrive/c/resources/ACE_wrappers/a...
The cygwin64 port isn't actively maintained so you need to update the ace/config-win32.h for this. You need to try which defines should be added to that file, when you have done that and it works, contribute your changes upstream at https://github.com/DOCGroup/ACE_TAO The issues section at https://github.com/DOCGroup/...
66,411,157
66,412,264
Import std lib as modules with clang
I am experimenting with modules in clang, and would like to include the standard lib as modules instead of as includes. Currently I do this #include <iostream> #include <string> It seems that you in msvc should be able to import standard libs with for example import std.core; When using clang however this does not se...
The C++20 standard does not include module definitions for the C++ standard library. Visual Studio does (unfortunately), and a lot of bad sites out there will act like this is standard. But it's not; it's just a Microsoft thing. If you want to include the C++ standard library through a module across platforms, you will...
66,411,296
66,411,411
bubbleSort only sorts first element C++
I've tried implementing the bubbleSort algorithm in every way I can think of and it's still only sorting the first number. I can't understand why this is happening. Any insight would be so helpful! I tried ***Please note I have to sort an array (so can't use a vector in implementation). bubbleSort.h #ifndef BUBBLE_SORT...
After the first outer loop, the value of j is already n-1 so the inner loop wont run. After each outer loop the last i elements are sorted so it should be for (j = 0; j < (n-i-1); j++)
66,411,447
66,411,806
How do i store a CSV file in variable as one big string
I want to achieve the same as this std::string data = "1.1,1.1,1.1,1.1,1.1,1.1\n" "2.2,2.2,2.2,2.2,2.2,2.2\n" "3.3,3.3,3.3,3.3,3.3,3.3\n" "4.4,4.4,4.4,4.4,4.4,4.4\n" "5.5,5.5,5.5,5.5,5.5,5.5\n" "6.6,6.6,6.6,6.6,6.6,6.6\n"; B...
Your variables are in the wrong scope: std::string data; if(inFile.is_open()) { while (inFile) { std::string line; getline(inFile, line); data += line+"\n"; } inFile.close(); } std::cout << data;
66,411,765
66,413,637
C++-module import chain results in strange compiler errors
When compiling c++-20 modules with clang. I get strange compilation errors when importing a file that imports another file that imports a third file like so: // a.cppm #include <string> export module a; export std::string getStuffA() { return "a"; } // b.cppm #include <string> import a; export module b; export ...
As already said, modules are supported in gcc 11, and you are trying to use clang with gcc 10 standard C++ library. With using the proper C++ standard library, preprocessor include directives such as #include <string> will be automatically mapped to import <string>;. With using the standard C++ library for gcc 10, that...
66,411,787
66,413,945
Normal map overrides smooth edges in DirectX 11
My object is a smooth barrel, with only the color and the original normals it looks like this: When I try to add the normal detail via a texture the smooth normals get overwritten like so: Is there a better way to merge the new normal texture without overriding the smooth edges? The code is mostly from the rastertek ...
The issue is this formula: // Calculate the normal from the data in the bump map. bumpNormal = (bumpMap.x * input.tangent) + (bumpMap.y * input.binormal) + (bumpMap.z * input.normal); The better approach is to create a matrix for the local tangent space, and then transform the local normal from the texture. // Given a...
66,411,968
66,412,348
need to output max and min (without array)
I'm writing a program that prompts the user to enter integer numbers. The program stops reading when user inputs 0. It should output the max and min element among inputed numbers. I must write it without using arrays. Input: 1 2 3 4 5 0 Output: min=1 max=5 My code: #include <iostream> using namespace std; int main() ...
You may want to input a starting value first, then loop: int main() { int n, min, max; cin >> n; min = n; max = n; if (n != 0) { while (cin >> n) { if (n == 0) break; if (n > max) max = n; if (n < min) min = n; } } std::cout << "min: " << min << ", max: " << max << "\n";...
66,412,198
66,412,395
Is it possible to return an associative container with a custom sort function?
In a project of mine I have to to return a map with a custom sort-function from a function, however I don't know how I'm supposed to specify the return-type of said function. A simplified example follows: #include <iostream> #include <map> std::map<std::string, bool> get_entries() { auto cmp = [](const std::string...
Yes: stop using lambdas like that. Make your custom sort function an actual type, since it is a clear part of your interface: struct custom_sort { bool operator() const (const std::string& a, const std::string& b) { return (a.length() != b.length()? a.length() > b.length(): a < b); }; }; std::map<std...
66,412,222
66,412,275
Same behaviour for size() vs .size() with string?
Is there any difference in output behaviour between using size(x) instead of x.size(), where x is a string variable? Or it is just another alias?
The behavior of std::size is: Returns the size of the given container c or array array. 1-2) Returns c.size(), converted to the return type if necessary. ... So calling std::size(x) and x.size() has the same effect, where x is a std::string. (This function can also accept an array, but that's not relevant when it c...
66,412,463
66,473,521
How to make the return type of a virtual member function parametric
I am implementing a visitor pattern for a syntax tree in C++. Every node in the tree is derived from a base class Expr which declares a pure virtual method accept. The accept method takes a reference to an instance of Visitor. Visitor is also an abstract class declaring a visit method for every type of node in the synt...
For completeness, another approach I found to solve this problem is described here: https://www.codeproject.com/Tips/1018315/Visitor-with-the-Return-Value. This follows the classic visitor pattern (i.e., have visit and accept methods return void). Different return types are taken care of by a separate template class, a...
66,412,529
66,413,172
C++ invalid conversion from 'int' to 'int*' [-fpermissive]
I am new to C++, am trying to write a program that computes profit and tax for #include <iostream> using namespace std; //FUNCTION PROTOTYPE - we are simply defining the function but the body function is in another file int taxCalculator(int qnty[], int s_px[]); int profitCalculator(int unit_selling_price[], int ...
You imagined your functions to work on the integer values you're passing them, but wrote them using the array syntax. //Function to calculate tax int taxCalculator( int qnty, int s_px) { int tax; if (qnty < 1500) { tax = 0.15 * qnty * s_px; } else if (qnty >= 1500 && qnty < 3000) { ...
66,413,131
66,413,371
C++ static constant array initialization inside class
I want to create a constant and static integer array as a public class variable. It is neat to define it and initialize it right away. See code below for complete example. #include <iostream> class Foo { public: constexpr static int arr[3][2] = { {1, 2}, {3, 4}, {5, 6} }; };...
Before C++17 (so C++11 and C++14) you have to add constexpr int Foo::arr[3][2]; outside the body of class.
66,413,139
66,413,424
MQTT: cannot subsribe to the topic in Qt
Im trying to read a data from localhost mqtt broker. For that purpose i am using following code: m_client = new QMqttClient(this); m_client->setHostname("127.0.0.1"); m_client->setPort(1883); m_client->connectToHost(); connect(m_client,&QMqttClient::connected,this,&mqtt::isConnected);//um zu sehen, ...
The subscription must be given after the connection, so you must invoke subscribe in the isConnected method: void mqtt::isConnected() { qDebug() << "client is connected"; topic.setFilter("test"); auto subscription = m_client->subscribe(topic, qos0); qDebug() << subscription }
66,413,212
66,413,265
Free memory created by instantiating base class with parent type that has protected destructor
I think this is probably a really simple question, but I am as much a C++ developer as the guys at the walmart meat counter are butchers. Say I have: class Parent{ protected: ~Parent(){}; }; class ChildA : public Parent{ }; struct Container{ Parent *child; //Tried this, causes: munmap_chunk(): i...
When you eventually call delete, you must pass it precisely the value you got from new. So you must store the value that new returns somewhere. But look at your call to new -- it dereferences that value and never stores it anywhere. So how can you call delete?! Container MakeStruct(){ ChildA child = *new ChildA();...
66,413,543
66,425,815
How to append semicolon (;) to cmake string
In cmake 3.19.2 i try to add semicolon to string by the following way: cmake_minimum_required(VERSION 3.12) project(some_project) #-------------------------------------------------------------------- # Set CPP standard #-------------------------------------------------------------------- set(CMAKE_CXX_STANDARD 17) set...
It's strange, but it works: #-------------------------------------------------------------------- # Generate include list #-------------------------------------------------------------------- set(INSTALLED_INCLUDES ) foreach(header_path ${HEADER_FILES}) string(CONCAT INSTALLED_INCLUDES "${INSTALLED_INCLUDES}${heade...
66,413,876
66,413,952
Custom array-like type in c++
In a program I am writing, I need to use often integer arrays of length 3 and I thought I should define a custom type. The integers they will hold are between 0 and 2, so int8 is more than enough. My goal is to avoid having to check explicitly for length. I could do something of the form: class MyArr { int8_t a; ...
I think the best way is to use std::array and if you want bounds checking you can use the at() function instead of operator[]. https://en.cppreference.com/w/cpp/container/array/at Example: #include <array> std::array<int8_t, 3> data = { 1, 2, 4 }; // Set element 1 data.at(1) = 88;
66,414,070
66,414,164
c++ semicolon - what are the rules for loops and statements?
I'm learning C++ and generally it has good and clear rules - but I'm a little confused about the rules related to semicolon. The following two examples are working fine - but what is the best practice - and what is the logic behind it? Example1 (without semicolon): #include <iostream> using namespace std; int main () ...
Example 2, reformatted: #include <iostream> using namespace std; int main () { for (int i = 0; i < 10; i++) { if (true) { cout << i << endl; } /*do nothing*/ ; } /*do nothing*/ ; } /*do nothing*/ ; In other words, ; in this case is simply an empty statement, totally sup...
66,414,299
66,421,535
Reference initialization - temporary bound to return value
In an article about reference initialization at cppreference.com (Lifetime of a temporary), it says: a temporary bound to a return value of a function in a return statement is not extended: it is destroyed immediately at the end of the return expression. Such function always returns a dangling reference. This excerpt...
Your example is very good, but your compiler is not. A temporary is often a literal value, a function return value, but also an object passed to a function using the syntax "class_name(constructor_arguments)". For example, before lambda expressions were introduced to C++, to sort things one would define some struct X w...
66,414,307
66,414,329
Refer to a std::string as a char*
I would like to refer (write) to a std::string like I would to a string literal (char*). This is what I'm trying to do: std::string File::readAll(){ std::string ret; ret.reserve(this->size+1); fseek(file, 0, SEEK_SET); fread((char*)ret.c_str(), size, 1, this->file); ret.append("\0"); return ...
Replace reserve with resize and then use .data() (or &ret[0] pre C++17) instead of .c_str().
66,414,510
66,414,905
Is returning from a noreturn function undefined behavior, if it returns with a call to another noreturn function?
Let's say that I'm making an application which will be long lasted, and not expected to terminate for any normal reasons (e.g. user terminates application, e.x.: an HTTP server). I mark main itself with the C++11 standard attribute [[noreturn]], indicating that it must never return control back to the callee without ab...
Is it safe to return into other noreturn functions, or is this undefined behavior? I wonder if there's some language confusion here. I'm not sure if you mean if it's UB for main() to return using the hypothetical return value from realMain() which it never should get; or if it's UB for realMain() to return back to ma...
66,414,527
66,414,592
Finding letters in a string while ignoring everything else
For my homework, part of what I need to do is take a phrase from the user, and from there take only the letters in the phrase, ignoring numbers, spaces, and special characters. Once I find letters in the string, I need to store them into a separate variable. However, I can't get that variable to store anything outsid...
your temp variable is an empty string. temp[x] is telling the compiler to change the x-th character of that string(which doesn't make any sense, as the string doesn't have any characters!). You're lucky(or unlucky) that you aren't getting any Segmentation faults(crashes). Just use the += operator: temp += line[i];
66,414,566
66,414,606
C++ set allowing duplicates?
I am attempting to solve the interview problem from leet code to remove duplicates from a vector of ints. Below is my my code for the answer: #include <vector> #include <set> using namespace std; class Solution { public: int removeDuplicates(vector<int>& nums) { vector<int>::iterator itr; set<int> ...
This is because this is undefined behavior. nums.erase(itr); std::vector's erase() method invalidates all existing iterators "at or after the point of the erase". Since itr is the "point of the erase", itr is no longer a valid iterator when erase() returns. Subsequent attempt to increment it, in the for loop's itera...
66,414,708
66,425,610
Converting Cartesian Coordinates To Polar Coordinates
I'm trying to covert an image from Polar Coordinates to Cartesian Coordinates but after applying the formulas I get float coordinates (r and teta) and I don't know how to represent the points in space using floats for x and y. There might be a way of transforming them in int numbers and still preserving the distributio...
Your implementation attempts to express every integer-coordinate point inside a given circle in polar-coordinates. In this way, however, you terminate with an array of coordinates toghether with a value. If instead you want to geometrically transform your image, you should: create the destination image with proper wid...
66,414,845
66,438,096
How to link OpenCV with MATLAB for macOS
I am trying to run C++ code that uses the OpenCV library with MATLAB and mex command (the code already has a mexFunction). I already have the OpenCV library installed, I used it with Python before. I assume that it should work for running C++ code. I am running this command to compile the code on MATLAB: mex -setup me...
1- The fix was by using the correct paths to the opencv library and Include folder, since I have on my computer several files for opencv that are installed using pip for python projects, I change the path to opencv folder that installed by brew. 2- I also added all the needed -l files not only -llibopencv_core. By the ...
66,415,005
66,415,092
returning QString for QML-Usage
idk why, but I can't read a return value of a QString method from .cpp-code in .qml-code, although I did everything logically correct (I'll put only relatable parts of code): .h File: public: Q_INVOKABLE QString displayOnQml(); QString message; public slots: void updateMessage(const QMqttMessage &msg); .cpp...
The Q_INVOKABLE do not create a binding since you cannot know when the string changed. In this case it is better to create a Q_PROPERTY: *.cpp class mqtt: ...{ Q_OBJECT // ... Q_PROPERTY(QString message READ message NOTIFY messageChanged) public: // ... QString message() const; // ... Q_SIGNALS:...
66,415,608
66,415,664
Why is fullName not displaying name after space
The final cout is not displaying the cin fullName: int main() { string fullName; cout << "Type your full name: "; cin >> fullName; cout << "Your name is: " << fullName; //this final cout is not displaying the cin fullName system("pause>0"); }
cin does not work with spaces in the input, the rest of your input is in the buffer. Try using getline like this: int main() { string fullName; cout << "Type your full name:" ; getline(cin,fullName); cout << "Your name is: " << fullName; system("pause>0"); } This way it will save into your variab...
66,415,855
66,416,134
C++ Using the increment operator on a pointer to dynamic memory
Is it not valid to use an increment operator on a pointer to dynamic memory in C++ when assigning the values to said dynamic memory? Or am I doing something wrong here? I am unable to find anything definitive on this specific point in any of the forums in my web searches, (mostly here in stackoverflow). This version of...
Whenever you increment a pointer you have to save a copy before you return it, this is also an advice for Linked List where you access each following nodes but want to save address of the very first one. So in your case: int* apply_all(const int* arr1 , size_t arr1_size, const int* arr2 , size_t arr2_size) { int* pA...
66,416,114
66,416,225
How to input a std::string_view in C++?
This is the normal way to input(kinda) a std::string_view variable : #include <bits/stdc++.h> using namespace std; int main() { string str; // Still have to use std::string class // Resulting in stack/heap allocation getline(cin, str); string_view view(str); return 0; } I was wondering is there any w...
No, there is no way to read input into a string view. If you want to input a string, you have to store it somewhere. It doesn't necessarily have to be std::string, but that is the simplest option.
66,416,368
66,416,412
openssl command encrypt data does not match EVP_aes_128_cbc C code
I tried the following C implementation of Openssl EVP function for AES-128-CBC encryption but the results I am getting are incorrect compared to the command line OpenSSL result. I referenced the code on the site below. https://wiki.openssl.org/index.php/EVP_Symmetric_Encryption_and_Decryption C code implementation of A...
The key and IV passed on the command line should be formatted as a hex string representing the bytes of the key and IV, not as ASCII text. So instead of: -K 0123456789012345 -iv 0123456789012345 You want: -K 30313233343536373839303132333435 -iv 30313233343536373839303132333435
66,416,615
66,416,851
Is it necessary to traverse a General Tree for destroying the tree (destructor)?
When destroying(when objects is out of scope) General Tree is it necessary to traverse each node and deleting them like you do with doubly linked list? The General Tree I am writing is a circular so that insertion can be done in constant time. It would be much helpful if someone could help me fix the error. The destruc...
You will need to call the destructor of each of the members of the tree in some way, either by traversing the tree in recursive manner (like your implementation) or by iterative methods. Simplest iterative approach would be to use a stack and add the elements as you go down the tree, and pop the elements to delete them...
66,416,654
66,434,910
Converting mixed type return data from an unmanaged C DLL?
I am writing a wrapper C# DLL to interface with a supplier provided unmanaged DLL written in C. For the most part everything is smooth, however there are some functions that in the provided documentation look like this: int get_value(int unit, int id, int* value) My issue is that int* value is an array with a mixture ...
int* value is an array with a mixture of int's and float's... That's a serious violation of the strict aliasing rule and will invoke undefined behavior. In C you'll have to use a union instead. The documentation should be like this union Value { int i; float f; }; int get_value(int unit, int id, union Value*...
66,417,011
66,419,065
How can a pointer to local scoped object still invoke the object method?
In my understanding that might be wrong, declaring a pointer to local object is dangerous or probably has no purpose. The following globally defined function Factory that returns a pointer to a local object has no purpose. Right after invoking Factory(), the returned address is pointing to a local object that has been ...
Undefined behavior First I want to give you a brief explanation of undefined behavior. If you want to you can read more here Undefined behavior. Undefinded behavior renders the entire program meaningless if certain rules of the language are violated. The compiler can basicly decide what to do. But like mentioned on c...
66,417,724
66,417,920
Singly Linked List Doesn't work when i am using Node(key,data) rather than Node.key and Node.data in C++
Created a Node to use in Singly Linked List, Nodes are getting successful created by both methods i.e n.key, n.data and n(data,key) Code Works Properly when I use n.key, n.data method But when I use n(key, data) n1 got appended but n2 failed to do #include <iostream> using namespace std; class Node{ public: ...
The constructor that takes the two arguments does not initialise next: Node(int k, int d){ key = k; data = d; next = NULL; // <--- was missing }