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 |
|---|---|---|---|---|
72,105,863 | 72,107,089 | filesystems "remove_all" vulnerability is not defined error | Hello i started c++ and im using Visual Studio 2017 and i want deletin all files/folder inside a folder and i tried this code:
#include <iostream>
#include <filesystem>
using namespace std;
int main()
{
remove_all("C:\myfolder");
printf("All items deleted!");
return 0;
}
remove(); is works for me but re... | I modified the snippet: added filesystem:: and \\
#include <iostream>
#include <filesystem>
using namespace std;
int main()
{
filesystem::remove_all("XX:\\XX\\TestFolder");
printf("All items deleted!");
return 0;
}
And use the C++ 17 in Project's properties.(Right click the project and you will see the... |
72,106,025 | 72,106,233 | Linker error on Timer based on Singleton pattern | Trying to write Singleton for the first time. This is a timer that works with one function to handle timer's both start and stop and also printing result.
When compiling, I'm getting linker errors like this one:
:-1: ошибка: CMakeFiles/some_algorithms.dir/timer_singleton.cpp.obj:timer_singleton.cpp:(.rdata$.refptr._ZN1... | The problem: Most non-constant static members need to be defined outside of the class definition in order to get the one-and-only-one instance that will be shared by all class instances. Normally this means that in timer_singleton.cpp you would have to add
timer_singleton::counter = 0; // allocate and initialize
But..... |
72,106,369 | 72,106,465 | Using queue Between two object of class | In order to send messages between two objects of class!
I implemeted this
class User
{
public:
virtual void run()
{
while (true)
{
string receivedMessage = receiveMessage();
sendMessage(receivedMessage);
}
}
virtual void sendMessage(stri... | You have a global send queue and a global receive queue. What you need is a receive queue per player.
Have a send method on the player class that writes to their send queue
So player 1 would go
player2.Send("hello player2");
How to do it
class Player
{
BlockingQueue<string> queue_ = BlockingQueue<string>();
pu... |
72,106,607 | 72,106,698 | c++ How do I fix my no instance error on my setMaterial piece of code | I just started coding with C++, and am doing a few tutorials on using C++, but when I finished up one part of code I saw that it was erroring:
no instance of overload function "Unigine::ObjectMeshDynamic""setMaterial" matches the argument
Here is my code, and even though I did exactly as I was supposed to, maybe ther... | If you read Unigine's current (2.15.1) documentation for setMaterial() (which Unigine::ObjectMeshDynamic inherits from Unigine::Object), you will see that it is overloaded to accept only the following parameters:
void setMaterial ( const Ptr<Material> & mat, int surface )
void setMaterial ( const Ptr<Material> & mat, c... |
72,106,670 | 72,106,707 | cold weather meteorologists report index | I'm new in c++ and trying to calculate "W = 33 - ( 10√v −v + 10.5) * (33 - t) / 23.1", but i don't know how to use sqrt() !!
here is my code :
/* W=33−(10√v−v+10.5)(33−t)/23.1
Where 'V' is speed in (m/s)
Where 't' is temperature in degrees Celsius: t <= 10
Where 'W' is windchill index (in degrees Celsius)
*/
#include... | The square root character is not a valid math operator in C++. You will have to use the sqrt function:
10.0 * sqrt(V)
Note: the square root is a floating point function, so all your values and variables should be float or double.
|
72,107,749 | 72,107,951 | How can I save a string input with blank space in c++ (I am using if else statement) | So I am trying to make a text multiplier , here is the code
#include <iostream>
using namespace std;
int main()
{
bool m, n;
string x;
int y;
cout << "enter how many times you want to multiply the text : ";
cin >> y;
isdigit(y);
if (y)
{
cout << "enter the text you want to multip... | If I understand what you want to do, you need to read the integer value, clear the remaining '\n' that is left in stdin by operator>>, and then use getline() to read the text you want to multiply, e.g.
#include <iostream>
#include <limits>
using namespace std;
int main()
{
string x;
int y;
cout << "e... |
72,107,767 | 72,107,794 | the lua math.random equivalent for c ++? | is there a similar function in c ++ where I can bind variables to random numbers?
local xoffset, yoffset, zoffset = math.random(-1, 10), math.random(1, -10), math.random(1, 10)
| There is a full suite of random number generation algoriths in <random>. You can do something like this:
std::default_random_engine e1(r());
int xoffset = std::uniform_int_distribution<int>{-1, 10}(e1);
int yoffset = std::uniform_int_distribution<int>{-10, 1}(e1);
...
|
72,108,619 | 72,108,923 | Is my understanding of __ATOMIC_SEQ_CST correct? (I'd like to write a mutex with it + atomics) | For fun I'm writing my own threading library used by me and a friend or two. First thing I'd like to write is a mutex
It appears I'm generating the assembly I want. __atomic_fetch_add seems to generate lock xadd and __atomic_exchange seems to generate xchg (not cmpxchg). I use both with __ATOMIC_SEQ_CST (for now I'll s... |
If I am using __ATOMIC_SEQ_CST will gcc or clang understand these are synchronizing function?
Yes, that is the entire reason for these primitives to have memory ordering semantics.
The memory ordering semantics accomplish two things: (1) ensure that the compiler emits instructions that include the appropriate barrier... |
72,109,441 | 72,109,673 | Maximum subsequence sum such that no three are consecutive | Given a sequence of positive numbers, find the maximum sum that can be formed which has no three consecutive elements present.
Examples :
Input 1: arr[] = {1, 2, 3}
Output: 5
We can't take three of them, so answer is
2 + 3 = 5
Input 2: arr[] = {3000, 2000, 1000, 3, 10}
Output: 5013
3000 + 2000 + 3 + 10 = 5013
Input... | When k == nums.size() - 1, you have UB with out of bound access with c computation.
You have to handle the case, for example:
int findMax(std::vector<int>& nums, std::size_t k, std::vector<long long int>& dp)
{
if(k >= nums.size()) {
return 0;
}
if(dp[k] != -1)
return dp[k];
int a = fin... |
72,109,610 | 72,109,807 | Random word pick based on the number of times that they were used | I have a vector of strings like this one:
std::vector<string> words ={"word1", "word2", "word3", "word4"}; //and many more
The code randomise the vector ( in an auxiliary vector) and takes the first word from the auxiliary vector. To do this I use random_shuffle. So far, everything goes very well. But now, I would lik... | std::discrete_distribution might help, something like
std::random_device rd;
std::mt19937 gen(rd());
std::vector<std::string> words = {"word1", "word2", "word3", "word4"};
std::vector<std::size_t> weights = {10, 10, 10, 10};
for (int i = 0; i != 12; ++i) {
std::discrete_distribution<> d(weights.begin(), weights.e... |
72,109,724 | 72,109,800 | Why removing random element from vector and list costs almost the same time? | As cppreference says
Lists are sequence containers that allow constant time insert and erase operations anywhere within the sequence, and iteration in both directions.
Considering the continuous memory used by std::vector where erase should be linear time. So it is reasonable that random erase operations on std::list... | Because it takes a long time to find the element in the list. Insertion or removal from list is O(1) if you already hold an iterator to the desired insertion/deletion location. In this case you don't, and the std::next(ls.begin(), j) call is doing O(n) work, eliminating all savings from the cheap O(1) erase (frankly, I... |
72,110,090 | 72,110,299 | Overload assignment operator and rule of zero | I have written a template class A<T> and I am making use of the rule of zero (I let the compiler generate the destructor, copy/move constructors and assignment operator overloadings).
However, I need now a customized assignment operator that takes a different type B<T> as argument:
A<T>& operator=(const B<T>& rhs);
Wi... | According to my understanding, adding a operator= overload will not prevent the compiler from generating the default one according to the rule of 0.
I base this understanding on the fact that your operator= overload is not in fact a copy assignment, nor a move assignment.
Therefore the rules about generaing default con... |
72,111,100 | 72,111,761 | CListCtrl did not show text immediately like StaticText | I have a code like this to write install log to a static text and a list control, and i have a button to start the installer that be handle by function OnClickInstallBtn() but every time I call the WriteLogtoScreen(), only the static text change and nothing show up in the list until the OnClickInstallBtn() is done and ... | You should call RedrawWindow() if you want to force the redraw of your list explicitly in something like this :
void WriteLogtoScreen(LPCTSTR sLog)
{
int iItems;
iItems = m_ListLog.GetItemCount();
m_ListLog.InsertItem(iItems, sLog);
m_ListLog.Update(iItems... |
72,111,819 | 72,112,297 | How to let a template function accept anything you can construct some basic_string_view out | I'm trying to write a simple template function which accepts all possible basic_string_view but i always get the compiler error "no matching overloaded function found".
I don't know the reason; explicitly converting to string_view by the caller works but i'd like to avoid that; or is intentionally made hard?
Are there ... | It's also possible to do this using just C++20 by checking whether the argument passed to the function is a range. The range can then be converted to a basic_string_view using its constructor overload that takes iterators.
I've also added an overload that can deal with char pointers since those aren't ranges.
#include ... |
72,111,903 | 72,113,978 | Adding multiple data attributes to one node | I need a way to add more than one data ( such as name, id, age) into a single node in a linked list in C++. Instead of having the data value being only a name or a number.
| I think you wish to group your data, there are many ways to do that.
The easiest is if you create a stucture:
struct MyData {
int id;
std::string name;
int age;
};
MyData data;
data.id = 1;
data.name = "John";
data.age = 23;
std::list<MyData> list;
list.push_back(data);
...
std::list<MyData>::const_iter... |
72,111,960 | 72,113,861 | GCC error when using parent class method as derived class method | I have a function in my code which only accepts a class member method as a template parameter. I need to call this method using a class method which is inherited from a parent class. Here is an example code of my problem:
template <class C>
class Test {
public:
template<typename R, R( C::* TMethod )()> // only a me... | There is namespace.udecl, item 12 (emphasis mine):
For the purpose of forming a set of candidates during overload
resolution, the functions named by a using-declaration in a derived
class are treated as though they were direct members of the derived
class. [...] This has no effect on the type of the function,
and in a... |
72,112,249 | 72,113,646 | BOOST_DEFINE_ENUM_CLASS and json | In the documentation for boost describe, under the heading "Automatic Conversion to JSON", it shows how to implement "a universal tag_invoke overload that automatically converts an annotated struct to a Boost.JSON value". The example supports BOOST_DESCRIBE_STRUCT, how would I implement something similar for BOOST_DEF... | The documentation gives this example (slightly modified to suit our JSON needs later):
template <class E> char const* enum_to_string(E e) {
char const* r = nullptr;
boost::mp11::mp_for_each<boost::describe::describe_enumerators<E>>(
[&](auto D) {
if (e == D.value)
r = D.name... |
72,112,372 | 72,113,446 | How to test the problem size scaling performance of code | I'm running a simple kernel which adds two streams of double-precision complex-values. I've parallelized it using OpenMP with custom scheduling: the slice_indices container contains different indices for different threads.
for (const auto& index : slice_indices)
{
auto* tens1_data_stream = tens1.get_sli... | Your graph has roughly the right shape: tiny arrays should fit in the L1 cache, and therefore get very high performance. Arrays of a megabyte or so fit in L2 and get lower performance, beyond that you should stream from memory and get low performance. So the relation between problem size and runtime should indeed get s... |
72,113,071 | 72,113,238 | Why the datatype of the pointer should be same as the datatype of the variable to which it is addressing? | Code snippet 1:
int main(){
float fl;
int *i=&fl;
}
The error was:
error: cannot convert 'float*' to 'int*' in initialization int *i=&fl;
Code snippet 2:
int main(){
int i;
float *fl=&i;
}
The error was:
error: cannot convert 'int*' to 'float*' in initialization float *fl=&i;
Question
The datatype... |
The datatype only helps in allocating the required memory size to the specified datatype.
This is not true. The type of a pointer p also tells the compiler what type to use for the expression *p.
If p is an int *, then *p has type int, and, if the program uses an expression such as a *p + 3, the compiler will generat... |
72,113,099 | 72,113,237 | What do clang and gcc qualify as variable being unused | I noticed in a PR review an unused variable and we were wondering why compiler didn't catch that. So I tested with godbolt the following code with bunch of unused variables and was surprised that some were reported as unused but others not. Even though all of them are unused.
#include <string>
struct Index
{
Index(i... | The reason why there's no warning is that variables of non-trivial class type aren't technically unused when you initialize them but then never access them in your function.
Consider this example:
struct Trivial {};
struct NonTrivial {
NonTrivial() {
//Whatever
}
};
void test() {
Trivial t;
No... |
72,114,337 | 72,115,595 | CMake - Install Find script for depencency together with script | I am making a CMake library around some installable SDK. So the dependency tree looks like:
Application --> MyLibrary --> OfficialSDK
This SDK is installed by some setup.exe and does not have a CMake module.
So instead I include a custom find script inside MyLibrary: MyLibrary/cmake/FindOfficialSDK.cmake. Then... | I found a solution, largely based on https://discourse.cmake.org/t/install-findpackage-script/5307.
Another example I found inside Pagmo2, for a custom FindBoost script: https://github.com/esa/pagmo2/blob/master/pagmo-config.cmake.in#L10
In a nutshell, I've added the following:
Added an install for my custom find scri... |
72,114,380 | 72,116,921 | Codewars:Path Finder #3: the Alpinist in C++ | I just tried to finish a problem:Path Finder #3: the Alpinist in Codewars. I had passed all basic test cases and there were any errors under my own test cases. But when i submited my solution, my code failed for random test cased. My solution of problem is graph searching based Dijkstra algorithm and priority_queue. I ... | Here is a test case where your code has the wrong answer.
"53072\n"
"09003\n"
"29977\n"
"31707\n"
"59844"
The least cost is 13, with this path:
{1 1 0 0 0}
{0 1 0 0 0}
{0 1 1 1 1}
{0 0 0 0 1}
{0 0 0 0 1}
But your program outputs 15.
|
72,114,591 | 72,118,439 | gsoap - Avoid escaping < and > to < and > | I am using gsoap to access a web service. I generate the code with wsdl2h and soapcpp2 in the following way:
wsdl2h -o BILBO.h http://www.bilbao.eus/WebServicesBilbao/services/ws_bilbaoSOAP?wsdl
soapcpp2 -j -r -CL -1 BILBO.h
And accessing the service in the following way:
#include "soapws_USCOREbilbaoSOAPSoapBindingPr... | To send and receive plain XML you can use the _XML built-in type that is a char* string serialized "as-is", i.e. without translation. Then use the _XML type at places where you used char* in the header file for soapcpp2.
In C++ you can define typedef std::string XML; in the header file for soapcpp2 to define an XML typ... |
72,114,811 | 72,121,222 | Calling C++ function using python | I am trying to build python wrapper for a function implemented in C++ that accepts 2d vector and returns 2d vector. I am trying to adapt the code from this to suit my needs.
Input matrix shape: (n*2)
Output matrix shape: (n*2)
I think there is an issue with code.i file but not really sure what exactly is the issue.
... | First of all, I just want to say that this is one of the most well-written questions I've seen on SO. So thanks for that.
The issue is that you are defining a template for the same type twice, which you are not allowed to do as-per the SWIG documentation:
The %template directive should not be used to wrap the same tem... |
72,116,513 | 72,125,276 | Eigen::Quaternion::FromTwoVectors(a, b) * a != b | I am trying to get the quaternion representing the rotation from unit vector a to unit vector b.
As a sanity check this quaternion should garantee this equality q * a = b. The Eigen function Quaterniond::FromTwoVector https://eigen.tuxfamily.org/dox/classEigen_1_1Quaternion.html doesn't seem to respect my intuition. Yo... | A check with R:
> crossprod(c(-0.0082091040565241327, 0.15209511189816791, -0.89586970189502269))
[,1]
[1,] 0.8257828
shows that your vector b is not a unit vector.
|
72,116,742 | 72,128,149 | Changing type of template at run time | I'm trying to make a Matrix struct which would work with various data types, including my Complex struct:
struct Complex {
double re = 0, im = 0;
Complex operator*(const Complex& other) const {
return Complex(re * other.re - im * other.im, im * other.re + re * other.im);
}
Complex operator*(con... | C++ is statically typed. Once you declare a variable and type, you can't change the type of that variable.
template <typename T>
struct Matrix {
void operator*=(const Complex& z) {
(*this) = (*this) * z;
}
}
The *= operator overload for your Matrix doesn't make sense. A Complex can hold the value of ... |
72,117,373 | 72,117,524 | Factorization of numbers | I'm trying to write a function that has one integer parameter (let's call it ), which returns as a result a vector consisting of all prime factors of the number , where each factor appears as many times how many times it appears in the factorization of numbers into prime factors.
#include <iostream>
#include <vector>
#... | Use the % operator to find numbers that divide n evenly. Each time you find a factor, divide n by that factor as long as it continues to divide evenly.
std::vector<int> PrimeFactors(int n) {
std::vector<int> r;
for (int i = 2; i * i <= n; i += 1 + (i > 2)) {
while ((n % i) == 0) {
r.push_bac... |
72,117,485 | 72,118,361 | undefined reference to inline friend | Why does taking the address of an inline friend not result in code being produced. This works for regular inline functions. Is the declaration not matching the inline friend somehow?
#include <iostream>
namespace S
{
template <unsigned N>
class X
{
int i;
friend X operator+(const X& a, const X& b) noexcept
... | There is no argument-dependent lookup when taking the address of an overload set.
So, the initialization of the function pointer doesn't require the compiler to instantiate X<256> to figure out whether there is a operator+ in it. For an unqualified function call this would happen.
Neither does the declaration of operat... |
72,117,986 | 72,119,927 | c++ write date as bytes in binary file and read in same view | I have multiple dates in yyyy-mm-dd format, which I need to write in a binary file as bytes and then read them in the same format. Here is the method I have for writing the file (but seems it is not fully correct):
fstream f("binaryOut.bin", ios::out | ios::binary);
string dateString;
char arr[4];
char dateArray[8];
fo... | I noticed that in your code you use numbers instead of chars to represent the year (e.g. char yearArr[] = {2, 0, 2, 2};). Is that by design? I would prefer to use char yearArr[] = {'2', '0', '2', '2'}; In fact, I would convert everything to char, so that I can read/write to the file using char.
Another observation I ma... |
72,118,002 | 72,118,470 | How can i store all my vector elements in a hash table c++ | Code which i Have Done##
class vehicle
{
public:
vehicle();
virtual ~vehicle();
void addVehicle();
void deleteVehicle();
void printvehicle(vehicle v);
void show();
void showleft();
void vehcileLoad();
protected:
private:
std::string pltno... | Assuming all of your vehicle objects are stored in a std::vector<Vehicle>, using a std::unordered_map<std::string, Vehicle> is a very simple way of getting a hash table populated with the vehicles:
#include <unordered_map>
#include <vector>
#include <string>
//...
class Vehicle
{
//...
};
void foo()
{
std::vector<... |
72,118,060 | 72,118,266 | how to delete a row from the QListWidget in which the button was pressed | how to delete a line from QListWidget in which the button was pressed? i know to delete some line (foto) it is necessary to cause method removeItemWidget but for it it is necessary QListWidgetItem but I do not know how to receive it having QWidget which I received from sender ()
The code I use to create strings:
QL... | removeItemWidget() only removes the item from the view but it does not delete it so you will have a memory leak. I am not sure if this is what you want, I guess not. But to remove widget from the item, you can delete the widget and it is removed automatically. So the following code should delete the widget and the row ... |
72,118,896 | 72,119,036 | why i am getting this error request for member set in b which is of non class type box[5] | why I am getting this request for member set in b which is of non class type box[5]?
I am calculating volume of box and storing length breadth and volume in box array of objects
what can I do to solve this?
#include<iostream>
using namespace std;
class box
{
int length;
int breadth;
int height;
int n;
... | emphasized textThe variable b declared in main
box b[5];
has an array type. Arrays do not have member functions. So this statement
b.set(5);
is incorrect. You could write for example
b[0].set( 5 );
However within the member function set there is used uninitialized pointer b
b[i].length=len;
b[i].brea... |
72,119,362 | 72,120,090 | Formatting input in C++ | So I am writing a program, and need to use some formatting to pretty up the output. Right now, the way I write it is like this (as an example):
cout << "|" << setfill('=') << setw(40) << "|" << endl;
cout << "| What is your name?: ";
cin >> userName;
cout << setfill(' ') << setw(40 - 21 - userName.size(... | This string "\033[F" moves the cursor up one line. What I did is move the cursor up one line after receiving the username and then reprinting the second line with the '|' symbol at the end.
This code only works if the username is not too long.
#include <iostream>
int main()
{
std::string username;
std::string ... |
72,119,874 | 72,120,187 | Why initializing a 'const reference to base' object from 'constexpr derived' object doesn't yields constant expression? | I have this simple example:
struct base
{
constexpr base () {};
};
struct derived: public base
{
constexpr derived () {};
};
int main()
{
constexpr derived d{};
constexpr const base &b = d; // why error?
}
G++ gives me the following error:
error: '(const base&)(& d)' is not a constant express... | The explanation given by Clang is correct.
Constexpr doesn't change the storage of a variable (where it's put in memory). If you declare a non-static constexpr variable, it'll still go onto the stack, just like all other non-static local variables do.
int test() {
constexpr int a = 3; //a gets created here and put on... |
72,119,906 | 72,765,374 | cmake problem of target type when using swig with C++17 | Things are getting confused for me, so I hope to be clear.
I made a c++17 library (called here myLib), and I bind it with python using swig. Everything is working when I compile by hand.
Now, I would like to automatize and clean my work using cmake: no problem for the library.
But things are getting more obscure to me ... | I came up with this solution (do not hesitate to improve it):
include(FindSWIG)
find_program(SWIG_PATH swig)
find_package(SWIG 4.0 COMPONENTS python)
include(UseSWIG)
find_package(PythonLibs 3 REQUIRED)
find_package(PythonInterp ${PYTHONLIBS_VERSION_STRING} REQUIRED)
set(CMAKE_SWIG_FLAGS -py3)
message("PYTHONLIBS_... |
72,119,987 | 72,120,018 | getting error in understanding friend function in c++ | Why am I am getting an "expected identifier" error before .token?
Please provide a solution to understand friend function properly.
At first, I am getting a forward declaration error, but I resolved that one by myself.
#include<iostream>
using namespace std;
class a;
class b
{
public:
void search(a and);
};
clas... | For compatibility with old keyboards and encoding schemes where some symbols weren't available, certain keywords can be used in place of symbols. Among them, and is a valid replacement for &&. So your and.name is actually getting parsed as &&.name, which is a syntax error.
The (unfortunate) solution to your problem is:... |
72,120,029 | 72,120,169 | boost::multiprecision::cpp_int acting like unsigned long long | So I have a programming assignment in which I have to work with 64 digit numbers. I am currently using the boost::multiprecision::cpp_int library but I'm not able to use it on large numbers.
For example-
#include <boost/multiprecision/cpp_int.hpp>
int main()
{
boost::multiprecision::cpp_int n1 =1233412576120458761... | Use the string constructor, because you cannot express the initializer in C++, otherwise.
Live On Coliru
#include <boost/multiprecision/cpp_int.hpp>
#include <iostream>
int main() {
boost::multiprecision::cpp_int n1("123341257612045876129038576124390847381295732");
n1 *= n1;
n1 *= n1;
std::cout << n1 ... |
72,120,058 | 72,120,082 | Function GetDriveTypeW always returns DRIVE_NO_ROOT_DIR | As title says, standard Windows GetDriveTypeW returns value 1 (DRIVE_NO_ROOT_DIR) for all passed paths.
Documentation says
The root path is invalid; for example, there is no volume mounted at
the specified path.
Although I'm pretty sure the supplied paths (e.g. "C:\\temp", "c:\\temp") is valid and is fixed drive (har... | The documentation also says that the argument must be:
The root directory for the drive.
A trailing backslash is required...
That is you should call it with C:\ if you want to check the C: drive, or C:\temp\ if you want to check the drive mounted at C:\temp.
|
72,120,369 | 72,125,589 | Number of friendly pairs in vector | I'm trying to write a function that accepts a vector of integers as a parameter and returns the number of friendly pairs that can be found in that vector. The function must not use any other auxiliary functions.
A pair of numbers is friendly if the sum of all divisors of one number (not counting itself) is equal to ano... |
A pair of numbers is friendly if the sum of all divisors of one number (not counting itself) is equal to another number and vice versa.
However, the code only tests that some sum of divisors equal to some number. The vice versa part is sorely missing. For example, the code claims one friendly pair in {7, 8}.
You need... |
72,120,435 | 72,122,188 | Calculating surface normals of dynamic mesh (without geometry shader) | I have a mesh whose vertex positions are generated dynamically by the vertex shader. I've been using https://www.khronos.org/opengl/wiki/Calculating_a_Surface_Normal to calculate the surface normal for each primitive in the geometry shader, which seems to work fine.
Unfortunately, I'm planning on switching to an enviro... | See Diffuse light with OpenGL GLSL. If you just want the face normals, you can use the partial derivative dFdx, dFdy. Basic fragment shader that calculates the normal vector (N) in the same space as the position:
in vec3 position;
void main()
{
vec3 dx = dFdx(position);
vec3 dy = dFdy(position);
vec3 N ... |
72,120,862 | 72,125,127 | Indexing JSON object in C++ | I am looking to parse a JSON object much more efficiently than I am now. Currently I'm running through a range-based for loop to index the key-value elements (see below). Is it possible to run through all of the records inside of a JSON object and parse particular fields w/o a loop?
#include "nlohmann/json.hpp"
using j... | According to the documentation at https://json.nlohmann.me/api/basic_json/at/ you can use the at()-method, which has a constant complexity when it's used with a location index parameter.
So for example you could do something like this:
std::cout << myObj.at(2)["batter"]["id"].get<std::string>() << std::endl;
Note that... |
72,121,621 | 72,121,717 | When does std priority queue compare the values? | I have a priority queue and the compare function references a value accessed by multiple threads. So it has to be protected by a mutex. Except I don't know when this compare function is ran. Is it ran when I push a value or when I pop a value? Example code below.
#include <iostream>
#include <queue>
#include <mutex>
... | To answer the question, if it is not documented anything can happen (and then we cannot then reason about when comparator is invoked).
If we take a look into cppreference, push is defined in terms of push_heap, which then reorganizes the elements into a heap. Given it then needs to reorganize, we can reason that it inv... |
72,122,018 | 72,149,017 | How can I get a consistent, unique, identifier for a unique class combination? | I need a way to identify a unique combination of template types that gives me an easily indexable identifier.
I have the following class:
#include <cstdint>
typedef std::uint32_t IDType;
template<class T>
class TypeIdGenerator
{
private:
static IDType m_count;
public:
template<class U>
static IDType Ge... | Instead of incrementing a counter to create the type IDs, you could instead use a hash function to generate a 'unique' hash. While there is some chance of collision, the risk is very low if the hashing function is efficient. This approach would provide consistent IDs for each type throughout an invocation of the progra... |
72,122,101 | 72,123,297 | Question about some specific differences between new T() and new T in C++11 and afterwards | Attention please: you may think this post is a duplicate to this old post. But the said post was more than 12 years ago and none of the answers mentions the C++11 and afterwards.
And what's more, my question is about the comment of the answer which has most votes and my question is about the detailed code snippet below... |
Question about some specific differences between new T() and new T
new T() is value initialisation. For aggregate classes such as Line and Point<T> this means that all sub objects are value initialised. For primitive objects such as double* and int this means zero initialisation.
new T is default initialisation. For... |
72,122,119 | 72,122,228 | why the raw pointer get by std::unique_ptr's get() can not delete the object and how is that implemented | As the following code presents, I tried to delete the object by the raw pointer get from a unique_ptr. But, as the output shows, the complier reported errors. However, for raw pointers, we can do this int *p1 = new int{100}; int* p2 = p1; delete p2;.
Besides, I thought that unique_ptr maintain its ownership by move sem... | std::unique_ptr is a really simple class. Conceptually, it's basically just this:
template <typename T>
class unique_ptr
{
private:
T* ptr;
public:
unique_ptr(T* p) ptr{p} {}
~unique_ptr() { delete ptr; }
T* get() { return ptr; }
T* release() {
T* p = ptr;
ptr = nullptr;
r... |
72,122,147 | 72,127,784 | Problem with Boost Fibonacci Heap at the moment of erasing an element | I'm getting an unrelated error with Boost's Fibonacci Heap when I use the erase()method:
astar: /usr/include/boost/intrusive/list.hpp:1266: static boost::intrusive::list_impl<ValueTraits, SizeType, ConstantTimeSize, HeaderHolder>::iterator boost::intrusive::list_impl<ValueTraits, SizeType, ConstantTimeSize, HeaderHolde... | This loop looks suspect:
for(auto it=open.begin(),end=open.end(); it != end; ++it){
open.erase(/*...*/);
}
Quoting the docs:
Unless otherwise noted, all non-const heap member functions invalidate iterators, while all const member functions preserve the iterator validity.
That means the erase invalidates the loop... |
72,122,163 | 72,122,213 | After inserting at head in linked list. Now what is name of that node which was head before inserting new node | // insert at head LL
#include<iostream>
using namespace std;
class node{
public:
int data;
node* next;
node(int val){
data=val;
next=NULL;
}
};
void insertAtHead(node* &head, int value){
node* n= new node(value);
n->next=head;
head=n;
}
void display(node* head){
while... |
[H]ow to access data of node which was previously head?
The previous head node is now the currents head-nodes next node:
std::cout << "Previous head value: " << head->next->data << '\n';
|
72,122,455 | 72,135,263 | Linux Apache CGI can't open lib when visiting the website | I'm using unixODBC and Apache CGI to build a database website on Linux. The following problems occurred when I tested the query of the database.
Connect Error
[01000] [unixODBC][Driver Manager]Can't open lib '/usr/local/lib/psqlodbcw.so' : file not found (0)
The above information appears on another computer on which I... | Okay, guys, I've solved this problem. Like Some programmer dude said, "Generally don't use the root user for any kind of development, that can give you the false impression that things works ". When I use tar as ubuntu (not root), system shows the same error "file not found". Then I realize that the ODBC library instal... |
72,122,495 | 72,122,546 | Overloading Type-Cast in c++ | I want to understand how typecast-overloading works. For my question, I want to know
The thing I'm trying to do is it possible?
If yes, then how?
I want the user to be able to pass a vector<float> to a function. This function is implemented in such a way that its parameter is a wrapper class around vector<float>.
Can... | All that's needed is a non-explicit constructor taking the correct argument (a so-called conversion constructor):
class Layer {
vector<float> l;
public:
Layer(vector<float> const& v);
};
Now the compiler will be able to do implicit conversions from vector<float> to Layer.
Note that it's usually not recommende... |
72,122,733 | 72,123,328 | C++ function not getting called | I have a function that takes 2d-vector and outputs a 2d-vector. For some reason, the function is not getting called.
Here is the link to reproduce the issue: Google Colab.
In the link to check for correctness, I have added another code that uses the exact same function but doesn't take a 2d-vector array as an argument ... | There's some issue on your code. First of all in main to correctly initialize the vector you have to use the {} syntax. Further in customComputeConvexHull you are setting values inside the res vector which are not yet present. You have to use push_back to populate res. Below a version of your code which works (I put ev... |
72,123,107 | 72,127,138 | What were the reasons to terminate boost graph searches via exceptions? | Early exit of algorithms in boost graph such as breadth first search should be done by throwing an exception according to the FAQ:
How do I perform an early exit from an algorithm such as BFS?
Create a visitor that throws an exception when you want to cut off the search, then put your call to breadth_first_search in... | It simplifies the implementation. It allows all searches to leverage a generic traversal algorithm.
The argument becomes amplified in the face of generics.
Note that the visitors can be implemented in several ways:
users can implement the visitor interface
derive from one and override some handlers
or
compose one fr... |
72,123,155 | 72,123,990 | Using a enum class from a c++ header in a c header | I am writing a c wrapper around a c++ library.
In the c++ there are enum classes used as types for function arguments.
How do I use theme correctly in the c header.
One ugly way would be to use int's in the c function and cast theme in the wrapper function to the enum type. But this gives the user of the c function no ... | You can not do it. It is impossible to use C++ features from C code. You are creating C wrapper for C++ function, why can not you create also C wrapper for enum? The only question is how to be sure that both enums have the same values. You can check it compile time after the small code change:
cpp header:
namespace GPI... |
72,123,200 | 72,123,568 | Unknown command : QT5_ADD_TRANSLATION in Qt cmake project | I'm developing Qt application and now I want to do some I18N stuff. First problem I meet is that cmake doesn't know about command QT5_ADD_TRANSLATION(we are using cmake for building our project). I refer to QtLinguist Manual. When I met that problem, I also read threads like Unknown CMake command "QT5_CREATE_TRANSLATIO... | It should be something like this:
find_package(Qt5 COMPONENTS LinguistTools)
qt5_add_translation(OUTPUT_VAR your_translation.ts)
CMake functions/macros provided by Qt itself belong to some particular module so you need to find that module before using its functioncs.
|
72,123,757 | 72,124,019 | Why is my matrix multiplication code not working? | I am new to C++ and I have written a C++ OpenMp Matrix Multiplication code that multiplies two 1000x1000 matrices. So far its not running and I am having a hard time finding out where the bugs are. I tried to figure it out for a few days but I'm stuck.
Here is my code:
#include <iostream>
#include <time.h>
#include <om... | The transposed matrix (BTransposed) is not correctly constructed. You can solve this in the following ways:
First Option: use a for loop to create the correct BTransposed matrix.
for (int i = 0; i != N; i++)
for (int j = 0; j != N; j++)
BTransposed[i][j] = bMatrix[j][i]
Second Option (better one): completely del... |
72,123,871 | 72,124,119 | How to store every sequentially increasing sequence in a vector into new vectors | I have a vector with the following elements:
std::vector<int> vectorOfInts{ 95, 137, 138, 139, 140, 156, 157, 158, 159 };
Problem: I'm trying to store each sequence in a new vector, where each sequence is defined as a list of sequentially increasing values (that are increasing by 1).
Some properties of vectorOfInts:
T... | You can use this algorithm: Create a vector of vectors that contains one vector containing the first element of the input vector. These are the output vectors. For each element of the input vector after the first, if the element is not previous element +1, then push a new vector to the output. Insert the current elemen... |
72,123,893 | 72,124,047 | How to read in C++ a short int (2 byte) LSB first value? | How can I read two separate bytes each with LSB first?
2 speparate LSB first bytes -> one short int MSB first
e.g. 01001100
11001100
-> 00110010 00110011
short int lsbToMsb(char byte1, char byte2) {
...
return msb;
}
| Try this:
char reverseBits(char byte)
{
char reverse_byte = 0;
for (int i = 0; i < 8; i++) {
if ((byte & (1 << i)))
reverse_byte |= 1 << (7 - i);
}
return reverse_byte;
}
short int lsbToMsb(char byte1, char byte2) {
byte1 = reverseBits(byte1);
byte2 = reverseBits(byte2);
... |
72,124,111 | 72,124,279 | Why the `this` pointer worked in constructor in C++? | I know the this pointer will point to the object instance that currently in, but I don't know how to implement it.
And I found that in standard 7.5.2 said:
The keyword this names a pointer to the object for which an implicit object member function ([class.mfct.non.static]) is invoked or a non-static data member's init... |
but I don't know how to implement it.
this pointer is a feature of the C++ language. If you aren't implementing C++, then you don't need to "implement" this pointer. If you want to know how to implement C++, there are open source C++ compilers available.
why I can use this pointer in constructor?
Constructor is a n... |
72,124,149 | 72,124,443 | Why doesn't mutex work without lock guard? | I have the following code:
#include <chrono>
#include <iostream>
#include <mutex>
#include <thread>
int shared_var {0};
std::mutex shared_mutex;
void task_1()
{
while (true)
{
shared_mutex.lock();
const auto temp = shared_var;
std::this_thread::sleep_for(std::chrono::seconds(1));
... | Suppose you have a room with two entries. One entry has a door the other not. The room is called shared_var. There are two guys that want to enter the room, they are called task_1 and task_2.
You now want to make sure somehow that only one of them is inside the room at any time.
taks_2 can enter the room freely through... |
72,124,490 | 72,124,562 | Why is the member value of parent lost in the vector after push_back()? (C++) | I would like to push an instance of Child (Parent is the base class of Child), in a vector using push_back(). But then the value of the Parent members lost.
In the following example, I would like to see 70 when writing the vector to the console, but I get random value instead. What is causing this?
main.cpp:
void demo(... | The child's copy constructor only copies the child parts. It should also invoke the parent's copy constructor to let it copy the parent members.
Child::Child(const Child& other) : Parent(other)
{
siz = other.siz;
}
|
72,124,951 | 72,125,039 | different behaviour of unhashable typeError between cpp and python | It is ok to insert a vector to a set in cpp, which not works in python however. Codes shown below:
// OK in cpp
set<vector<int>> cpp_set;
cpp_set.insert(vector<int>{1,2,3});
// not OK in python
py_set = set()
py_set.add([1,2,3]) # TypeError: unhashable type: 'list'
py_set.add({1,2,3}) # TypeError: unhashable type: '... | Python's set is a hash table, and has no hashing functions for set and list.
std::set is not a hash table but a sequence ordered by an ordering relation (std::less by default).
You can use std::set with any type where you can define a strict weak ordering.
Try std::unordered_set in C++ and you will encounter problems.
|
72,125,208 | 72,125,265 | cin didnt work in range based loop in vector | I tried to input values to my vector,but it filled with zero value.
I try to input value by following range based loop and output them.
#include <bits/stdc++.h>
using namespace std;
#define REP(i,n) for(int i=0; i<(n); i++)
int main() {
int N;
cin>>N;
vector<int>A(N);
for(auto x:A) cin>>x;
for(aut... | The problem does not relate to std::cin at all. The problem is the way you used auto in the range based loop.
In order to update the std::vector, you should change:
for(auto x:A) cin>>x;
to:
for(auto & x:A) cin>>x; // NOTE: added '&'
Because the meaning of auto does not include "reference-ness" (even if the express... |
72,125,663 | 72,131,960 | Avoid compiling definition of inline function multiple times | I have a non-template struct in a header file:
struct X {
constexpr X() : /* ... */ { /* ... */ }
constexpr void f() {
// ...
}
};
With functions of varying size. This is used in a lot of different translation units, and each function appears in multiple object files for them to be discarded in the... | C++ doesn’t have the notion of an inline function that must be emitted in one translation unit and which therefore certainly need not be emitted anywhere else. (It doesn’t have the notion of emitting object code at all, but the point is that there’s no syntax that says “I promise this definition is ODR-identical to th... |
72,126,220 | 72,126,536 | Allocator named requirements -- exceptions | [allocator.requirements.general]/37
Throws: allocate may throw an appropriate exception.
Any limitations on "appropriate" implied elsewhere?
Can a valid custom allocator just throw a double on any request?
Context: implementation of a noexcept function that uses allocator, but has fallback strategy to do something i... |
Any limitations on "appropriate" implied elsewhere?
No. "Appropriate" qualifier has no objective meaning. It's effectively a suggestion to use common sense. There are no limitations on the type thrown from allocate.
Can a valid custom allocator just throw a double on any request?
It would be conforming if the autho... |
72,126,824 | 72,391,931 | How to load multiple images in SDL_image and SDL2? | I've been trying to load 2 images in a SDL window, like a player and an enemy, but SDL2_image loads only one image at a time
here's my code :
#include<iostream>
#define SDL_MAIN_HANDLED
#include<SDL2/SDL.h>
#include<SDL2/SDL_image.h>
using namespace std;
SDL_Texture* load(SDL_Renderer* ren, const char* path, SDL_Rect ... | solved, it was due to SDL_RenderClear
|
72,127,008 | 72,127,295 | Why this function is not able to reverse the Linked List? | I want to reverse a linked list but when i compile this code it terminates unexpectedly.
#include <bits/stdc++.h>
using namespace std;
class node{
public:
int data;
node* next;
node(int val){
data=val;
next=NULL;
}
};
For Inserting Elements in Linked List
void insertattail(node* &head,int... | Your initialization and 'incrementing' of nextptr both (potentially/eventually) dereference a NULL value of currptr. You should initialize nextptr to NULL and only change that to the 'real' next if currptr is not NULL; thus, its (re)assignment should be at the start of the loop, not at the end:
node* reverseit(node* he... |
72,127,603 | 72,127,661 | Can we take the address of xvalue | As I know, there have been come concepts since C++11: lvalue, rvalue, prvalue, xvalue etc.
As my understanding, if a function returns a local variable, it should be a rvalue.
std::string func() { return std::string("abc"); }
auto ret = func(); // func returns a rvalue
And for xvalue, std::move(x) is a kind of xvalue.
... | Your colleague is incorrect. C++ has always required an lvalue for use with the address of operator. This is called out explicitly in [expr.unary.op]/3:
The operand of the unary & operator shall be an lvalue of some type T. The result is a prvalue.
If the standard had used glvalue instead of lvalue then they would ... |
72,127,835 | 72,127,957 | Should assignment initialization work with a type with non-explicit single param ctor but with deleted move ctor? | Should the following compile under c++11 rules? Why should it or why not? Is there UB? It seems that gcc forbade it before but changed their mind in version 11. Microsoft accepts it and clang consistently does not.
I was under the expression that IntWrapper myInt = 42; in this case is just syntactic sugar and is exactl... | msvc v.19.x and gcc 11.x both default to using C++17 as the language standard to compile against while all of the other compilers you used default to C++14. This is why you see a difference.
Before C++17 IntWrapper myInt = 42; is semantically treated as IntWrapper myInt = IntWrapper(42); so you need a non-deleted copy... |
72,127,920 | 72,128,180 | Naive reverse string iteration infinite loop and/or assertion failure C++ / Visual Studio 2022 | I am trying to reverse iterate through a string, but am getting assertion failure for the [] operator in the latest VS.
int foo() {
std::string s = "s";
for (int i = (s.size() - 1); i >= 0; i--) {
std::cout << s[i] << std::endl;
}
return 0;
}
Commenting out the cout line gives infinite loop war... | Could it be that your int defaults to being unsigned and therefore decrementing when i=0 resuts in a high value ?
As @PeteBecker mentioned, int should be signed and should not overflow. However my guess is that your actual code does not use int.
|
72,128,134 | 72,129,309 | Generic vector of vector n dimensionnal | I try something (probably in the wrong way) but the langage and std doesn't let me do what I want.
I have a void* that can contain : std::vector<int> or std::vector<std::vector<int>> or std::vector<std::vector<std::vector<int>>> or ... and so on. I have a dpeth variable to know how much vector level.
So I "just" want t... | First of all, prefer a std::any (rather than void*) to allow a variable to take on values of any type.
Here is a way to describe your strongly-typed N-dimensional jagged vector.
#include <vector>
#include <any>
template<int n, typename T>
class DIM : public std::vector<typename DIM<n - 1, T>::type> {
public:
type... |
72,128,421 | 72,132,012 | Convert python with numpy to c++ with opencv | I'm working on some optimazation and want to convert some parts from python to c++
Is it possible to convert this code to c++ with opencv?
The python code uses numpy
import numpy as np
from PIL import Image
pil_img = Image.open(input_filename)
img = np.array(pil_img)
pixels = img.reshape((-1, 3))
num_pixels = pixels.... | This is the equivalent code in C++11. This should be several times faster than your python code.
#include <random>
#include <numeric>
#include <opencv2/opencv.hpp>
void shuffling(const std::string &input_filename, const std::string &output_filename) {
// ========== UPDATE ==========
const cv::Mat plain_input... |
72,128,490 | 72,128,713 | Simple yet realistic billiard ball acceleration | I have a simple 2D game of pool. You can give a ball some speed, and it'll move around and hit other balls. But I want a ball to stop eventually, so I added some acceleration, by running this code every frame:
balls[i].ax = -balls[i].vx * 0.1;
balls[i].ay = -balls[i].vy * 0.1;
...
if(hypot(balls[i].vx, balls[i].vy) < 0... | The rolling friction formula is this: F_k,r=μ_k,r_Fn. It only factors in the properties of the surface (μ_k) and the force on the ball (r_Fn). This should decelerate with a constant value, just adjust it until it looks roughly correct.
Example code:
x = 1 // mess around with this until it looks right
if (ball.xVeloc... |
72,128,648 | 72,128,846 | How to create a `span<std::byte>` from a single generic object? | I have a parameter of type const T& and want to turn it into std::span<const std::byte> or whatever the magic type that std::as_bytes() spits out is.
Ranges have a number of constructors, mostly aimed at containers, arrays, etc. But I can't seem to turn a single object into such a span. I feel like this is not an unrea... | Pointer to individual object can be treated the same way as pointer to an array of single object. You can create a span like this:
const T& t = value();
auto s = std::span<const T, 1>{std::addressof(t), 1};
You can then use std::as_bytes:
auto bytes = std::as_bytes(std::span<const T, 1>{std::addressof(t), 1});
Helper... |
72,128,990 | 72,129,558 | How to use a button to stop a while loop that has a sleep timer? (Qt c++) | I would like to preface that I am very new to programming. So the answer may be obvious or I may have done something incorrectly; feel free to (politely) point that out. I am always excited to learn and be better!
I am trying to create and send test data using a while loop. The while loop has a sleep timer so that the ... | Use a QTimer instead of a sleep. That way it can be stopped at any point, and it doesn't block other things that your application wants to do while it's waiting.
Make the QTimer a member pointer of your class:
class DlgTestData
{
...
private:
QTimer *m_timer;
};
Then initialize it in the constructor:
DlgTestDat... |
72,129,229 | 72,156,496 | error: (-215:Assertion failed) (int)_numAxes == inputs[0].size() in function 'getMemoryShapes' | im trying to use opencv to do face recognition using facenet512. i converted the model to onnx format using tf2onnx. i know that the input of the model should be an image like :(160,160,3). so i tried doing this using this script :
void convertDimention(cv::Mat input, cv::Mat &output)
{
vector<cv::Mat> channels(3);... | using netron i was able to visualize the input of the model :
the origin of the problem was from the conversion of the model i just had to change this :
model_proto, _ = tf2onnx.convert.from_keras(model, output_path='facenet512.onnx')
to this :
nchw_inputs_list = [model.inputs[0].name] model_proto, _ = tf2onnx.conver... |
72,129,236 | 72,130,778 | How to expand multiple index_sequence parameter packs to initialize 2d array in C++? | I'm trying to initialize my Matrix class with std::initializer_lists. I know I can do it with std::index_sequence, but I don't know how to expand them in one statement.
This is how I do it:
template<size_t rows, size_t cols>
class Matrix {
public:
Matrix(std::initializer_list<std::initializer_list<float>> il)
... | I think the problem comes from the fact that RowIs and ColIs are expanded at the same time, i.e. both always having the same values during the initialization: 0, 1, 2...
You can check here that your current output (after fixing the compiler error) would be something like
[[1.1, 5.5, 9.9], [0, 0, 0], [0, 0, 0]] for the ... |
72,129,780 | 72,130,307 | Subscripting/Indexing a Pointer in C++ | I'm working through some code for a class I'm taking, and since I'm not familiar with C++ I am confused by subscripting pointers.
My assumptions:
& prefixed to a variable name, gives you a pointer to the memory address of that value and is roughly inverse to * prefixed to a variable name, which in turn gives you the va... | As per Ted Klein Bergmann's comment, there was a problem with operator precedence.
[] is considered before &. Do (&val)[0] instead.
So a working example would be
#include <iostream>
using namespace std;
int main() {
int val = 1;
// does work now
cout << (&val)[0] << endl;
return 0;
}
|
72,130,098 | 72,130,185 | Comparing multiple bits between two uint64_t's based on unique type id always returns true | I've got a map where keys are entity id's (uint32_t) and values are "signatures," aka uint64_t's with certain bits set that represent a type: std::unordered_map<uint32_t, uint64_t> m_entityComponents{};
My goal is to write a template function that accepts a variable amount of types and returns whether or not ALL of tho... | You are generating a signature that contains all the required bits set to 1, but you are not correctly checking if the entity's value actually has all of those same bits set to 1. You are checking if the value has any of those same bits is set to 1 instead.
In this comparison:
return (m_entityComponents[entity] & signa... |
72,130,690 | 72,130,963 | Does boost atomic reference counting example contain a bug? | I'm referring to this example.
The authors use memory_order_release to decrement the counter. And they even state in the discussion section that using memory_order_acq_rel instead would be excessive. But wouldn't the following scenario in theory lead to that x is never deleted?
we have two threads on different CPUs
ea... | All modifications of a single atomic variable happen in a global modification order. It is not possible for two threads to disagree about this order.
The fetch_sub operation is an atomic read-modify-write operation and is required to always read the value of the atomic variable immediately before the modification from ... |
72,131,086 | 72,131,130 | Using parent constructor instead of defining child | I have a base class Foo and two child classes Bar and Car. Foo is pure virtual. Bar inherits foo with its own constructor to assign a variable. However Car doesn't have a constructor.
#include <memory>
#include <iostream>
class Foo{
public:
virtual void T() = 0;
};
class Bar : public Foo{
protected:
int n;
publ... | You can apply inheriting constructors as:
class Car : public Bar {
using Bar::Bar;
...
};
Then
Car car(10); // Bar base subobject is initialized by Bar(10)
|
72,131,095 | 72,131,284 | The sum of a sequence | I'm trying to make a function for calculating this formula
#include <iostream>
#include <vector>
double Sequence(std::vector < double > & a) {
double result = 0;
for (int i = a.size() - 1; i > 0; i--) {
if (a[i] == 0) throw std::domain_error("Dividing with 0");
if (i > 1)
result += 1 / (a[i - 1] + 1 ... | if (i > 1)
result += 1 / (a[i - 1] + 1 / a[i]);
else result += a[i - i];
This is wrong; it just happens to work if you have three or fewer terms.
The recurrence you actually want is
if (i == a.size() - 1) {
result = a[i];
} else {
result = a[i] + 1 / result;
}
you can see that this is a correct recurrence b... |
72,131,285 | 72,131,963 | Declare a constexpr static member that is a function of a potentially-absent member in a template parameter? | I have a templated class for which I would like to provide a constexpr integer whose value is determined by the presence or absence of a constexpr integer in the template parameter:
template<typename Traits>
class Foo
{
static constexpr int MaxDegree =
std::conditional<
std::is_integral<Traits::MaxDegree>::... | Traits::MaxDegree
yields a compiler error, if the member doesn't exist. This means you cannot use this code as part of the expression directly.
You could use constexpr functions with SFINAE to implement this though:
template<class T>
constexpr typename std::enable_if<std::is_integral<decltype(T::MaxDegree)>::value, in... |
72,131,693 | 72,133,797 | boost::asio::io_context::stop segfalt in gtest setup and teardown | Using C++17. I am trying to setup a gtest fixture that will create a fresh io_context to run timers on for each test case. My test segfault about 90% of the time. If I debug and step very slowly, I can get it to run all the way through.
I am not sure what's going on here. I've went and created a new thread and new iose... | The problem is that there is no guarantee that anything on a thread is going to execute before the main thread resumes execution. This caused problems where the ioservice was not created and running before the test case executed, where it was assumed that the ioservice would be running.
This can be fixed using a semaph... |
72,131,793 | 72,143,663 | Can you relink/modify relative shared library look up paths? | I am running into the following situation. Project A has libraries A1, A2, A3... That follow their own directory structure. For example:
Libaries/
|
|--Dir1/
| |
| |--A1.so
| |--A2.so
|
|--Dir2/
| |--A3.so
| |--A4.so
In this case Project A compiles just fine. The libraries of project A are dependencies for projec... |
Is there a way I can poke the files Ai.so and tell them "Hey that other library whose symbols you need is actually over here now"?
You can use patchelf to do that, but you shouldn't.
Since you control how A*.so is built, you should set their RPATH so that it works "out of the box". Adding -rpath=/path/to/BLibraries t... |
72,131,818 | 72,132,018 | gcc-10-ar thinks the invalid "." option is being passed to it | I'm compiling a game using the Source Engine. When I run make, after a while the archiver tool complains about an invalid option ".":
/usr/bin/ar: invalid option -- '.'
this happens with every archiver I have installed: gcc-10-ar, llvm-10-ar, and busybox ar.
The command the makefile is trying to run is:
gcc-ar-10 ../l... | The first argument to ar is supposed to be one or more characters indicating the operation to perform (optionally prefixed with -) and modifiers to this operation.
If you want to create a new archive from the object files, you probably want rcs, which asks ar to insert the listed files into the archive with replacement... |
72,131,930 | 72,132,196 | Why aren't temporary container objects pipeable in range-v3? | Why is the following
#include <iostream>
#include <string>
#include <range/v3/all.hpp>
std::vector<int> some_ints() {
return { 1,2,3,4,5 };
}
int main() {
auto num_strings = some_ints() |
ranges::views::transform([](int n) {return std::to_string(n); }) |
ranges::to_vector;
for (auto s... | Short answer would be because they are lazy and | does not transfer ownership.
I would expect the lifetime of the temporary to be extended to the lifetime of the whole pipeline expression so I don't understand what the problem is.
Yes, that is exactly what would happen, but nothing more. Meaning that as soon as the c... |
72,132,309 | 72,142,187 | C++ {fmt} library: Is there a way to format repeated format fields? | I have a program with many formatted write statements that I'm using the fmt library for. Some of them have many fields, say 100 for example purposes, something like this:
fmt::print(file_stream, "{:15.5g}{:15.5g}{:15.5g}/*and so on*/", arg1, arg2, arg3/*same number of arguments*/);
Is there a straightforward way to t... | You can put your arguments in an array and format part of this array as a view (using span or similar) with fmt::join (https://godbolt.org/z/bo1GrofxW):
#include <array>
#include <span>
#include <fmt/format.h>
int main() {
double arg1 = .1, arg2 = .2, arg3 = .3;
double args[] = {arg1, arg2, arg3};
fmt::print("{:... |
72,132,658 | 72,134,496 | Qt Creator Release Build Quit Unexpectedly | After compiling any version (Debug and Release) of the application with Qt Creator, it only runs from under Qt Creator with the option: "Add build library search path to DYLD_LIBRARY_PATH and DYLD_FRAMEWORK_PATH".
I try compilation and use macdeployqt for creation dmg. App after start crash: "Quit Unexpectedly" because... | I found solution, macdeployqt not copy all required libraries and some files to App, need manually copy to:
Plugins
cp -r $QT_MACOS_PATH/Plugins/ to App/Contents/Plugins/
Resources/qml
mkdir App/Contents/Resources/qml
cp -r $QT_MACOS_PATH/qml/ to App/Contents/Resources/qml/
Frameworks
cp -r $QT_MACOS_PATH/li... |
72,133,602 | 72,133,778 | Stationary element of matrix | I'm trying to write a function which will check if matrix has (at least one) stationary elements. An element of a matrix is stationary if its value is equal to the value of the elements located to the left, right, above and below it.
#include <iostream>
#include <vector>
bool Stationary(std::vector < std::vector < int ... | The problem is that you check the edges of the matrix and in a position like a[0][0] you step out of bounds when checking a[-1][0] and a[0][-1]. Instead start your loops at 1 and end at size() - 2 (inclusive).
Another suggestion is to not take the matrix by-value which copies the whole matrix. Take it by const& instead... |
72,133,687 | 72,133,808 | QT5 - Detecting when new files are added to a directory and retrieving their path | My problem is relatively simple. I have an application where I need to monitor a particular folder (the downloads folder, in my case) for added files. Whenever a file is added to that folder, I want to move that file to a completely different directory. I have been looking at QFileSystemWatcher; however, none of the... | You’ve hit the limit of what the underlying OS provides: notification of change to the content of a directory.
If you wish to identify the file:
deleted you must have a prior list of files available for compare
added same as deleted
modified loop through the directory for the file with the most recent last modified da... |
72,133,917 | 72,133,974 | C++ structure reference from member reference | Given the following setup...
struct A {unsigned char _data;};
struct B {unsigned char _data;};
struct C {A a; B b;};
// in this context (ar) is known to be the "a" of some C instance
A& ar = ...;
B& br = get_sister(ar); // the "b" of the same C instance that (ar) belongs to
C& cr = get_parent(ar); // the C instance th... | Only if you know for a fact that ar is referencing a C::a member, then you can use offsetof() (which should return 0 in this case, since a is the 1st non-static data member of C, but best not to assume that) to help you access the C object, eg:
C& get_parent(A& ar)
{
return *reinterpret_cast<C*>(reinterpret_cast<ch... |
72,134,088 | 72,285,933 | multiple definition of `std::logic_error::logic_error(std::logic_error const&) | I am cross-compiling a windows application from my Linux host machine and I am getting a linking error of multiple definitions between two files in the std!
/usr/lib/gcc/i686-w64-mingw32/7.3-win32/libstdc++.a(cow-stdexcept.o):(.text$_ZNSt11logic_errorC2ERKS_+0x0): multiple definition of `std::logic_error::logic_error(s... | Building the code with CXX_FLAGS += -D_GLIBCXX_DEFINE_STDEXCEPT_COPY_OPS solved the issue.
by looking at the symbols of test.o using nm -C test.o, I found that the copy constructor was defined and had an address mentioned next to it, I made an assumption that the compiler automatically created the copy constructor for ... |
72,134,259 | 72,146,392 | in-tree include directory with bazel custom toolchain | Is it possible to configure a Bazel custom toolchain to include directories in the repository?
Assume that I have following in the root of my repository:
sysroots/armhf/include/myheader.h
sysroots/amd64/include/myheader.h
myproject1/component.cpp
myproject2/component.cpp
I'd like to configure toolchain such that when... | If you haven't found it yet, you need to write C++ toolchains. The Configure C++ Toolchains Tutorial is a good place to start, if you have more specific questions they'll get better answers as separate questions. I'm going to answer specifically about the paths here.
Most of the paths are just normal paths relative to ... |
72,134,451 | 72,134,571 | Make functions instantiate its generic parameter | What would be an equivalent to the following C++ program in rust?
#include <iostream>
#include <vector>
template <typename T>
T stuff() {
return T();
}
int main() {
std::vector<int> vec = stuff<std::vector<int>>();
vec.push_back(1);
for (auto &&i : vec) {
std::cout << i << std::endl;
}
}
I... | Maybe there was a mixup when you entered the code that you say gave you the error you provided, because that same code did not yield that specific error when I tried it.
Either way, you were close. Consider this code:
trait Newable {
fn new() -> Self;
}
fn stuff<T: Newable>() -> T {
T::new()
}
#[derive(Debug)... |
72,134,789 | 72,134,831 | Error Missing Type specifer - int assumed . Note C++ does not support default init | In order to make two objects, User1 and User2, of a class User sending and receiving messages,
#include <iostream>
using namespace std;
class reply
{
public:
User* sender;
};
class User
{
BlockingQueue<Message > queue;
public:
void sendMessage()
{
};
void run()
{ //......
}... | You have to add a forward declaration of player before Message
class Player; <<<<=====
class Message
{
public:
Player* sender ;
std::string text;
};
see here for explanation What are forward declarations in C++?
and yes - it should be std::string
|
72,135,134 | 72,135,568 | Pointer to const object as a data member | Accordingly to C++ best practices on IsoCpp we shouldn't have a const or reference data member: C.12: Don’t make data members const or references
But it does not specify if a pointer to a const object is allowed or not. Consider the example:
class Connection {
gsl::not_null<const Network*> m_network;
...
publi... | It depends.
The reason this recommendation exists, is to make your type copyable and assignable, with both having matching semantics.
So consider this:
struct Connection {
Network const& network;
/**/
};
Copying this is perfectly fine, right? But then assigning breaks because network will not be reseatable.
So in ... |
72,135,880 | 72,136,171 | why can't compare string in #if expression in c++ | i want to write code like this but i can't:
#define COLOR "red"
#define RED "red"
#define BLUE "blue"
int main()
{
// following code can't be compiled
#if (COLOR==RED)
cout<<"red"<<endl;
#endif
// following code can work
if(COLOR==RED)
cout<<"red"<<endl;
else
cout<<"notred"<<endl;
}
so how can i real... | Because #if only works with integers
expression is a C expression of integer type, subject to stringent restrictions. It may contain...
see https://gcc.gnu.org/onlinedocs/gcc-3.0.1/cpp_4.html#SEC38
|
72,135,948 | 72,175,346 | Is seastar::thread a stackful coroutine? |
Seastar allows writing such code, by using a seastar::thread object
which comes with its own stack.
The seastar::thread allocates a 128KB stack, and runs the given
function until then it blocks on the call to a future's get() method.
Outside a seastar::thread context, get() may only be called on a
future which is alre... | Yes, seastar::thread and "stackful coroutines" are indeed very similar concepts.
Note that Seastar also supports stackless coroutines, using the new C++20 coroutines feature. This is now almost always preferable over stackful coroutines (seastar::thread): stackless coroutines are lighter and are useful also in heavily ... |
72,136,018 | 72,136,074 | "auto" keyword: How to customize it? | Title is vague, I know. Consider this:
template<typename T>
using Ref = std::shared_ptr<T>;
template<typename T>
using StrongRef = std::shared_ptr<T>&;
struct Person {
std::string m_name;
Person(const std::string& l_name) : m_name(l_name) {}
};
class Container{
Ref<Person> m_person;
public:
People(co... | You can tell auto you want a reference like
auto& person = container.GetPerson();
This does have one drawback though as if GetPerson changes to return by value, then you are trying to bind an lvalue reference to an rvalue and that will result in a compiler error.
To get around this, you can use a forwarding reference ... |
72,136,026 | 72,136,051 | Boolean function returning 24, and acting inconsistent across multiple compilers | Alright, this is driving me nuts and I have no idea what's going on. I have some code I'm making for school that basically takes in a string and a start and end index, and spits out true if the string is a palindrome, and false if it isn't. I added some extra stuff to make sure that it works if you give it a sentence w... | you are not returning a value from isPalindrom, - your compiler is surely warning you about it, mine did
1>C:\work\ConsoleApplication1\ConsoleApplication1.cpp(68): warning C4715: 'isPalindrom': not all control paths return a value
you probably - its your logic - just want
if (tolower(str[start]) == tolowe... |
72,136,127 | 72,136,617 | std map access element while creating new one thread safety | If I have a map<int, Fruit> x. On one thread I try to read the data of one element x[10].type, while on another thread I create a new element Fruit &new_fruit = x[7]. Is this thread safe? Since from what I can understand as long as it is not the same key/element it should be fine.
| You're probably referring to iterator invalidation, when you say that from what you understand, it's safe as long as you're not reading/writing to the same key from different threads.
However, thread safety doesn't work like that. Unless it is explicitly guaranteed (or proven,) you must assume that this kind of access ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.