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
74,469,980
74,470,032
How to make concept that checks type equality for any templated type in C++?
In C++ you can make concepts that check for specific type equality: template<typename T> concept Int = std::is_same_v<T, int>; template<typename T> concept String = std::is_same_v<T, std::string>; Is it possible to make a concept that checks for type equality of any type, so I could make templates looking something li...
I mean, you could write a concept to do that. Or you could just use std::same_as: template<std::same_as<int>... Ints> void passInts(Ints... ints) template<std::same_as<std::string>... Strings> void passStrings(Strings... strings) When a concept is used against a template parameter pack, it is applied individually to e...
74,470,769
74,470,976
Verify whether the key exists in a map and access the iterator in the caller
I am trying to know in the caller whether the value in the underlying map exists, and if so, return a reference/iterator to it since the caller needs its access. Typically you check whether the element exists in a map by verifying whether the returned iterator == map.end(), but here there's no way in the caller to tell...
Why return an iterator at all? Surely the right way would be to return the int if it exists? If so you can use optional to indicate if it is valid or not: std::optional<int> get(int key) { std::unordered_map<int,int>::iterator it = m.find(key); if (it != m.end()) return it->second; return std::nullo...
74,470,941
74,471,246
Question on basic_string.h implementation
I was looking at the basic_string.h implementation to understand more and try to compile it in a separate namespace. I have the below compile error and was confused. I am using gcc compiler 12.1 basic_string.h: error: wrong number of template arguments (1, should be 3) operator==(const basic_string<_CharT>& __lhs, The...
The file you are referencing is <bits/basic_string.h> in the standard library path of the libstdc++ standard library implementation. As you are saying it defines std::basic_string without providing default arguments to any of its three template parameter. However the standard requires that the second and third be defau...
74,471,107
74,471,145
How to round in functions
void isRight(float sideA, float sideB, float sideC){ float aSquared = sideA * sideA; float bSquared = sideB * sideB; float cSquared = sideC * sideC; round(aSquared); round(bSquared); round(cSquared); if (aSquared + bSquared == cSquared || cSquared + bSquared == aSquared || aSquared + cSquared == bSquared){ cout <<...
This is happening because of Floaing point precision loss. C++ built-in floating point types are finite in precision. double is usually implemented as IEEE-754 double precision, meaning it has 53 bits of mantissa (the "value") precision, 11 bits of exponent precision, and 1 sign bit. To solve this, you can do the follo...
74,471,983
74,472,105
How can we declare lvalue inplace while calling a function with lvalue reference parameter?
If I have a function like this: int calc(const DataVec& data_vec, int& sub_sum); how can I call that without a explicit lvalue definition of type int? auto calc_result = calc(data_vec, int()); // error, int() is not a lvalue Below is a valid form: int _; // not interested auto calc_result = calc(data_vec, _);
This can be solved with function overloading. Like int calc(const DataVec& data_vec); Your overloaded function could be a simple wrapper around your dummy-int variable workaround: int calc(const DataVec& data_vec) { int dummy = 0; return calc(data_vec, dummy); } Please note that this might be a suitable worka...
74,472,175
74,472,235
how to run Bool function if if statement is true
bool isTriangle(double sideA, double sideB, double sideC){ if(sideA + sideB > sideC && sideA + sideC > sideB && sideB + sideC > sideA){ return true; }else{ return false; } } int main() { double sideA, sideB, sideC; cout << "Enter the lengths of the three sides of a triangle -- "; cin >> sideA >> sideB >> side...
This if (&isTriangle){ should be this if (isTriangle(sideA, sideB, sideC)){ When you call a function, you use the name of that function followed by parentheses () and you put the parameters that the function requires inside the parentheses separated by commas. Some other suggestions. If you want to test something and...
74,472,823
74,597,670
Which Visual Studio project settings affect the list of DLLs imported at the start of the program?
There are two PCs with Visual Studio 2017 installed. I'm running a simple program on both of them, one that lists the name of modules (exes/DLLs) inside its own process. But I get wildly different results. On one PC, I only get 7 modules: Lab7_1.exe ntdll.dll KERNEL32.DLL KERNELBASE.dll MSVCP140D.dl...
Okay, turns out it's not related to Visual Studio settings. I compiled the sample code on one machine, ran in on the other, and got the same result as if I compiled the code there. So it's either Windows version (7 vs 10) or MS VS Redistributable version (though I think both projects used v140). In either case, I can't...
74,473,008
74,474,292
Why is std::forward necessary for checking if a type can be converted to another without narrowing in C++20
To make a concept checking if a type can be converted without narrowing to another, it is proposed here to make it using std::forward and std::type_identity_t like this: template<class T, class U> concept __construct_without_narrowing = requires (U&& x) { { std::type_identity_t<T[]>{std::forward<U>(x)} } -> T[1]; }...
This is the usual approach for type traits like this that involve some kind of function/constructor argument. U is the type from which T is supposed to be constructed, but if we want to discuss the construction we also need to consider the value category of the argument. It may be an lvalue or a rvalue and this can aff...
74,473,260
74,474,056
Do ASIOs io_context.run() lock the thread into busy waiting
I think a straightforward question that i cant seem to find any information on. When calling ASIOs io_context.run(), if there is at that moment nothing yet to read/write asynchronously, does asio do busy waiting with that thread or does it do something more clever where the thread can be released and used in other part...
It's not busy-waiting. This is documented here: The Proactor Design Pattern: Concurrency Without Threads It highlights what underlying API's are preferred depending on platforms: On many platforms, Boost.Asio implements the Proactor design pattern in terms of a Reactor, such as select, epoll or kqueue. And On Window...
74,473,410
74,473,556
Unordered map hash function
#include <iostream> #include <unordered_map> #include <utility> #include <cmath> #include <stdint.h> template <class T> struct Vec2 { T x, y; Vec2() : x(0) , y(0) { }; Vec2(T xn, T yn) : x(xn), y(yn) { }; bool operator==(const Vec2& vec) const { return (x == vec.x) and (y == v...
You have a map with keys of pairs of iVecs but your hash is for single iVecs, that doesnt match. Though this will only be the next error you will be getting after fixing the current one. It seems you try to pass an instance HashVec2int{300} as template argument when a type is expected. If maximum does not change (it sh...
74,473,588
74,473,718
removing spaces - pass by reference
prompt - c++ Write a program that removes all spaces from the given input. Ex: If the input is: "Hello my name is John." the output is: HellomynameisJohn. Your program must define and call the following function. The function should return a string representing the input string without spaces. void RemoveSpaces(string ...
It seems to be a common newbie confusion. Printing gets confused with other concepts. If a function prints something, then the function is 'returning' what is printed. This is completely untrue, printing is printing, nothing else. If you want to write a function that removes spaces from a string, then that is what the ...
74,474,201
74,475,662
GCC and Clang seem not to obey the overload resolution in the allocation function call
Consider this example #include <iostream> struct A{ void* operator new(std::size_t N, std::align_val_t){ // #1 return malloc(sizeof(char)* N); } }; int main(){ auto ptr = new A; // #2 } Both GCC and Clang complain that <source>:9:17: error: no matching function for call to 'operator new' au...
At present the only major compiler that implements CWG 2282 is MSVC. I'm not aware of any current effort or feature requests for GCC or clang. Also, I don't believe the __cpp_aligned_new feature test macro has been updated for CWG 2282, so you'll need to use old-fashioned compiler version checking to determine whether ...
74,474,270
74,474,364
When to use std::numeric_limits<double>::espsilon() instead of DBL_EPSILON
I understood that std::numeric_limits::espsilon() and DBL_EPSILON should deliver the same value but are defined in different headers, limits, and cfloat. Which makes std::numeric_limits::espsilon() a c++ style way of writing and DBL_EPSILON the c style. My question is if there is any benefit in using std::numeric_limit...
Here on this page https://en.cppreference.com/w/cpp/types/numeric_limits you can find tables of what are the C marco equivalents of the std::numeric_limits. They are equivalents, so for any pair of std::limits function/constant and C macro you find in the table, they can be interchanged. The big difference is in generi...
74,474,371
74,474,681
Concept that requires a certain return type of member
I have some trouble getting started with C++20 concepts. I want to define a concept that requires a class to have a member called count_ that must be of type int: #include <concepts> template <typename T> concept HasCount = requires(T thing) { { thing.count_ } -> std::same_as<int>; }; The following struct should ...
If count_ is a member of thing with declared type int, then the expression thing.count_ is also of type int and the expression's value category is lvalue. A compound requirement of the form { E } -> C will test whether decltype((E)) satisfies C. In other words, it tests whether the type of the expression E, not the typ...
74,474,636
74,475,517
Why is only the first Child Process printing something out?
The program I am working on is called myfile - It should find a file in a certain searchpath. You should also be able to search for multiple files and if so, I MUST create multiple child processes with fork(). The problem is, i dont get the expected outcome printed out. If I am searching for multiple files, only the fi...
Looks like a problem with opendir, readdir, and reusing variables. I cut your program down to: int main(int argc, char **argv) { struct dirent *d; DIR *dr; dr = opendir(argv[1]); for (int i = 2; i < argc; i++) { if (fork() == 0) { cout << "Current PID: " << getpid() << "...
74,474,821
74,475,621
C++: Copy the vector of pointers to arrays, to Eigen::ArrayXd
I have std::vector<double *> x, in which each elements points to C-style double array. The values of double arrays are changing with each iteration of my program. I would like to create a copy of them into Eigen::ArrayXd x_old so I can compute a difference with new values. I have tried to use Eigen::Map but it copied o...
The problem with memcpy(x_old.data(), *x.data(), 4*sizeof(double)); is that since you manually allocated memory for each elements of the vector, the data underneath aren't contiguous anymore, ie 2 is not followed by 3.(The locations of the pointers are contiguous, but the arrays they are pointing to are not) So when yo...
74,475,178
74,475,767
Passing a reference to an abstract class object
I have an abstract syntax tree class which uses the visitor pattern. All constructors and the visit functions take in a reference to the abstract node 'ASTNode' or its derived classes. class ASTNode { public: virtual void accept(ASTVisitor& visitor) = 0; }; class NameNode : public ASTNode { public: NameNode(st...
Since ASTNode is purely virtual you cannot construct an instance of it, moreover you should not use value semantics when dealing with polymorphic types, because of slicing. Secondly in the example shown you return a reference to a local variable. You should either use pointers (as you mentioned) and construct the tree ...
74,475,436
74,478,041
mkTime() function does not pick correct timezone c++
I am getting an input date from user and convert it into tm struct, (setting is_dst, timezone and gmtoff parameters of tm struct using local time), but when I am using mkTime to get epoch value it changes the timezone and gmtOffset property of tm struct and return the wrong offset value. tm tmStartDateTime = {}; string...
localtime() is using the DST setting for the time you passed to it, not the current time when the function is called. DST was in effect in the UK on 1 Jan 1970, so it will return summer time regardless of whether DST is in effect today.
74,475,799
74,475,945
SMBUS undefined reference
I'm trying to make simple program in c++ to read from SMBus, but can't even build program sample. I'm building with gcc(9.4.0) on Ubuntu 20.04.5 LTS. I've installed libi2c-dev i2c-tools Code: #include <cstdio> extern "C" { #include <linux/i2c.h> #include <linux/i2c-dev.h> #include <i2c/smbus.h> } #includ...
The order of the source file and the library is relevant. The following command should work: gcc test_inc.cpp -li2c
74,476,213
74,490,320
c++ convert fmt::format_string<Args...>to std::string_view
I'm currently struggling to convert fmt::format_string<Args...>to a std::string_view. The idea: I would like to create a fucntion with can be called from an ISR and task context. However in an ISR no dynamic memory allocation is allowed. That's why i cannot call fmt::fomat() in this case. However I'm getting a strange ...
as suggested by @user17732522 in the comments the answer is changing String_T& to String_T and renaming template <typename String_T> bool logAsync( String_T& strFormatedDebugMessage, String_T& strCategory, const std::source_location loc = std::source_location::current() ); to template <typena...
74,478,276
74,478,374
Constructor of virtual genetic class
I have this code: sensor.h: template<class T> class Sensor { public: uint8_t address; T data; virtual void collectData() = 0; Sensor(uint8_t address); }; class TemperatureSensor: public Sensor<float> { void collectData(); }; sensor.cpp: template<typename T> Sensor<T>::Sensor(ui...
I want to create TemperatureSensor using constructor defined by Sensor ex: TemperatureSensor sensor(0xbeef/*address*/) If you want to use base class constructor directly, you can use using class TemperatureSensor: public Sensor<float> { using Sensor::Sensor; void collectData(); };
74,478,546
74,488,909
IOUserClientMethodArguments completion value is always NULL
I'm trying to use IOConnectCallAsyncStructMethod in order set a callback between a client and a driver in DriverKit for iPadOS. This is how I call IOConnectCallAsyncStructMethod ret = IOConnectCallAsyncStructMethod(connection, MessageType_RegisterAsyncCallback, masterPort, asyncRef, kIOAsyncCalloutCount, nullptr, 0...
The likely cause for kIOReturnBadArgument: The port argument in your method call looks suspicious: IOConnectCallAsyncStructMethod(connection, MessageType_RegisterAsyncCallback, masterPort, … ------------------------------------------------------------------------------^^^^^^^^^^ If you're passing the IOKit main/master...
74,478,818
74,549,164
How to build a CMake project with MSVC 2015?
I try to build a CMake (v3.14) project with MSVC 2015. I use the CMake GUI to generate the makefile but when I hit the "Configure" button, I get the following error: The C compiler identification is MSVC 19.0.24210.0 The CXX compiler identification is MSVC 19.0.24210.0 Check for working C compiler: C:/Program Files (x8...
Indeed, CMake couldn't find the program mt.exe because the Windows SDK folder wasn't in the PATH variable. To solve this problem, I need to execute this command with these arguments: "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x64 8.1
74,479,052
74,531,214
Does NPP support overlapping streams?
I'm trying to perform multiple async 2D convolutions on a single image with multiple filters using NVIDIA's NPP library method nppiFilterBorder_32f_C1R_Ctx. However, even after creating multiple streams and assigning them to NPPI's method, the overlapping isn't happening; NVIDIA's nvvp informs the same: That said, I'm...
To summarize and add to the comments: The profile does show small overlaps, so the answer to the title question is clearly yes. The reason for the overlap being so small is just that each NPP kernel already needs all resources of the used GPU for most of its runtime. At the end of each kernel one can probably see the t...
74,480,024
74,510,227
Is there a non-hacky way in libfmt to construct names for named arguments at runtime?
I am using libfmt to build a code generator that generates a sort of adapter layer around an existing library. So I have a dataset of parameter descriptions that include format strings describing the conversion from the data type in the outer layer to the data type in the inner layer. In the most simple case, this migh...
In general, it's better to use a template system like Mustache for this. That said, storing argument names as std::strings on the side and use them to construct dynamic_format_arg_store is OK. There is nothing hacky about it.
74,480,056
74,480,302
`operator type&` confusion
I have user-defined type: class String::CharProxy { public: const char* operator&() const; char* operator&(); operator char() const; operator char&(); }; The problem is when I'm trying to perform some explicit casts, the wrong operator is called: CharProxy p(...); static_cast<char>(p); // operator char...
In your static_cast, both operator char() const and operator char&() are candidate functions as per [over.match.conv] because both char and char& are convertible to char via a standard conversion sequence. Between the two functions, the compiler then decides by standard overload resolution rules. In these, operator cha...
74,480,093
74,480,877
pybind11: pass *C-style* function pointer as a parameter
I'm currently porting a C library to python using pybind11, and it has lots of C-style function pointers (i.e. not std::function, as described in https://pybind11.readthedocs.io/en/stable/advanced/cast/functional.html) So my question is: is there an easy way to handle C style function pointers, when they are passed a f...
Well, you need to store the function state somewhere. The simplest solution would be to put it in a local static variable: m.def("glfwSetMonitorCallback", [](std::function<std::remove_pointer_t<GLFWmonitorfun>> f) { static std::function<std::remove_pointer_t<GLFWmonitorfun>> callback; callback = std::move(f); ...
74,480,645
74,482,353
Forward a variadic instance method call via a pointer to member function in C++
I'm working on a class representation utility that would work in a similar way to Java's Class class. That is, a mechanism that would emulate class reflection. #include <map> #include <stdexcept> #include <string> template<typename Class> struct class_repr { std::map<std::string, uintptr_t> fields; std::map<s...
You can create a class representing any member function using type erasure (modified from this SO answer). No void*, no C-stype ellipsis .... #include <memory> #include <any> #include <vector> #include <functional> class MemberFunction { public: template <typename R, typename C, typename... Args> MemberFuncti...
74,481,147
74,481,311
How to clear cin input buffer
int main() { string inputName; int age; // Set exception mask for cin stream cin.exceptions(ios::failbit); cin >> inputName; while (inputName != "-1") { // FIXME: The following line will throw an ios_base::failure. // Insert a try/catch statement to catch the exception. ...
I don't quite understand what you want to fix. In any case, I just fixed the problem with cleaning the cin. #include <iostream> #include <limits> using namespace std; int main() { string inputName; int age; // Set exception mask for cin stream cin.exceptions(ios::failbit); cout << "Input...
74,481,793
74,482,021
Use std::string_view size in template parameter from NTTP constructor
I have a simple C++20 compile-time string type that is defined like this: template<std::size_t N> class compile_time_string_storage { public: constexpr compile_time_string_storage(std::array<char, N> str) noexcept : value(str) { } constexpr compile_time_string_storage(const char (&str)[N]) noex...
Is there a way of using a std::string_view to initialise compile_time_string_storage? Your problem is that you seem to want a number of things that cannot all go together. You want: To create a compile_time_string_storage from a constexpr string_view without specifying the size explicitly as a template parameter. To...
74,482,149
74,482,588
Making linker errors more helpful through specificity (C/C++)
This is my first time asking a question here, as I'm usually able to find answers in previous posts, but I can't find any information on this topic. I'm trying to write C/C++ header files that can be reused between projects. One of my headers uses <math.h> (deprecated in C++, so it uses <cmath> instead). When I compile...
The build process runs in different phases. The compilation phase takes your program code including the header file and produces a so called object files (with the file extension .o). The same applies for your library. You get a set of object files. When you tell the compiler to produce a static library it takes a set ...
74,483,053
74,486,126
Why does my vulkan compute shader receive a 0.0 float as -170146355474918162907645410264962039808.0?
I'm working on a small vulkan app that utilises compute shaders to transform some geometry data. This data is sent to a single compute shader via multiple storage buffers. To ensure that everything is reaching my compute shader as expected (no byte alignment issues etc.), i've temporarily created an output buffer to wh...
As @chux-ReinstateMonica correctly pointed out, the hex code of above float is ff0000ff, which does look like a colour hex code imo. Turns out I forgot to set the offset in the vkBindBufferMemory instruction, causing my colour buffer to overwrite my instances. It was only by coincidence, that the y-coordinate of the fi...
74,483,127
74,491,504
how to get a GET/POST variable with a c++ CGI program?
my google-fu has failed me, I'm looking for a basic way to get GET/POST data from an html forum page on my server to use in a c++ CGI program using only basic libraries. (using an apache server, on ubuntu 22.04.1) here's the code I've tried the HTML page: <!doctype html> <html> <head> <title>Our Funky H...
okay, 2 different methods, depending if it's a post or get method: -GET- html: <!doctype html> <html> <head> <title>Website title obv</title> </head> <body> Content goes here yay. <h2>Sign Up </h2> <form action="cgi-bin/a.cgi" method="get"> <input type="text" name="username" value="SampleName"> <inpu...
74,483,386
74,483,405
Best datastructure for iterating over and moving elements to front
As part of a solution to a bigger problem that is finding the solution to a maximum flow problem. In my implementation of the relabel-to-front algorithm I'm having a performance bottleneck that I didn't expect. The general structure for storing the graph data is as follows: struct edge{ int destination; int cap...
It seems to me that this is what std::deque<> is for. Imagine it as a 'non-continuous vector', or some vector-like batches tied together. You can use the same interface as vector, except that you cannot assume that adding an index to the first element's pointer results in the given element (or anything sensible other t...
74,483,471
74,483,834
How do I use test cases for competitive programming? CodeChef C++
I've just started getting into competitive programming on CodeChef and I was working on this challenge and for the most part, it works, but I'm not sure how to implement the test cases. I've seen solutions where people use a while loop and decrement the T, I tried that but I had no luck. Here is the Problem statement: ...
Competitive programming is fun! It's a good exercise for writing compact and fast code. Don't be thrown off by the term 'test cases', it's just a fancy name for 'numbers'. First read T, then read N, looping T times. Something a bit like that: size_t T; std::cin >> T; while (T--) // loop T times { std::string N;...
74,483,661
74,483,704
C++ convert an unsigned int in range [0, 2^n) to signed int in range [-2^(n-1), 2^(n-1) )
At the outset, I realize what I did was bad. I relied on what is now (at least) undefined behavior, if not explicitly forbidden. It used to work, and I thought I was being clever. Now it doesn't and I'm trying to fix it. I have positive power-of-2 numbers (FFT bin index, but not important). I want to effectively FFT-sh...
How about: auto wrapper = Wrapper<9>{ index & (1 << (9 - 1)) ? long(index) - 2 * (1 << (9 - 1)) : index }; If, for some reason (e.g. performance), ternary is not preferred, then you might also try: auto wrapper = Wrapper<9>{ long(index) - 2 * (index & (1 << (9 - 1))) };
74,484,422
74,484,453
how to use if else c++
How do you provide a condition in the if statement, if the variable is an integer data type then it will be displayed, and if the variable is any other data type then something else will be displayed? #include <iostream> #include <stdlib.h> #include <windows.h> #include <conio.h> using namespace std; int main() { ...
From the istream::operator>> man page: If extraction fails (e.g. if a letter was entered where a digit is expected), zero is written to value and failbit is set. So, your function could test the cin.good() method to see if the >> operation was successful, like this: cin >> p; if (cin.good()) { cout << "The integer...
74,485,364
74,485,609
What actually happens when this type of condition in the for loop is checked?
I can't understand the difference between the condition checked in a for loop and an if condition. Do both behave in a different way? When I write: int num = 10; for(int i = 0; i < 15 && num; i++){ cout << i << " "; } It only checks whether i < 15 and it doesn't check for i < num and prints all the way from 0 to 1...
The condition of a loop (whether a for loop, a while loop, or a do..while loop), and the condition of an if, are both boolean contexts and thus work in exactly the same way. Both of your assertions are wrong, in that the compiler never checks for either i < num or x < num in your example, that is not how && works. In ...
74,485,536
74,485,588
std::function error conversion from ‘x' to non-scalar type ‘y’ requested?
I have the following code to demonstrate a function been called inside another function. The below code works correctly: #include <iostream> #include <functional> int thirds(int a) { return a + 1; } template <typename T, typename B , typename L> //------------------------------------------------VVVVV- int hello(...
std::vector<uint8_t> thirds(Number &N) : Argument type is Number&. Therefore, you need '&' : std::function<std::vector<uint8_t>(Number&)> myfunc = &thirds;
74,485,714
74,485,871
linked list not printing output
I have to dynamically allocate a list of robots for a school project. In an actual program, there will be other member functions that will require the list of names in order to perform certain functions. As of right now, I just learned about this concept, and have tried really hard to put together some things I have se...
Your display function is fine. The problem is that you have 2 logic flaws in addNode(): you are not storing strings in your list correctly. You are assigning botName to newNode->name_ before botName has been assigned a value. So all of your nodes have empty strings. Assigning botName afterwards will not update newNod...
74,486,364
74,486,622
Why capacity of std::string is 15. Why my reserve() is ignored?
#include <iostream> #include <string> using namespace std; int main() { string s; s.reserve(5); cout << s.capacity() << endl; } The reserve is a std::string's function that sets the capacity. The capacity function shows the space size of c_string in the std::string. But, the result is not 5, but 15. I do...
Note that also int main() { std::string s; std::cout << s.capacity() << "\n"; s.reserve(5); std::cout << s.capacity() << "\n"; } Would print 15 twice. Consider the output of this #include <iostream> #include <string> int main() { std::string s; std::cout << s.capacity() << "\n"; std::cout ...
74,486,584
74,486,753
Is using std::numeric_limits<T>::quiet_NaN() a bad practice?
Have the following function that searches a query for a match and returns NaN if no match was found: int64_t Foo::search(const std::string& foo, int64_t t0, ... if { ... } else return std::numeric_limits<int64_t>::quiet_NaN(); }
std::numeric_limits<T>::quiet_NaN(); is only meaningful if T is a floating point type for which std::numeric_limits<T>::has_quiet_NaN(); is true. So, no, your code is not good practise. Reference: https://en.cppreference.com/w/cpp/types/numeric_limits/quiet_NaN
74,486,919
74,497,389
Is it legal to use std::declval in lambda in unevaluated contexts?
Code as below or on godbolt compiles with gcc and MSVC but fails with clang. I couldn't find if/where it is forbidden in the standard. In my opinion it should be supported. So who is correct on this, clang or gcc/MSVC? #include <type_traits> void foo() { static_assert(decltype([_=std::declval<int>()]() consteval n...
I am not completely sure how this is intended to work, but here is my attempt at a solution: According to [intro.execution]/3.3 the initializer of an init-capture is an immediate subexpression of a lambda expression. However none of the listed items make the expressions in the lambda's body subexpressions. Unevaluated ...
74,487,257
74,510,835
Python/C++ Extension, Undefined symbol error when linking a library
I made a project that has glfw as a library, my directory looks like this: main_dir |--include |--|--glfw_binder.h |--src |--|--glfw_binder.cpp |--lib |--|--glfw |--|--|--src |--|--|--|--libglfw.so |--|--|--|--libglfw.so.3 |--|--|--|--libglfw.so.3.3 |--|--|--|--... |--|--|--include |--|--|-- ... |--main.cpp |--setup.py...
For anyone facing a similar issue, you need to specify runtime_library_dirs so the setup.py file looks like this: from setuptools import setup, Extension, find_packages module1 = Extension('nerveblox', sources = ['main.cpp', 'src/nerveblox_VM.cpp'], include_dirs=["include", "lib/glfw/include"], #...
74,487,512
74,488,174
Is memory leak possible, when I directly change the char array in std::string by accessing the address of it?
#include <iostream> #include <string> using namespace std; int main() { string s; char* c = &s[0]; c[0] = '4'; c[1] = '3'; c[2] = '\0'; cout << s.data(); } You can access the char array inside a string like this. But, I think that it is undefined behavior. This behavior make that many f...
Yes, you're right that it is Undefined Behavior. With Undefined Behavior, anything can happen. That does include "memory leak", which can occur in isolation or in combination with any other symptom. Of course, "memory leak" isn't that important when the other problems happening are "crash" or "computer on fire". So jus...
74,487,559
74,487,666
(C++) Calculating [(1! / 1^1) + (2! / 2^2) + ... + (20! / 20^20)] with using subfunctions of factorial and power
#include <iostream> using namespace std; int power(int a, int b); // Subfunction to calculate a^b int fact(int c); // Subfunction to calculate factorial int main() { int x=0; for(int i=1 ; i<=20 ; i++) x+= fact(i) / power (i,i); // needs to calculate like [(1! / 1^1) + (2! / 2^2) + (3! / 3...
You have some serious problems with your types: int power(...); int fact(...); => this should be long long. In top of this, you are doing integer division, while you need floating point division: fact(i) / power (i,i); ... should be: ((double) fact(i)) / power (i,i);
74,487,601
74,487,704
LINKED LIST: Why do I need to "return;" in the if statement...even if i'm passing head by reference in the function(to add node at end)
#include<iostream> using namespace std; class node{ public: int data; node* addr;.//it's address of the next node node(int val){ data=val; addr = NULL; } }; void addVal(node* &head, int val){ node *n=new node(val); if (head==NULL){ head = n; return;///<-WHY...
If you do not return this is what happens: node *p=head; // p equals head which equals n while(p->addr!=NULL){ // p->addr is NULL, this loop stops immediately p=p->addr; } p->addr=n; // this assignes n to p's next ptr return; The use of many diffe...
74,487,769
74,488,262
Initialize custom collection with list of values
I have created a class that should act as a collection (with some custom behavior of mine). Inside, the class contains an array, to store the values. class MyCollection { private: int m_array[N]; public: int operator [] (int idx) const { return m_array[idx]; } int operator [] (T...
The std::initializer_list will be your friend. We can add it in a constructor, but also in an assignment operator, or any other member function. Please read about it here. Code could look like: #include <iostream> #include <initializer_list> class MyCollection { private: int m_array[10]{}; public: MyCollection...
74,489,031
74,489,078
Why don't define some undefined behaviours?
What are the reasons for C++ to not define some behavior (something like better error checking)? Why don't throw some error and stop? Some pseudocodes for example: if (p == NULL && op == deref){ return "Invalid operation" } For Integer Overflows: if(size > capacity){ return "Overflow" } I know these are very...
Because the compiler would have to add these instructions every time you use a pointer. A C++ program uses a lot of pointers. So there would be a lot of these instructions for the computer to run. The C++ philosophy is that you should not pay for features you don't need. If you want a null pointer check, you can write ...
74,489,355
74,489,909
Function was put into a curly bracket in order to initialize the member in class. What is its syntax?
The code is shown here: class Basket{ public: /*other contents*/ private: // function to compare shared_ptrs needed by the multiset member static bool compare(const std::shared_ptr<Quote> &lhs, const std::shared_ptr<Quote> &rhs) { return lhs->isbn() < rhs->isbn(); } // multiset to hold multiple ...
items{compare}; is a call to one of the overloads of the constructor of std::mulitset. Which one of the overloads to use is decided by the compiler from looking at your argument type: compare matches the description of a "comparison function object" (see link), so the second invocation is used. It is a pointer to a fun...
74,489,412
74,528,835
OpenCV 4.5.3, C++, OpenCL "Transparent API", UMat instead Mat, no improvements
my C++ code is running on Win 10, self built OpenCV 4.5.3., WITH_OPENCL flag checked. Using UMat instead of Mat does not result in any performance improvements through "Transparent API" of OpenCL. From what I have read on https://jeanvitor.com/opencv-opencl-umat-performance/ i expected at least a slight performance imp...
found out that the issue was caused by the Microsoft Unit Testing Framework for C++. in my production code using UMat is way faster than Mat. question answered
74,489,766
74,490,057
How to use an abstract class rvalue reference member?
I have an abstract class Base and derived class Derived: class Base { public: Base(int n) :_n(n) { _arr = new int[n]; } virtual ~Base() { delete[] _arr; } Base(Base&& other) { _n = other._n; _arr = other._arr; other._arr = nullptr; other._n = 0; } virtual void func() = 0; private: int _n; int* ...
Base&& _b is a reference to the temporary object, when that temporary is destroyed at the end of the line Bag bag(Derived(1, 1)); the reference becomes a dangling reference and any use of the reference is undefined behaviour. You could change _b to a value instead but that would slice your object. If you want to store ...
74,489,862
74,513,942
WinUI3 : Understanding WinUI3 desktop app
As we can create a WinUI3 app in both the desktop app(win32 app) and the UWP app. What exactly does it mean to create a WinUI3 in a desktop app? As I understand, this app will follow the Win32 App model, that is, the app will not run on sandbox and the app will not have activation and lifecycle management like UWP apps...
I found that you have posted the same case on the Q&A forum: https://learn.microsoft.com/en-us/answers/questions/1095079/winui3-understanding-winui3-desktop-app.html You could refer to the answer provided by Castorix 31. To prevent the link from expiring, I will post the answer to Castorix 31: Application::Start repla...
74,490,868
74,491,142
CMakeLists includeT Qt5::QML does not work
This is my CMakelists.txt file. cmake_minimum_required(VERSION 3.0.2) project(osm_map) find_package(catkin REQUIRED COMPONENTS rviz) find_package(Qt5 COMPONENTS Widgets REQUIRED) set(QT_LIBRARIES Qt5::Widgets Qt5::Qml) set(CMAKE_AUTOMOC ON) set(CMAKE_AUTORCC ON) set(CMAKE_AUTOUIC ON) set(SRC_FILES src/core.cpp ) ...
The problem is in your find_package(Qt5 COMPONENTS Widgets REQUIRED) here you asked CMake that you wanted the Widgets component of Qt5 but then you tell it to link with Qml which you did not ask for. You should change this to the following: find_package(Qt5 COMPONENTS Widgets Qml REQUIRED)
74,490,925
74,491,133
Accessing a pointer to a derived class when it is not created
Why referring to a pointer to a derived class that has not yet been created is valid, but not undefined behavior. godbolt.org #include <iostream> struct A{ int a; void foo() { std::cout << "A = " << a << std::endl; } }; struct B : public A{ int b; void foo() { std::cout << "B = ...
Compile with -O3 -Werror -Wall to get the following message from gcc: <source>: In function 'int main()': <source>:25:8: error: array subscript 'B[0]' is partly outside array bounds of 'unsigned char [4]' [-Werror=array-bounds] 25 | b->b = 333; | ~~~^ <source>:19:18: note: object of size 4 allocated by...
74,491,271
74,491,838
Double free in c++ destructor
I'm trying to implement a linked list in C++. The list contains a pointer to a node type allocated on the heap The code is as follow: #include <memory> template<typename T> class node { public: node(T v) : value(v) {} ~node() = default; T value; node *next; }; template<typename T, class Allocato...
This is a common newbie error. You modified your loop control variable. for (auto start = head; start != nullptr; start = start->next) { start->~node(); alloc.deallocate(start, 1); } You modified start (deleting the memory) in the for loop's body and then tried to dereference the pointer you just deleted in...
74,491,731
74,491,878
Constexpr evaluation and compiler optimization level
see the following snippet: struct config { int x; constexpr int multiply() const { return x*3; } }; constexpr config c = {.x = 1}; int main() { int x = c.multiply(); return x; } If I compile this with clang and -O0 I get a function call to multiply even though the object c and the funct...
The Standard just requires that a call to constexpr is evaluated at compile time if the arguments are constexpr and the result must be constexpr due to context. Basically just forcing more restrictions on the author of the function, thus allowing it to be used in constexpr contexts. Meaning y in second snippet forces e...
74,492,635
74,493,368
Is there a sugar syntax for usings in CPP? Like using std::{name1, name2, ..., nameN}?
Let's say I want to use #include <iostream> using std::cout; using std::cin; using std::endl; But I don't want to use using namespace std; Is there something like this: using std::{cout, cin, endl}; I've tried using std::{cout, cin, endl}; Instead I got a syntax error.
As of c++17, you can add multiple objects in using separated by a comma. using std::vector, std::cout, std::cin; Previously it required a separate using statement for each. See the using declaration . You do have to include the full path for each declaration.
74,493,270
74,493,331
What is the use of a private init() member function?
EDIT for more details: this is a school assignment and the private variables/functions of the Time class were given to me already. I have to declare and define a member function which adds two Times together and saves the result in the Time member variable of another class. I'm not sure what the assignment intends me t...
This is an old C++ style. It allows multiple constructors to share code. Modern C++ would use Time::Time() : Time(0,0,0) { } which reuses the existing 3-argument ctor.
74,494,340
74,494,929
Delete duplicated in a linked list solution from C++ to rust
I have this code solution written in c++ for the problem remove-duplicates-from-sorted-list and just now I'm learning rust and I want to build the same solution in rust programming language my rust linkedList doesn't have ListNode have Option<Box<Node>> class Solution { public: ListNode* deleteDuplicates(ListNode*...
impl Solution { pub fn delete_duplicates(mut head: Option<Box<ListNode>>) -> Option<Box<ListNode>> { by matching instead of just checking for .is_none() we can get the value inside & check for None at the same time. // if (!head) return head; // ListNode* current = head; let mut current = m...
74,494,375
74,525,478
Inverting a sparse matrix using eigen
I'm trying to use a sparse solver as SimplicialLLT to inverse a symmetric positive-definite matrix and return it. I get a matrix from R using Rcpp to connect R and cpp, I take this matrix as an argument of the function cpp_sparse_solver, use sparseView() to turn it to SparseMatrix, declare the solver, compute and solve...
There were a number of things wrong in your code, and a few other stylistic things I would do differently. Below is version which actually compiles and it differs in having reduced the number of headers to the single one you need removed the namespace flattening statements which mostly cause trouble updated some type...
74,494,530
74,495,745
How to copy a vector of A to a vector of A pointer using std algorithms?
I've got a std::vector<Edge> edges and I'd like to copy some items from this array into a std::vector<Edge*> outputs using std library. I know std::copy_if can be used to copy a vector of pointers to a vector of pointers: std::vector<Edge*> edges; //setup edges std::vector<Edge*> outputs; std::copy_if(edges.cbegin(),...
You can use Eric Niebler's range-v3 library: get the input vector, filter out some of its elements, transform the remainder into pointers to them, and convert that view to a vector of pointers. [Demo] #include <iostream> #include <range/v3/all.hpp> #include <vector> struct Edge { int value; }; int main() { ...
74,494,649
74,494,970
Coin change problem in C++ stuck on recursion
I have to write a recursiive solution to the coin change problem in C++. The problem provides a set of coins of different values and a value representing a sum to be paid. The problem asks to provide the number of ways in which the sum can be paid given the coinages at hand. I am stuck on this: #include <iostream> #inc...
If amount is 0, this is an answer, return 1 to be added to ways. If you got below 0, dead end street, return 0, nothing will be added. if (amount == 0) return 1; if (amount < 0) return 0;
74,494,716
74,496,144
Std::vector vs. placement new for communicating const array with size known at run-time
I have two methods for creating a list of objects at run-time which have potential downsides that I'd like to consider. Ultimately I am wondering which one more e The criteria of my problem: One major object will contain a fixed collection of minor objects (technically representing a 2d array) Desire not to implement ...
Based on Quentin's comment above an example implementation of a wrapper class could be done with the following template class. This allows for run-time initialization benefits of std::vector while allowing/disallowing other operations as needed. Access to the objects it contains would be the same via the subscript oper...
74,494,936
74,495,466
Threadsafe copy constructor
I am trying to make the copy constructor of a class thread safe like this: class Base { public: Base ( Base const & other ) { std::lock_guard<std::mutex> lock ( other.m_Mutex ); ... } protected: std::mutex m_Mutex; } class Derived : public Base { public: ...
The advice of @AnthonyWilliams is to lock the constructor as an argument of a delegated constructor, see here for the full article: class A { private: A(const A &a, const std::lock_guard<std::mutex> &) : i(a.i), i_squared(a.i_squared) {} public: A(const A &a) : A(a, std::lock_guard<std::mutex>(a.mtx)) {} ... }...
74,495,037
74,495,188
Does std::unordered_map::erase actually perform dynamic deallocation?
It isn't difficult to find information on the big-O time behavior of stl container operations. However, we operate in a hard real-time environment, and I'm having a lot more trouble finding information on their heap memory usage behavior. In particular I had a developer come to me asking about std::unordered_map. We're...
The standard doesn't specify container allocation patterns per-se. These are effectively derived from iterator/reference invalidation rules. For example, vector::insert only invalidates all references if the number of elements inserted causes the size of the container to exceed its capacity. Which means reallocation ha...
74,495,058
74,495,078
Do WinInet or WinHTTP support custom ports? If so, how do I implement it?
I am trying to download a file using both HTTP and HTTPS (in different scenarios) from a service which defaults to using ports 5080 and 5443, respectively. I wanted to use WinInet (or WinHTTP) as they're native to Windows, but it appears that both WinInet and WinHTTP only support using port 80 or port 443, and do not s...
WinInet's InternetConnect() and WinHTTP's WinHttpConnect() both let you specify any port number you want in their respective nServerPort parameters. You don't have to use the pre-defined constants like INTERNET_DEFAULT_HTTP(S)_PORT.
74,496,335
74,497,162
GLSL uint_fast64_t type
how can i get an input to the vertex shader of type uint_fast64_t? there is not such type available in the language how can i pass it differently? my code is this: #version 330 core #define CHUNK_SIZE 16 #define BLOCK_SIZE_X 0.1 #define BLOCK_SIZE_Y 0.1 #define BLOCK_SIZE_Z 0.1 // input vertex and UV coordinates, di...
Unextended GLSL for OpenGL does not have the ability to directly use 64-bit integer values. And even the fairly widely supported ARB extension that allows for the use of 64-bit integers within shaders doesn't actually allow you to use them as vertex shader attributes. That requires an NVIDIA extension supported only by...
74,496,338
74,496,474
Can't draw simple bitmap to window in SDL2
I'm currently trying to set up a few C++ libraries for a future project. Namely, SDL2. Here's my code: #include <iostream> #include <fstream> #include <SDL.h> int SCREEN_WIDTH = 457; int SCREEN_HEIGHT = 497; const char* imgpath = "Sprite.bmp"; std::string errmsg; SDL_Window* window = NULL; SDL_Surface* screensurfac...
The problem is that you are trying to get the window surface, but the window isn't already created. Please swap those two lines: screensurface = SDL_GetWindowSurface(window); window = SDL_CreateWindow("Transcend", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); This wa...
74,496,713
74,520,929
How to get the type of the values in a C++20 std::ranges range?
Given a std::ranges::range in C++20, how can I determine the type of the values in that range? I want to write a function that makes a std::vector out of an arbitrary range. I'd like this function to have a nice, explicit declaration. Something like: template<std::ranges::range Range> std::vector<std::value_type_t<Rang...
Let's go through this in order: template<std::ranges::range Range> auto make_vector(Range const& range) This is checking if Range is a range, but range isn't a Range, it's a const Range. It's possible that R is a range but R const is not, so you're not actually constraining this function properly. The correct constrai...
74,497,118
74,497,239
My stack is not displaying my array but queue display it
My Queue is displaying right but my stack is displaying nothing. Im using array to transfer it to stack and to queue but when i transfer the array to stacks and display it, it show nothing. and is there a way to reverse my Queue and save it to my array again? case 1 is where the input of stack and queue comes, void dis...
You need to construct your Stack outside the do-while loop. As it stands right now, a new Stack is created at each iteration while the previous goes out of scope. In doing so, you are creating your Stack in the input phase, only for it to get erased at end of the iteration! Just modify the beginning of your main() func...
74,497,274
74,497,319
How to output Classes and Objects
#include <iostream> using namespace std; class PrintName{ public: void studentName(){ cout<<"Name : "<<studentName<<endl; } }; class MathClass{ public: void multiplicationFunc(int x, int y){ cout<<"Result : "<<(x*y)<<endl; } }; int main() { cout<<endl; PrintName PN;...
It seems like there is no error on line 15. Instead, you did not define the variable studentName in your void studentName() function in line 8. Also, you used 2 arguments for studentName() in line 23, where the original function is not taking any. This is the corrected code: #include <iostream> using namespace std; c...
74,497,661
74,497,745
How can I loop through variables by their names?
Suppose I have N float variables x0, x1, x2, ..., xn. I basically want to loop through each of them and sum them all in a final variable sum. I'm in a context where I cannot make use of data structures like arrays, vectors, etc. If it helps, in my context N is always less than 10. Is it possible to make a for loop to d...
not sure whether it fits your needs, but you can try something like: #define SUM_X0 (x0) #define SUM_X1 (SUM_X0 + x1) #define SUM_X2 (SUM_X1 + x2) #define SUM_X3 (SUM_X2 + x3) #define SUM_X4 (SUM_X3 + x4) #define SUM_X5 (SUM_X4 + x5) #define SUM_X6 (SUM_X5 + x6) #define SUM_X7 (SUM_X6 + x7) #define SUM_X8 (SUM_X7 + x8)...
74,498,419
74,499,236
std::bind with std::shared_ptr works on gcc/clang, but not on msvc
The following code can be compiled with g++ 8.1.0 and clang 10.0.0. #include <memory> #include <iostream> #include <functional> int main() { auto dereference = std::bind( &std::shared_ptr<int>::operator*, std::placeholders::_1); std::shared_ptr<int> sp = std::make_shared<int>(10); std::cou...
Behavior is unspecified when trying to take the address of a member function of a standard library class. This allows the standard library to choose a different number or different declarations for the overloads of the member function, as long as direct calls still behave as specified by the standard. For example if th...
74,498,492
74,499,587
How to efficiently store matmul results into another matrix in Eigen
I would like to store multiple matmul results as row vector into another matrix, but my current code seems to take a lot of memory space. Here is my pseudo code: for (int i = 0; i < C_row; ++i) { C.row(i) = (A.transpose() * B).reshaped(1, C_col); } In this case, C is actually a Map of pre-allocated array declared as...
The reshaped is the culprit. It cannot be folded into the matrix multiplication so it results in a temporary allocation for the multiplication. Ideally you would need to put it onto the left of the assignment: C.row(i).reshaped(A.cols(), B.cols()).noalias() = A.transpose() * B; However, that does not compile. Reshaped...
74,498,531
74,499,221
C++ - Closure template class behaves strangely when multihreading depending on closure types
I am trying to write my own c++ wrapper class for linux using pthreads. The class 'Thread' is supposed to get a generic lambda to run in a different thread and abstract away the required pthread calls for that. This works fine if the lambdas don't capture anything, however as soon as they capture some shared variables ...
You've got undefined behaviour, since the lambda objects are actually destroyed immediately after the constructor of Thread completes. To see this, instead of a lambda you could pass an object that prints a message in the destructor: struct ThreadFunctor { int& stackInt; int* heapInt; ThreadFunctor(int& si...
74,498,709
74,499,224
C++\C | Link | Queue | Hyperlink
when i choose at Queue insert value ( example 1 ), then i call remove_Queue, and then i try to print_Queue, but in terminal i see value -572662307 code: const int MAX_QUEUE = 10; typedef int Item; struct Queue { Item value; Queue* next; }; Queue* front; Queue* back; Queue* tmp; bool remove_Queue(Item& i,...
You have global variables (that's bad), and you have local variables named the same as your global variables (that's worse) and you are expecting changes to local variables to be reflected outside of the local scope (that's plain wrong). It's not completely clear what you are trying to do. I'm going to go down the glob...
74,498,900
74,498,923
Why does the data still exist after I delete the space of the array?
Today, I found a small problem when creating dynamic arrays. I use the resize () function to change the size of the array. In the resize () function, I created a temporary array "newData", and then I assigned it the new size I wanted. After assigning the value of the initial array "Data" to it, I set Data=newData; At ...
You (try to¹) access deleted space; that's what is called undefined behaviour in C++: Anything might happen. There might be the original values, the might be some other data you worked on put there, there might be the value 0xdeadcafe all over the place, your program might crash or cause a fire, delete all files or giv...
74,499,887
74,499,974
Why doesn't this code for a binary search function in c++ work?
#include <iostream> int binary_search(int arr[], int size, int target) { int first = 0; int last = size - 1; int midpoint = (last + first) / 2; while(first <= last) { if(arr[midpoint] == target) { return midpoint; } else if(arr[midpoint] < target) ...
You basically forgot to update midpoint in each iteration. An updated version of your code here (not using those "C" style arrays).It was also not clear if you meant to return the found value or the index at which it was found. #include <iostream> #include <vector> auto binary_search(const std::vector<int>& values, in...
74,500,509
74,500,510
"Failed to setup resampler" when starting QAudioSink
I'm porting some QtMultimedia code from Qt 5.15 to 6.4.1. The following program, when built with Qt 6.4.1 on Windows: int main (int argc, char *argv[]) { QCoreApplication a(argc, argv); QAudioDevice device = QMediaDevices::defaultAudioOutput(); QAudioFormat format = device.preferredFormat(); QAudioSin...
Apparently, it's a bug in Qt 6.4.1 on Windows, where, as the user johnco3 discovered in that forum post, for some reason QAudioSink is looking for a DLL named "mfplat.dll.dll" when it should be looking for "mfplat.dll" (it adds an extra ".dll" suffix). The correctly named version of this DLL lives in the Windows system...
74,500,555
74,500,602
I found this question, but I can't code it. [TODO list]
Aman has made a To-Do list: a list of all the pending tasks that he has to complete. The list is in the increasing order of time taken to finish the tasks. Aman begins from the starting of the list. Given an array of size N denoting the list of the pending tasks. Each task is an integer between 1 and N. The tasks numb...
Something like this, loop though the tasks counting the priority ones. When the number of priority tasks reaches 7, stop the loop and print out the number of tasks seen so far. int tasks = 0, pri_tasks = 0; for (; tasks < n && pri_tasks < 7; tasks++) { if (arr[tasks] <= 7) ++pri_tasks; } if (pri_tasks == 7)...
74,500,928
74,501,076
How to count string and sort them?
I am reading from an input file and want to read all letters and symbols. I am looking to create something bigger from this like encode it eventually - but I cannot seem to move from this block of trying to read in characters and use its frequency in a vector which I would sport in a heap. For context, how can I get so...
The most straightforward way would be to first create a std::map for the frequencies (similar to your dictionary map, but you need to use a std::(unordered)_map<char, int> instead of <int,char>). Then you can use a std::multimap where you insert the all reverse pairs. #include <iostream> #include <map> #include <string...
74,501,189
74,501,542
trouble understanding list.begin() | list.end() | list<int>::iterator i
void Graph::max_path(){ for(int i=0; i <N; i++){ cost[i]=0; cam_max[i]=999; } // Percorre todos os vertices adjacentes do vertice int max = 0; list<int>::iterator i; for (int a = 0; a < N ; a++){ int v = ordely[a]; for (i = adj[v].begin(); i != adj[v].end(); ++i){ ...
begin and end are iterators (specfically, pointers), which are used to iterate over a container. You could imagine begin as 0 and end as the size of an array. So it is like for (i = 0; i < size; ++i). However, the thing about pointers is that they're addresses, so in C++, i < end (where i started as begin) is more like...
74,501,884
74,502,008
LibTorch (PyTorch C++) LNK2001 errors
I was following the tutorial in LibTorch here. With the following changes: example-app => Ceres example-app.cpp => main.cxx Everything worked until the CMake command cmake --build . --config Release. It produced the following errors: main.obj : error LNK2001: unresolved external symbol __imp___tls_index_?init@?1??laz...
Look to: Updating to Visual Studio 17.4.0 Yields linker errors related to TLS You most likely need to rebuild PyTorch after MSVC update.
74,502,062
74,503,892
Unabled to load lohmann/json.hpp using CMake - getting fatal error: 'nlohmann/json.hpp' file not found
I have the following main.cpp, very simple script, trying to re-produce the problem and isolate to it's most basic. #include<iostream> #include<fmt/core.h> // #include "json/json.hpp" // #include <json/json.hpp> // #include <nlohmann/json.hpp> // #include "json.hpp" // #include "nlohmann/json.hpp" int main(){ fm...
You can either specifically use the interface target already included in the nlohmann library, which will automatically populate the correct include path for you, with: target_link_libraries(main nlohmann_json::nlohmann_json) Or you would need to specifically include the include path yourself: include_directories(${js...
74,502,063
74,515,844
yaml-cpp doesn't roundtrip with local tags
When I YAML::Load a node with a local tag, the tag type and tag contents are not preserved. Minimal example I am using the 0.7.0 conan package. auto x = YAML::Node(42); YAML::Emitter e; e << YAML::LocalTag("x") << x; std::string s = e.c_str(); auto y = YAML::Load(s); std::cout << "before: " << s << std::endl; std::co...
Your problem is this code: void EmitFromEvents::EmitProps(const std::string& tag, anchor_t anchor) { if (!tag.empty() && tag != "?" && tag != "!") m_emitter << VerbatimTag(tag); if (anchor) m_emitter << Anchor(ToString(anchor)); } The primary problem is that the default emitter always produces verbatim tag...
74,502,473
74,504,400
How can I make a function use the child object associated function instead of the parent one?
I'm coding a simple physics engine with a few others for a school assignment. In order to be as generic, we made a Particle class, then an Object class which inherits it (and is basically a particle with a force vector), and finally a Disc class which is a child class of Object. In my class PyhsicsWorld, I want to use ...
If you really need to call for Disc, just cast it. I further assume that you need general solution for multiple shapes, like Disc, Cube, Sphere etc. So I prepared example for you, that is based on virtual functions and shows how can you choose correct function for Disc and Cube. class Disc; class Cube; bool intersectD...
74,502,731
74,502,812
Disabling a constructor using std::enable_if
My aim is to create my own analogue of std::basic_string but with some additional conditions. I want my AnyString<CharType, Traits> to be convertible from std::basic_string<CharType, AnyOtherTraits, AnyAlloc> but I want to disable this constructor for some CharType such that basic_string<CharType> does not exist (compi...
Basic example for constructor restriction using concepts (not your traits) #include <type_traits> #include <string> // declare your own concept template<typename type_t> concept my_concept = std::is_convertible_v<type_t, std::string>; // just a demo concept class ColouredString { public: // then you can limit...
74,503,028
74,640,899
Compiling out strings used in print statements in multi-level log - C++
I'm looking for a way to compile print strings out of my binary if a specific macro-based condition is met. here, _dLvl can be conditionally set equal or lower than the maximum allowed level. enum DEBUG_LEVELS : int { DEBUG_NONE, DEBUG_ERRORS, DEBUG_WARN, DEBUG_INFO, DEBUG_VERBOSE }; #define MAX_L...
Here's a complete answer, it's based on Nikos Athanasiou's answer (Thanks Nikos). What's added is a templated class per DEBUG_LEVELS enum, which defines the MAX_LEVEL, which would be used in constexpr if statement at compile time, to compile out unused strings. #include <utility> #include <cstdio> enum DEBUG_LEVELS : ...
74,503,659
74,503,748
How to calculate the total distance between various vertices in a graph?
Let's say I have a weighted, undirected, acyclic graph with no negative value weights, comprised of n vertices and n-1 edges. If I want to calculate the total distance between every single one of them (using edge weight) and then add it up, which algorithm should I use? If for example a graph has 4 vertices, connected ...
Since you have an acyclic graph, there is only one possible path between any two points. This makes things a lot simpler to compute and you don't need to use any real pathfinding algorithms. Let's say we have an edge E that connects nodes A and B. Calculate how many nodes can be reached from node A, not using edge E ...
74,503,960
74,508,747
Why don't I need to use the -MT option for dependency generation when I save my object files to a separate directory?
I have a (GNU)Makefile that gives the .o files a name that puts them in a separate directory. If I'm reading the GCC documentation on preprocessor options correctly, then all directory components and the file extension of the source file are stripped, .o is appended, and that's the name of the target. However, it seems...
This question doesn't have anything to do with make or makefiles. It's purely about how the GCC compiler's dependency generation works. I agree with you that the behavior generated doesn't seem to match the documentation, unless we're misinterpreting what it says. Here's a test case, that doesn't need all the complex...
74,504,231
74,504,285
Follow pattern until negative then reverse using recursion
Trying to write a program that follows a simple pattern (x-y, x+y) as practice with recursion. Essentially taking a number, subtracting the second until reaching a negative value, then adding until reaching the original value. I understand my base case is reaching the original value, and my recursive case to subtract u...
Just print the value twice for each recursive call. You can't really know what the original value was, unless you pass it into the function: void PrintNumPattern(int x, int y){ std::cout << x << " "; // Print "x" first if ( x >= 0 ) { // If x is positive (or zero?) keep recursing ...
74,504,975
74,505,986
c++ saving and reading a struct with a vector struct in it
I'm new to C++ so I'm not fully used to the syntax yet. I do know more than the basics of C# syntax tho, which I have been using for the better part of a year now, and I have 2 years of PHP and python to go with that. I'm tryng to write a struct with a vector inside of it to a file, and read it back at a different mome...
A std::vector<> contains a length and a pointer to heap memory. You cannot save a vector like this: vector<int> v = {1, 2, 3}; // the following line will save the length and the address of the array // containing the data. NOT the data itself. fileW.write((char *) &v, sizeof(v)); //... std::vector<int> u; // the...
74,505,069
74,506,674
How do I change the odd numbers to even in an array? C++
For this assignment, I have to write a program that removes the odd numbers from an array and replaces them with even numbers. The array must have 10 elements and be initialized with the following numbers: 42, 9, 23, 101, 99, 22, 13, 5, 77, 28. These are the requirements: Must use the values provided in my array. Prin...
You mentioned that you are somehow new to programming. So, we need to adapt our answer to that fact. You will not yet know all the existing functions in the standard library. So, let us come up with a very easy solution. Obviously we need to frist print the original unmodified date from the array. So, we will output th...
74,505,228
74,505,244
I get the error "fatal error: Tablero.h: No such file or directory" when trying to compile C++
I'm learning C++ and trying to create a class but when I try to compile my codeit gives me this error. As you can see, the file "Tablero.h" is in the same folder as the main.cpp file. Is there any other step that i should take for g++ to find the file "Tablero.h"? Here you can see the error and the file being in the fo...
Try using #include "Tablero.h". Using <> checks headers in the standard library, but quotes "" look for headers in the local directory.
74,505,355
74,505,471
How can I make quick expression that's visible to assign to const?
I want to assign some value to a const, where it used to be something like const int x = animal == "cat" ? 0 : 1; But now, I want to make it so that if animal == cat, assign 0, and if dog returns 1, else 2 to the const. Well, in reality, it's not that simple but say something like use equation a, in this case, equatio...
With the help of a lambda function, there is no need to specify the definition of another function somewhere in the code. const string animal = "dog"; const int x = [animal]() { if (animal == "cat") return 0; else if (animal == "dog") return 1; else return 2; }(); cout << x << endl...
74,505,475
74,505,614
c++ object lifetime extension rules with member initializers
In this talk, the author mentions lifetime extension rules extend to member initializers based on the standard. I see the opposite though, i.e. ~Y is called before "Hello" is printed below. Is the author referring to something else? #include <iostream> using namespace std; struct Y { ~Y() { cout << __PRETTY_...
It applies only in the case of aggregate initialization, because otherwise there is a constructor call and the prvalue would be bound to the reference parameter of that constructor, not directly to the reference member. Also, it does not apply to aggregate initialization with parentheses instead of braces in C++20 and ...
74,505,859
74,506,401
how I make that two variables points at the same spot in C++?
I'm working with an array of objects where some of them should have the literal same parameter, so when it changes it also changes in all of them. I tried using pointers, so that every parameter points at the same memory, but I really don't really know how to do it. In my code something is happening because it compiles...
To dereference a ponter, you use * before the pointer. void Set_elemento(Nodo* nodo_i, Nodo* nodo_j, Seccion* seccion_) { nodoi = *nodo_i; nodoj = *nodo_j; seccion = *seccion_; } It gets the objects at the pointers' addresses and sets your member variables to them. Though I think your entire method of achi...
74,506,123
74,506,203
How ceil function works in c++?
When I execute this code the value of ans1, ans2 is 50002896 and 50005000. I know there is some issues with ceil function but was not able to figure out the exact cause. #include <bits/stdc++.h> using namespace std; int main() { long long ans1 = 0, ans2 = 0; for (long long i = 1; i <= 10000; i++) { ...
The source of the problem is not the ceil function, but rather that not all integers can be represented accuratly as floating point values. Some more info about floating point representation: Wikipedia IEEE 754. The following code is a minimal demonstration of the same issue that causes your issue: float f1 = 100000000...
74,506,702
74,506,771
why is the iterator showing address instead of value in the loop?
` vector<int> nums; nums.push_back(1); nums.push_back(2); nums.push_back(3); vector<int> res; res.push_back(nums.front()); vector<int>::iterator it = nums.begin(); vector<int>::iterator it2 = res.begin(); ++it; cout << "it2 -> " << *it2 << endl; cout << "it + it2 " << *it + *it2 << endl; while(it != nums.end()) { ...
Those aren't addresses, they are garbage integers. Your code is suffering from iterator invalidation. When you add an item to a vector you potentially invalidate any iterator that is pointing to it. This happens because adding an element to a vector may cause the vector to reallocate the memory it uses to hold it's ele...