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 |
|---|---|---|---|---|
67,979,485 | 67,980,137 | How to fix this shared_ptr reference cycles? | I designed an App that holds a stack of layers and an active obj.
When a Layer is attached to the App, the Layer tells App what an active object is. But my design causes a sigtrap when deallocating.
It cause sigtrap because the destruction of shared_ptr<Obj> m_obj in App happens first which reduce the use_count to 1. T... | You're accessing m_activeObj after its lifetime has ended, and thus the behavior of your program is undefined.
The sequence of events is as follows:
App object goes out of scope
~App runs
m_activeObj is destroyed; after this its lifetime has ended and it can no longer be accessed
m_defaultLayer is destroyed
m_stack is... |
67,979,854 | 67,980,103 | My program is exiting with return value 3221225620 | I have written a cpp code for array rotation and the file handling part is a bit tricky for me.
The code itself is correct but even though the files are in the same directory as the code it is not working for some reason
#include <math.h>
#include <algorithm>
#include <bits/stdc++.h>
#include <iostream>
#include <fstre... | here shows a possible error:
3221225620 (0xC0000094): Zero Division Error
means that a divisor in your code could sometime be zero.
as for your code(line 20: d = d % n;), when your n is 0, the output will show return value 3221225620
so please check your data in "input.txt"
|
67,980,026 | 67,982,763 | boost flat_map batch insertion | I have a C++ program that maintains a boost::flat_map. It receives real-time commands in the form of (key, value). If value is 0, then the flat_map[key] should be deleted if it exists. If value is nonzero, then the flat_map[key] should be set to value in the flat_map if the entry already exists, or it should be inserte... | You can use extract_sequence / adopt_sequence to update the underlying vector, and so long as it ends up ordered and uniqued, there's only a pair of vector moves in overhead.
auto underlying = my_map.extract_sequence();
// merge underlying and batch
my_map.adopt_sequence(boost::ordered_unique_range_t{}, std::move(und... |
67,980,176 | 68,317,034 | Caching images in c++. Using buffer_body or other things instead of file_body? | I have slightly modified version of this https://www.boost.org/doc/libs/develop/libs/beast/example/http/server/async/http_server_async.cpp.
What it does:
According to the correctness of the request it returns the required image or an error.
What I'm going to do:
I want to keep frequently requesting images in local cach... | Sometimes there is no need to cache these files, for example, in my case changing file_body to vector_body or string_body were enough to speed up respond time almost twice
|
67,980,240 | 67,980,523 | Cout from class method does nothing | I have a class "beaker" that represents a beaker with n-dices that have n-faces. It has a method "roll" which returns a vector with n-elements where each element represents a dice. Then I have another class "board" that for now, it only prints the values generated by beaker.roll using cout;
So I call the beaker.roll fu... | The problem is that the values in dice are of type uint8_t, which the cout::<< operator is interpreting as unsigned char, so it is printing out the values as ASCII characters. However, the values are between 1 and 6, and ASCII characters less than 32 are mostly non-printing characters, so they aren't visible in the ou... |
67,980,273 | 67,980,470 | Unable to initialize const unordered_map<string, variant<int, float>> using initializer list | So here is the function:
void spawn(const param ¶) {
// ...
}
The param is typedef std::unordered_map<std::string, std::variant<int, float>> param;
And here is how i call it:
spawn({{"x", 450}, {"y", 324}, {"vel", 1.0}, {"increaser", 0.05}, {"direction", 120}});
And here is the error:
no instance of construct... | The value type of your unordered_map is std::variant<int, float>, but in your brace init list, you're passing float instead of a double. This conversion from float to a variant is not allowed.
Either change your value type to std::variant<int, double>, or pass literals of float type, e.g. 1.5f instead of 1.5.
The minim... |
67,981,526 | 67,982,241 | How to enable/disable a member function according to the existence of a member of its derived class? | I had searched over 10 answers and nothing fits my current situation.
(member detector marcos comes from: http://en.wikibooks.org/wiki/More_C++_Idioms/Member_Detector)
CREATE_MEMBER_DETECTOR(normal);
CREATE_MEMBER_DETECTOR(abnormal);
template <typename T>
struct Weapon
{
//template <std::enable_if_t<Detect_normal<... | You would need the template parameter from the method for SFINAE:
template <typename T>
struct Weapon
{
template <typename U = T, std::enable_if_t<Detect_abnormal<U>::value, bool> = true>
void DefaultShoot()
{
std::cout << "special\n";
}
template <typename U = T, std::enable_if_t<Detect_nor... |
67,981,706 | 67,982,353 | Does C++ 17 STL std::string_view fulfill RAII design philosiphy? | In RAII(Resource Acquisition Is Initialization), an object obtain piece of resource is the procedure of initialization itself, and resource will be held as life cycle of object, but resource in string_view only includes char * and size, which means the address could be free to invalidation and object couldn't be consci... | std::string_view doesn't Acquire Resource, it is not a RAII object.
|
67,981,912 | 67,981,963 | How to create an invalid QModelIndex? | I am implementing a function which searchs a QModelIndex based on a QString input.
However if I cannot find this index, the function should retun an invalid index.
My model is a QStandardItemModel.
Is is okay to return invisibleRootItem()->index() as an invalid index?
In the qt documentation is noted that it will alway... | You must use the default constructor of QModelIndex(e.g. return QModelIndex()) which is null as indicated in the docs:
QModelIndex::QModelIndex() Creates a new empty model index. This type
of model index is used to indicate that the position in the model is
invalid.
(emphasis mine)
|
67,982,354 | 67,982,621 | How to fix DimensionError? | I am having a strange error still could not figure it out.
#include <iostream>
#include "fusion.h"
using namespace mosek::fusion;
using namespace monty;
int main(int argc, char ** argv)
{
int number_of_steps = 7;
int lambda1 = 1000;
int lambda2 = 1000;
int dim_space = 3;
auto A = new_array_ptr<double, 2>({... | The shape of b is (1,10) and the shape of the expression is (10). It will work if you do
auto b = new_array_ptr<double, 1>({0.3597,
0.8894,
0.9238,
0.9682,
0.9534,
... |
67,982,764 | 67,984,066 | Why comparing a small floating-point number with zero yields random result? | I am aware that floating-point numbers are tricky. But today I encountered a case that I cannot explain (and cannot reproduce using a standalone C++ code).
The code within a large project looks like this:
int i = 12;
// here goes several function calls passing the value i around,
// but using different types (due to ... | Barring the undefined behavior which can be easily be fixed, you're seeing the effect of denormal numbers. They're extremely slow (see Why does changing 0.1f to 0 slow down performance by 10x?) so in modern FPUs there are usually denormals-are-zero (DAZ) and flush-to-zero (FTZ) flags to control the denormal behavior. W... |
67,982,842 | 68,037,999 | How can Objc/C++ project compilation time be profiled/optimized? | My Objc/C++ project compilation time is too long.
Even when Xcode is doing an incremental build, it can take e.g. 140s = 2.5 minutes.
The problem is, 2.5 minutes for an incremental build says me nothing of what can be improved.
E.g. Xcode Report Navigator shows that some file is compiled in 4.2s:
How can I check if th... | For a single compilation unit, Clang has -ftime-trace argument to activate time profiler.
It will generate a JSON file that can be visualized as a flamegraph, for example in chrome://tracing
The compilation time is split between frontend and backend. You can review all the headers included, and the time spent on parsi... |
67,983,176 | 67,984,224 | C# call to C and pass parameter as a pointer to an array | I have a C method with the following signature:
extern __declspec(dllexport) int my_func
(const double(*points)[3], double parameters[MAXPARS], int* numberofparameters);
This function is part of a .lib, which I'm wrapping in a DLL (CLR/CLI) written in C++, so that I can call from C#.
The signature of the C++ metho... | If you already have a C++/CLI wrapper, I would adjust the API there and make that one more C#-ish.
So change the C++/CLI declaration to something like:
int MyFunc(array<double>^ points,
array<double>^ parameters);
and then do all the managed->unmanaged wrapping in that implementation.
In the end, it would ... |
67,983,593 | 67,993,510 | menu bar functionalities aren't working in Qt | so i am writing a simple video player program and i did the same steps as the lesson i am taking but when i run the program and click on functionalities like end (which is close()) and open (open file) they dont work, i used the slot triggering as per the lesson although i saw different ways of using the menubar here b... | am pretty sure this instruction here:
connect(meinPlayer, SIGNAL(mediaChanged(QMediaContent)), this, SLOT(listeUndTitelAktualisieren()));
is not located where it should coz you are connecting the signal toa slot INSIDE of the SLOT implementation....
try moving that to the constructor of dein videoWidget
|
67,983,806 | 67,983,942 | STL and std custom compare arguments working in c++ | I asked this question on stackoverflow STL passing object
I got to know that we pass objects which in tern call the compare operator in them and compare our values and gives us a result. All good.
Now in this piece of code:
class Compare {
public:
bool operator ()(const int &a, const int &b) { return a < b;}
};... | In the first code snippet the compiler issues an error because you was using an object Compare() as the type template argument instead of the type Compare.
If you will write for example
#include <iostream>
#include <vector>
#include <set>
using namespace std;
class Compare {
public:
bool operator ()(const int... |
67,984,036 | 67,985,922 | Concept as_same identity fail | I have a nice type traits that check if a type T is an iterator:
demo: https://wandbox.org/permlink/vUZ2hjQq6i9nlXFd
stack post with explanation: https://stackoverflow.com/a/67822208/9063139
I try to do the same but with concept. My first attempt was:
template<typename T>
concept isIterator = requires(T a) {
{ ty... | It fails with std::vector<int>::iterator and int* because:
std::iterator_traits<int*>::reference == int&
std::iterator_traits<const int*>::reference == int&
int&{} does not compile (where const int&{} does)
So { typename std::iterator_traits<T>::reference{} } fails for these types. It can be fixed with :
{ std::decl... |
67,984,171 | 67,984,366 | Reference const to bitfield value | Is it safe to create a reference const to a bitfield value?
Have a look in the following example
typedef struct
{
int a:1;
}x_t;
int main() {
x_t x;
bool const & x2 = x.a;
}
|
Is it safe to create a reference const to a bitfield value?
Yes, it's like the same as if you would write for example:
bool const& x3 = 42;
In your code the value of x.a is taken and a temporary object of type bool is created with the value of x.a assigned to it and then the reference is bound to that temporary obje... |
67,984,577 | 67,986,895 | C++ multiple parameter packs grouped by name | I am currently trying to write some ECS in C++. Inside my ECS (Entity component system), I have a set of entities which all have a set of components. Like a position, rotation, etc.. What I want to do is implement a function which returns an iterator to iterate over the entities which fullfill a few requirements. These... | common solution:
template<typename...>
struct required;
template<typename...>
struct requires_one;
template<typename...>
struct excludes;
template<typename, typename, typename>
struct ECS_each_impl;
template<typename... RTypes, typename... ROTypes, typename... XTypes>
struct ECS_each_impl<required<RTypes...>, requires... |
67,984,603 | 67,984,728 | My variadic templated constructor hides copy constructor, preventing the class to be copied | I made a Vector<numType, numberOfCoords> class. I was happy with it, it's kinda weird but it seemed to work at the start. But I just found out copying the vectors is impossible.
The reason is that to allow the number of coordinates to be a template, there is a templated variadic constructor which expects the right numb... | You might:
SFINAE your variadic constructor, for example:
template <typename... NumTypes,
std::enable_if_t<sizeof...(NumTypes) == Size
&& std::conjunction<std::is_same<NumType, NumTypes>::value,
int> = 0>
constexpr Vector(NumTypes&&... vals) : values{ std::for... |
67,984,761 | 67,985,013 | I can't understand why does my pthread freeze | I was trying to create a thread safe queue, but something went wrong. I can't understand why does my thread freeze.
Expected: 1 2 3, but i get nothing (everything just freezes)
I guess the problem is misuse of condition variable in front (pop) and get (peek) methods, but I can't find my mistake.
Could you please point ... | This is your front :
template<class T>
T SafeQueue<T>::front(){
pthread_mutex_lock(&_mutex);
T temp;
while(!get(temp)){
pthread_cond_wait(&_condition, &_mutex);
}
pthread_mutex_unlock(&_mutex);
return temp;
}
It locks the mutex, does some stuff, releases the mutex. As part of "some st... |
67,985,309 | 67,985,347 | error segmentation fault in dynamic array | I am solving this problem on dynamic array in which input first line contains two space-separated integers,n, the size of arr to create, and q, the number of queries, respectively.
Each of the q subsequent lines contains a query string,queries[i]. it expects to return int[]: the results of each type 2 query in the ord... | You are accessing elements of vector without allocating them.
resize() is useful to allocate elements.
#include<iostream>
#include<vector>
using namespace std;
//The function is expected to return an INTEGER_ARRAY,fuction accepts parameter 1) INTEGER n & (2) 2D_INTEGER_ARRAY queries
vector<int> dynamicArray(int n, vect... |
67,985,606 | 67,988,561 | Read/write Eigen::Matrix with cv::Filestorage | According to the OpenCV Docs, we can use cv::FileStorage to read/write custom data structure from/to config files (XML, YAML, JSON):
#include <opencv2/opencv.hpp>
#include <Eigen/Core>
class MyData { };
static void read(const cv::FileNode& node, MyData& value,
const MyData& default_value = MyData()) { }
int main... | The issue is due to the intruduction of namespace, indeed you can get a similar issue with this code:
#include <opencv2/opencv.hpp>
namespace X
{
struct MyData {};
}
static void read(const cv::FileNode& node, X::MyData& value,
const X::MyData& default_value = X::MyData()) { }
int main()
{
cv::FileStorage fs;
... |
67,985,805 | 67,986,409 | Is it necessary to use synchronization between two calls to CUDA kernels? | So far I have written programs where a kernel is called only once in the program
So I have a kernel
__global__ void someKernel(float * d_in ){ //Any parameters
//some operation
}
and I basically do
main()
{
//create an array in device memory
cudaMalloc(......);
//move host data to that array
cudaMemcpy(.... | Additional synchronization would not be necessary in this case for at least 2 reasons.
cudaMemcpy is a synchronizing call already. It blocks the CPU thread and waits until all previous CUDA activity issued to that device is complete, before it allows the data transfer to begin. Once the data transfer is complete, the... |
67,986,039 | 70,720,174 | QtCharts module not found even after installing in Qt Maintenance | I know that there're many questions regarding this aspect:
QML module not found (QtCharts)
How to include the QtCharts library in Qt Creator 4.2.0 (Community)
How to fix "QtCharts" library file not found/can't include <QtCharts>?
Importing QtCharts in QML causes module not installed error
Many more...
But most of the... | It seems you have only installed Qtcharts in the Additional libraries section.I know it's showing 0mb installation which is useless.
Select the QT section which is below the additional libraries section. Then select the version you have installed. Under the selected version there is a QT charts module, select it and i... |
67,986,573 | 67,989,987 | Why does this program runs in a container but not on the host? | I am doing a very simple docker image with a c++ written program that says hello.
I had to build the executable from a virtual machine, Ubuntu 18.04, x86-64.
I launched this executable on another machine, a Windows 10 64 bits via cmd, but it throws the following:
hello.exe n’est pas compatible avec la version de Windo... | Your Dockerfile uses "scratch" image, which is a minimal (with very basic binaries to reduce the size).
According to Docker Hub, the scratch image is Docker’s reserved empty
image, which is useful in the context of building base images (such as
debian and busybox) or super minimal images. As of Docker 1.5.0, FROM
scra... |
67,986,592 | 67,986,654 | Function which can dynamically allocate matrix | I'm trying to create a function which I can use to dynamically allocate and input values of a matrix, and another matrix to output the results.
I get an error, saying my matrix is not an array, pointer or vector.
#include <iostream>
using namespace std;
double data_entry_matrix(int ARows, int ACols);
void output_mat... | You have to return and hold the pointer double**, not single double.
#include <iostream>
using namespace std;
double** data_entry_matrix(int ARows, int ACols); // change return type to return a pointer
void output_matrix(double **A, int ARows, int ACols);
int main()
{
int ARows=3;
int ACols=3;
cout... |
67,986,877 | 67,986,983 | Is there a way to perform arithmetic on integer which has been converted from a string cpp | So basically I am getting two string inputs in the form of coordinates as (x,y) and then I am adding the numbers from the inputted string (which are p1 and p2) to different variables and then adding those variables (which are x1,x2,y1,y2). So is there a way to add the variables together i.e perform arithmetic on the va... | You can do this with std::stoi(). Add a line to put these strings into int variables and do your arithmetic:
int x = stoi(x1);
|
67,987,003 | 67,987,411 | policy base design: conditionally change a member variable from policy class | My program defines an Animal struct that can be configured with CanSwim/CanNotSwim and CanBark/CanNotBark:
#include <iostream>
struct CanSwim {
};
struct CanNotSwim {
};
struct CanBark {
CanBark() : volume(10) {}
void bark() {
std::cout << "bark at volume " << volume << std::endl;
}
void set... | With CRTP, you might got that information:
struct CanSwim {};
struct CanNotSwim {};
template <typename Der>
struct CanBark {
CanBark() : volume(std::is_base_of_v<CanNotSwim, Der> ? 20 : 10) {}
void bark() {
std::cout << "bark at volume " << volume << std::endl;
}
void setVolume(int newVolume) ... |
67,987,246 | 67,987,273 | Problem with printing a dynamic 2d array (execution problem) | I've written this code down here but my problem is whenever i hit the run button and execute my program the values are fine but every element of the 2D array is printed out in a separate line, it's not printing a square with area its dimensions (size n x n) like i wanted, how can i fix this?
my code
it should be like t... | You placed the line
cout << "]" << endl;
at a wrong place. It should be after the inner loop, not inside that.
void showCurrentIteration(char **surface, int dimensions)
{
int rows, cols;
for (rows = 0; rows < dimensions; rows++)
{
cout << "[";
for (cols = 0; cols < dimensions; cols++)
... |
67,987,298 | 67,988,432 | boost python code involving both static and overloaded member functions | I'm trying to compile some boost python code involving both static and overloaded member functions. Any hint? I just can't get it compiled using pointers on functions (never done it before) but may be there is another track to follow?
#include<iostream>
#include <boost/python.hpp>
#include <boost/python/raw_function.hp... | The following changes worked for me:
You need #include <string> to use std::string. You also do not need to assign your function pointers as members of ORM, along with just having the parameter types in your function pointer assignments. When you declare BOOST_PYTHON_MODULE() the input must match your library name (ie ... |
67,987,495 | 67,987,763 | How to initialize member variables before inherited classes | I'm trying to make one class which requires member variables to be initialized first. I know why this happens, but is there a way around this?
Current print order:
second
first
Wanted print order:
first
second
#include <iostream>
struct A {
A() {
std::cout << "first" << '\n';
}
};
struct B {
B() {... | Stick your members that need initializing first in a struct and inherit privately from that, before B.
struct A {
A() { std::cout << "first" << '\n'; }
};
struct B {
B() { std::cout << "second" << '\n'; }
};
struct Members { A a; };
struct C : private Members, public B {
C() : Members(), B() {}
};
int m... |
67,988,167 | 67,989,848 | What happens if multiple WillRepeatedly actions are specified on a google mock? | I have this kind of test setup:
for (...)
{
std::unique_ptr<MockObject> mock = std::make_unique<MockObject>();
const SomeObject* validObject = ...;
EXPECT_CALL(*mock, method(_)).WillRepeatedly(Return(validObject));
}
Is this guaranteed to return the validObject object local to the scope of the current for?... | For this example, each iteration of the for loop makes a new MockObject mock.
The EXPECT_CALL....WillRepeatedly line will set the return value for this method of that mock object only to whatever validObject points to.
would it behave the same if the mock was declared outside the for?
Yes, at least this part of the t... |
67,988,250 | 67,988,373 | Segmentation fault while calculating the intersection of two sets | I need to find the intersection of two arrays and print out the number of elements in the intersection of the two arrays. I must also account for any duplicate elements in both the arrays. So, I decide to take care of the duplicate elements by converting the two arrays into sets and then take the intersection of both t... | set_intersection does not allocate memory: https://en.cppreference.com/w/cpp/algorithm/set_intersection
You need a vector with some space. Change vector<int> v; to vector<int> v(n+m);
https://ideone.com/NvoZBu
|
67,988,506 | 67,990,364 | Magnification Windows API - How to add Smoothing/Anti Aliasing | Context
Since Windows 10 version 2004 update, the Magnifier windows application was updated.
And as with every update, there are some issues with it.
Since those issues might take a long time to fix, I've decided to implement my own small project full screen magnifier.
I've been developing in c#, .Net 4.6 using the Mag... | There is no public interface in the Magnification API that allows clients to apply filtering (other than color transforms). This used to be possible, but the MagSetImageScalingCallback API was deprecated in Windows 7:
This function works only when Desktop Window Manager (DWM) is off.
Even if it is still available, it... |
67,988,828 | 67,999,951 | Why is Python recursion so expensive and what can we do about it? | Suppose we want to compute some Fibonacci numbers, modulo 997.
For n=500 in C++ we can run
#include <iostream>
#include <array>
std::array<int, 2> fib(unsigned n) {
if (!n)
return {1, 1};
auto x = fib(n - 1);
return {(x[0] + x[1]) % 997, (x[0] + 2 * x[1]) % 997};
}
int main() {
std::cout << fi... | A solution is a trampoline: the recursive function, instead of calling another function, returns a function that makes that call with the appropriate arguments. There's a loop one level higher that calls all those functions in a loop until we have the final result. I'm probably not explaining it very well; you can find... |
67,990,344 | 68,062,544 | 32bit Application run 64bit registry (with WOW6432Node) | I have a 32bit application that must call C:\Windows\System32\regedit.exe, but instead it runs C:\Windows\SysWOW64\regedit.exe. How can I call the regedit in System32?
void CSecureShellView::OnCommandsRegistry64bit()
{
STARTUPINFO si = { sizeof(si) };
PROCESS_INFORMATION pi;
CString szExe;
szE... | To solve this problem I use ShellExecuteEx() and SHELLEXECUTEINFO.
HRESULT result = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
SHELLEXECUTEINFO Sei;
ZeroMemory(&Sei,sizeof(SHELLEXECUTEINFO));
Sei.cbSize = sizeof(SHELLEXECUTEINFO);
Sei.lpFile = "C:\\windows\\regedit.exe";
Sei.nShow = SW_SHO... |
67,990,349 | 67,990,721 | Check if a vector contains object with already entered values | so I'm struggling with these things:
I have method that returns istream input and takes istream input as a parameter, sends values to vector and stores them in it. Now, when I've entered 1 value, I'm trying to make a check if vector already contains that value, here is my code to understand it better:
struct Predmet {
... | first of all, you can check count of std::vector to see if given key exists
//std::count(v.begin(), v.end(), key)
if (std::count(v.begin(), v.end(), key)){
//it is inside
}
else{
//it isn't inside
}
This is one way to go, but you should do the map
std::map<std::string,int> myMap;
//adding will look like this
s... |
67,990,913 | 67,993,104 | VSC - IntelliSense marks boolean operator as errors | IntelliSense is incorrectly marking boolean operators (and, or, etc.) As errors. Here is an example:
This is my c_cpp_properties.json:
{
"configurations": [
{
"name": "Win32",
"includePath": [
"${workspaceFolder}/**"
],
"defines": [
... | With Visual C++, it looks like you need to add #include <iso646.h>.
C++ specifies bitand as an alternative spelling for &. In C, the alternative spelling is provided as a macro in the <iso646.h> header. In C++, the alternative spelling is a keyword; use of <iso646.h> or the C++ equivalent is deprecated. In Microsoft ... |
67,990,936 | 67,993,785 | 2D array traversal coding problem C++/ recursive function not returning correct value | I have been trying to solve a puzzle which asks whether it is possible for a king (in chess) to walk to a target square without passing through a square covered by a queen, given the input of the board size, the queen x and y, the king x and y and the target x and y. I have written a (very inefficient) recursive functi... | Returning a non-zero return code makes it seem like it's crashing somewhere. A good practice when writing homework code is to use vector.at(i) instead of vector[i] since the former will throw an exception when it's out of bounds (rather than just randomly accessing memory). When I did that I found the visited vector wa... |
67,990,979 | 67,994,287 | C++ String to Number Custom function problem | I am trying to convert a string to number(long double) in C++. The problem arises when the number of digits after decimal point is greater than 3. It automatically rounds-off the to the nearest third digit after the decimal.
Additional info:
compiler: mingw
os: win10
Here's the code (test.cpp):
#include<iostream>
#in... | The default precision of std::cout is 6 as set by std::ios_base::init. So
auto val = 1234.56789;
std::cout<<val<<'\n`;
yields 1234.57 i.e. 6 digits (and rounds it accordingly). Set the precision accordingly using setprecision from the iomanip header and you should be able to see the correct value.
std::cout << std::se... |
67,991,228 | 67,991,465 | C++ function template argument deduction | I have a class template for the smart pointers of which I want an operator+()
template<typename T, typename U>
class Foo{};
template<typename T, typename U>
std::unique_ptr<Foo<T,U>> operator+(std::shared_ptr<const Foo<T, U>>, std::shared_ptr<const Foo<T, U>>);
I now want the following to work with tempate argument d... | Implement a template taking const references to Foo and then create another template using arbitary parameters that use this implementation.
The following creates always returns unique_ptr containing a default initialized Foo.
template<typename T, typename U>
class Foo{};
template<typename T, typename U>
std::unique_p... |
67,991,595 | 67,992,194 | Modifying private pointer of object within same type (but different object) public method | I've been attempting to create a node class which mimics a node on a graph. Currently, storage of the predecessor and successor nodes are stored via a node pointer vector: std::vector<Node*> previous. The vectors for the predecessor/successor nodes are private variables and are accessible via setters/getters.
Currently... | I think this should get you going (edge-cases left to you to figure out, if any):
template<typename T>
class Node {
// Everything made public for debugging purposes, change this to fit your needs
public:
std::vector<Node<T>*> previous;
std::vector<Node<T>*> next;
T data;
Node(T val) {
data = va... |
67,991,685 | 67,991,712 | unknown type name 'GsetBrakeMode' in seemingly working code | In some IDEs I am given an error for this yet in others it works fine. I would like to know what the problem is and what i can do to fix it.
typedef enum custom_brake
{
BRAKE_COAST = 0,
BRAKE_BRAKE = 1,
BRAKE_HOLD = 2
} TokenType;
void GsetBrakeMode(custom_brake brakeMode){
switch(brakeMode){
case BRAKE_C... | GsetBrakeMode(BRAKE_HOLD); is a function call. You cannot place that outside function body without some trick.
Place that inside some function body like this:
void someFunc(void) {
GsetBrakeMode(BRAKE_HOLD);
}
One of the trick to write that outside function body is placing that in an expression to determine initia... |
67,991,707 | 67,991,853 | Clang failing to find header files in non-standard location | I am currently trying to build OpenPose. First, I will try to describe the environment and then the error emerging from it. Caffe, being built from source, resides in its entirety in [/Users...]/openpose/3rdparty instead of the usual location (I redact some parts of the filepaths in this post for privacy). All of its i... | You are using cmake. The makefiles generated by cmake don't conform to "standard" makefile conventions; in particular they don't use the CXXFLAGS variable.
When you're using cmake, you're not expected to modify the compiler options by changing the invocation of make. Instead, you're expected to modify the compiler op... |
67,992,367 | 67,992,510 | In C++, does Initializing a reference or pointer with itself cause UB? | int &r1 = r1; // r1 0 initialized, `r1` references 0, not UB?
int *p1 = p1; // p1 0 initialized, `p1` is a null ptr, not UB?
int main() {
int &r2 = r2; // reference to intermediate value. has UB ?
int &r3 = r2; // Also has UB ?
int *p2 = p2; // pointer to garbage location. has UB ?
int *p3 = p2; // Also has UB ?... |
// namespace scope
int *p1 = p1; // p1 0 initialized, `p1` is a null ptr, not UB?
Standard is ambiguous regarding this case, but "not UB" could reasonably be argued due to the static initialisation that precedes the dynamic initialisation. On the other hand standard implies that lifetime of the object hasn't started... |
67,992,406 | 67,992,621 | Why is an external template redeclared as a "different kind of entity"? | So I'm trying to share a templated global variable between translational units.
There is a common strategy to do this for functions where you have one header declaring/implementing the template and second C++ file that explicitly enumerates all arguments to actually generate the code for the linker.
The original versio... | You can do one of the two things.
Make pool a normal variable.
extern PoolType<int> pool;
// in some other file
PoolType<int> pool;
// in main
pool.do_something();
Make pool a variable template.
template <class T> extern PoolType<T> pool;
// in some other file
template <> PoolType<int> pool<int>;
// in main
pool<int... |
67,992,478 | 67,993,135 | boost::asio::async_write_some - sequential function call | I am writing an application using boost.asio. I've an object of type boost::asio::ip::tcp::socket and (of course) I've boost::asio::io_context which run's function was called from only one thread. For writing data to the socket there are a couple of ways but currently I use socket's function async_write_some, something... |
no; the reason for that is probably documented with the underlying sockets API (BSD/WinSock).
not applicable. Note that the order in which handlers are invoked is guaranteed to match the order in which they were posted, so you could solve it using an async chain of async_write_some calls where the completion handler ... |
67,993,077 | 67,993,207 | How to resolve "Delphi style classes have to be derived from Delphi style classes"? | If I have a class defined as :
// foo.h
class Foo
{
public:
virtual void GetFoo();
}
And I want a TForm to inherit from it, for example
class TFMainWindow : public TForm, public Foo
{
...
}
I get the error
[bcc32c Error] TFMainWindow.h(36): Delphi style classes have to be derived from Delphi style classes
Ho... | TForm derives from TObject, which is a "Delphi-style class", ie it is implemented in Delphi pascal, not in C++. in Delphi, TObject is the root of all class object instances.
Delphi does not support multiple inheritance of classes, like C++ does. Only single inheritance. A Delphi class can have only 1 base class at m... |
67,993,134 | 68,020,236 | How come the fmt library is not header-only? | I know it is possible to use the fmt formatting library in header-only mode:
How to use fmt library in the header-only mode?
but - why isn't it just header-only, period? That is, what's the benefit of using it in non-header-only mode?
| The main reason is build speed as others already correctly pointed out. For example, compiling with a static library (the default) is ~2.75x faster than with a header-only one:
#include <fmt/core.h>
int main() {
fmt::print("The answer is {}.", 42);
}
% time c++ -c test.cc -I include -std=c++11
c++ -c test.cc -I inc... |
67,993,360 | 68,010,327 | C++ : custom vtable implementation does not work | I'm trying to implement a custom vtable to better understand a concept of virtual tables and overriding. For this I have the following 'base' class
#pragma once
#include <iostream>
#include <string>
using namespace std::string_view_literals;
struct vtable;
class IdentityDocument {
public:
IdentityDocument()
... | Finally I simplified my solution and got what I wanted :
#include <iostream>
class A;
struct VTable
{
void (*say_hello)(A*);
};
class A
{
public:
A()
{
vtable.say_hello = A::sayHello;
}
void sayHello()
{
vtable.say_hello(this);
}
static void sayHello(A* a)
{
... |
67,993,469 | 68,015,474 | Need Help Upgrading xml-security-c-2.0.2 Getting Fatal Error | I'm trying to upgrade xml-security-c-2.0.2. I extracted the tar file on my linux environment. I exported the following xerces environment variables below before the ./configure command:
Env variables:
export xerces_LIBS=/opt/shibboleth-sp/lib
export xerces_CFLAGS=/opt/shibboleth-sp/include
configure command:
./config... | RHEL 7.2 is the year 2015 update. Current is 7.8 (yum update).
XercesDefs.hpp: No such file
xml-security-c-2.0.2 configure will look in /usr/include, /usr/local/include ! When you have a "hide away" location, the INCLUDE path must be specified : See $ ./configure --help
Example : CXXFLAGS=-I/opt/shibboleth-sp/include... |
67,993,769 | 67,993,890 | Primary expression error when defining a vector with ternary operator | I have a simple code where I try to define a vector as one of two initializer lists using a ternary operator:
int main() {
std::vector<int> const vec = true ? {3,4} : {5};
for (int const item : vec) {
cout << item << endl;
}
return 0;
}
But then I see the below primary-expression error:
tmp.cpp... | Because you can't have braces in that context.
If you look at cppreference on list initialization, you see that the case inside a ternary operator isn't defined. So it can't be parsed correctly and you get the error you have.
You'd have to use something like this :
std::vector<int> const vec{(true ? std::vector<int>{3,... |
67,994,521 | 67,994,541 | Iterating over a vector does not update the objects | I'm learning C++ and have come to a bit of a halt. I'm trying to iterate over a vector with a range-based for loop and update a property on each of the objects that belong to it. The loop is inside of an update function. The first time it fires, it works fine; I can see the property gets updated on each member of the v... | Vector3 position = point.position; makes a copy of point.position. The following code then updates this copy, which in turn is thrown away when it goes out of scope at the end of the if statement.
The solution is simple enough - use a reference instead: Vector3 &position = point.position;. The rest of the code can be... |
67,995,083 | 67,995,233 | unresolved external symbol _SDL_main referenced in function _main_getcmdline | This is probably me being stupid but what am I doing wrong here? I'm not sure if I need the code but I'm doing this in Visual Studio 2019.
| Are you sure you specified both assembly versions correctly in the linker? This means both for release and for debug.
Considering that you are using VisualStudio2019, I strongly advise you to use vcpkg - this is a package management made by Microsoft that simplifies the installation of libraries and other features in 1... |
67,995,273 | 67,995,327 | error: expected identifier before 'public' | I'm currently trying to make a GBA game for the GBA Game Jam, anyways I've gotten rid of basically every error when trying to compile I think these last errors are connected to each other though so anyways here's the error that I think there all connected to:
error: expected identifier before 'public'
38 | class gba... | It should be the following:
class B : class A
This will make class B inherit class A.
You have:
class gbaEngine :: public engine
instead of:
class gbaEngine : public engine
|
67,995,381 | 67,995,809 | Does Comparison Function specified with lambda function in std::sort return bool type? | I was reading this code (source):
#include <iostream>
#include <functional>
#include <algorithm>
using namespace std;
int main() {
int number[] = {3, 5, 1, 6, 9};
auto print = [](int n) { cout << n << " "; };
sort(begin(number), end(number), [](int n1, int n2) { return n2 - n1; });
// result: 9 6 1... | The std::sort implementation in libstdc++ has optimized for a short sequence, after checking the source, we know that for a small sequence short than 16 elements, it will fall back to insertion sort.
In c++, the non-zero number can be automatically converted into a bool value true, with insertion sort, if your sequence... |
67,995,709 | 67,995,765 | How do I make sure Types in a variadic Tuple are identical? | I want to create a toString function for Tuples with a variadic amount of a specific type (arithmetic types for now).
Something like this
<template T, typename enable_if<is_arithmetic_v<T>>::type* = nullptr>
toString(tuple<T...> tup)
{
std::stringstream ss;
std::apply([&ss](auto&&... args) {((ss << args << ";... | You can check all the types are identical or not with the help of fold expression (since C++17).
E.g.
template <typename T, // the 1st type
typename... Args, // subsequent types
typename enable_if<... |
67,995,795 | 67,995,850 | My C++ code dosen't accept the characters typed at the keyboard into the array | I'm trying to input some characters into the array but after hitting enter , the terminal would not accept further input.
#include <bits/stdc++.h>
using namespace std ;
int main() {
char Array[5];
for(int i=0;i<5;++i){
cout << "Enter :";
cin.ignore('\n');
cin >> Array[i];
}
for(a... | You don't need the cin.ignore() here:
#include <iostream>
int main() {
char Array[5];
for(int i=0;i<5;++i){
std::cout << "Enter: ";
// No use in cin.ignore() here
std::cin >> Array[i];
}
for(auto data : Array){
std::cout << data << std::endl;
}
return 0;
}
... |
67,996,274 | 67,996,287 | Weird difference between "for(std::vector<int>::iterator it = my_vec.begin(); it != my_vec.end(); ++it)" and "for(int i:my_vec)" | I've seen many forums say that for(std::vector<int>::iterator it = my_vec.begin(); it != my_vec.end(); ++it) and for(int i:my_vec) are the same. But when I ran the following codes (PART A and PART B):
class my_class
{
public:
void increase_age(){age_++;}
private:
int age_;
}
int main()
{
std::vector<my_class> m... | In the (my_class c : my_vec), the c is a copy a corresponding element. Whereas in it->increase_age() you dereference the iterator, which has access to the actual element of the container.
In the case of my_class c, the increase_age() invoked on a local (to the body of the loop) copy. So, no mutation of the elements in... |
67,996,372 | 67,996,399 | Does the C++ standard guarantee anything about algorithms operating on empty containers? | For instance,
#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
int main() {
std::vector<int> empty{};
std::reverse(empty.begin(), empty.end());
std::cout << "Sum: " << std::accumulate(empty.cbegin(), empty.cend(), 0) << std::endl;
std::cout << empty.size();
}
builds and runs as I ... | Since standard library algorithms operate on iterator ranges, algorithms are guaranteed to be safe and valid on any valid iterator range passed to them. Now we only need to be concerned with what valid iterator range stands for.
Requirements on iterators forming an iterator range:
They have to refer to elements (or on... |
67,996,736 | 67,996,838 | getting runtime error in balanced parenthesis code | this is the code I have written to solve balanced parenthesis problem but I am getting runtime error for some hidden test cases and I am unable to find where it is wrong?
can anyone help me find what is wrong in this code and why it is giving me runtime error?
function to find balanced parenthesis I have written as fol... | If you have just ")" (or "]", "}") string as input, you will try to pop an empty stack.
int main() {
std::string demo = ")";
std::cout << ispar(demo) << std::endl;
}
demo : https://wandbox.org/permlink/XgurahYzZY5KIV9U
It usually a good practice to create small test when you code, even better, create your tes... |
67,996,970 | 67,997,010 | Inheritance and Function Arguments | My book covered superficially many test topics from the Object-Oriented domain and I need some explanation and a hint which book does cover such topics.
There's a test question:
#include <iostream>
class A {
public:
virtual void f(int n=2) {// takes the argument value from here
std::cout << n+1 << " in A";... | You have more info here : Can virtual functions have default parameters?
The idea is "the static type of p is A so it will use the default value of A::f"
IMHO, it's a detail and probably not what you should be focusing if you are learning OOP, but it's great you did see it.
|
67,996,974 | 67,997,092 | how to change the value of elements in a QVector of QMaps | I have created a QVector of QMap and pushed some qmaps into the qvector.
QVector<QMap<QString, QString>> * x;
QMap<QString, QString> tMap;
tMap.insert("name", "jim");
tMap.insert("lname", "helpert");
x->push_back(tMap);
tMap.insert("name", "dwight");
tMap.insert("lname", "schrute");
x->push_back(tMap);
after this, I ... | The problem is that the QVector::value function returns the value by value.
That means it returns a copy of the value, and you modify the copy only.
Use the normal [] operator instead to get a reference to the map:
if((*x)[i]["name"] == "target"){
(*x)[i]["name"] = "new value";
break;
}
|
67,996,998 | 67,999,399 | How to deal with the fact that dynamically loaded DLL can be unloaded by Windows even if reference count is not zero? | The documentation says "The system unloads a module when its reference count reaches zero or when the process terminates (regardless of the reference count)."
This causes a significant problem and it's unclear how to solve it. Now about the problem. Suppose we have an executable E that explicitly depends on a DLL libra... |
When handling DLL_PROCESS_DETACH, a DLL should free resources such
as heap memory only if the DLL is being unloaded dynamically (the
lpReserved parameter is NULL). If the process is terminating (the lpvReserved parameter is non-NULL), all threads in the
process except the current thread either have exited already or h... |
67,997,055 | 67,998,920 | can we pass object of a class in different class constructor? | I am a beginner in C++ and badly stuck at creating a constructor of a class that uses the object of another class. while doing so I am getting the error
No matching function for call to ....
Priority_que::Priority_que(graph g) {
for (unsigned i=0; i<g.size(); i++) {
for (unsigned j=i; j<g.size(); j++) {
... | Those are member variables and need to be initialized in the initializer list - you're trying to call them as functions, which is the reason for the error message.
You should also make the parameter a const reference to avoid copying it.
Prio_que::Prio_que(const graph& g)
: parent(g.size(),-1),
dist(g.size(),... |
67,997,648 | 67,999,047 | Template alias not recognized as valid | I've got the following issue:
template<class S>
void setAtIdx(int idx, std::vector<S> toSet) {
cdVec container = cdVec(toSet.size);
std::transform(toSet.begin(), toSet.end(), container,
[](S el) -> std::complex<double>{return std::complex<double>(el);});
if (isHorizontallyPack... | Here S is the name of the template argument:
template<class S> using matS = std::vector<std::vector<S>>;
As an analogy, consider
void foo(int x) {};
foo(x);
The call will not compile, because the name of the argument is largely irrelevant for passing the parameter. If you want to instantiate a matS you either need t... |
67,998,474 | 67,999,005 | arduino ide - concatenate string and integer to char | The following code should work for strings, but does not seem to be working for char arrays.
char *TableRow = "
<div class = \"divTableRow\">
<div class = \"divTableCell\">" + j + "< / div >
<div class = \"divTableCell\" id=\"tm" + i + "b" + j + "\">0< / div >
<div class = \"... | String literals without prefix in C++ are of type const char[N]. For example "abc" is a const char[4]. Since they're arrays, you can't concatenate them just like how you don't do that with any other array types like int[]. "abc" + 1 is pointer arithmetic and not the numeric value converted to string then append to the... |
67,998,835 | 67,999,058 | Is there a way to refer to the class' @brief in the doxygen? | Let's say, we have the following doxygen comment:
/**
* @brief The cool class.
*
* More info...
*/
class A {};
I'd like that "The cool class." brief has been appeared on some arbitrary place. For example, I'd like to make a table with list of some arbitrary classes and theirs brief descriptions. So, I have option ... | I think the \copybrief command is suited for this, just a mock-up with a list:
/// \file
///
/// Lets try to make a list:
/// - \copybrief A
/// - \copybrief B
/// \brief The cool class
class A {};
/// \brief The other cool class
class B {};
Which results here in the list in the detailed description of the file:
|
67,999,004 | 67,999,090 | Error on append string - Access violation reading location | I am trying to formulate a data matrix into a string to send to the server. But I get an error when apending data to a string. Why is this happening ?
The data I'm trying to send is the Bitmap image pixels.
My code:
string getPixelsFromBitmap(Bitmap& bitmap) {
//Pass up the width and height, as these are useful for... | In this statement
matrix += string(rgbValue + ",");
the argument expression represents an expression with the pointer arithmetic, To the pointer expression of the type const char * (",") is added the integer value rgbValue that evidently results in accessing a memory beyond the string literal ",".
It seems you mean so... |
67,999,012 | 67,999,141 | What's the resource management contract for IEnumString::Next? | I'm trying to implement an iterator over the IEnumString interface. I am having a hard time figuring out the precise contract of the IEnumString::Next() method.
The second parameter is documented as follows:
rgelt
An array of enumerated items.
The enumerator is responsible for allocating any memory, and the caller is ... | According to this Microsoft-authored sample on Github, the memory should be freed by calling CoTaskMemFree.
Start reading at line 91:
IFACEMETHODIMP CSampleSpellCheckProvider::InitializeWordlist(WORDLIST_TYPE wordlistType, _In_ IEnumString* words)
{
unsigned int type = wordlistType;
engine.ClearWordlist(type);
... |
67,999,437 | 68,012,232 | How to print contents of a container using std::format | Using fmtlib, we can print a container as follows:
#include <vector>
#include <fmt/ranges.h>
int main() {
std::vector<int> v = {1, 2, 3};
fmt::print("{}\n", v);
}
Can I do the same in the c++20 standard library version?
| Formatting ranges is not a part of C++20 std::format but P2286 proposes it for C++23.
|
67,999,444 | 67,999,562 | no member named 'hardware_constructive_interference_size' in namespace 'std' | According to cppreference, to determine if std::hardware_constructive_interference_size is usable it uses the following example:
#include <new>
#ifdef __cpp_lib_hardware_interference_size
using std::hardware_constructive_interference_size;
using std::hardware_destructive_interference_size;
#else
// 64 byte... |
How can I handle this situation?
You could detect the broken language implementation using pre-defined macros and make an exception for it.
Detection could be made by trying to compile and run a small program:
#include <new>
int main() {
#ifdef __cpp_lib_hardware_interference_size
// return 0 if the interference... |
67,999,522 | 67,999,617 | Why cannot use `decltype()` for `std::function<>` with lambda? | we know that decltype() could be used to get type of variables, just like following:
int a = 0;
using a_t = decltype(a);
a_t b = -1; // it worked, and type of b is int
but it didn't work for this:
auto f = [](int a) -> int { return a + 1;}; // the type of callable should be int(int)?
std::function<decltype(f)> F(f); ... | This is simply improper usage of the std::function wrapper. This type is meant to hide the actual implementation by wrapping it into a type-erased object with as little information about the underlying callable as possible: and this is the function signature.
When you use decltype(f), you get the acutal unique, compile... |
67,999,533 | 68,068,108 | Cmake how to selectively include folders | I am experiencing a problem in including only some folders in my cmake target_include_directories.
I need to include all but the folder /include/ros in the include directory if a CMake option is OFF and all, include that folder, if ON
The project look like this:
- include
- core
- algorithms
- ros
- src
- core... | The first problem that sticks out is that you're thinking about your dependencies in terms of folder you need to include instead of the cmake targets that they need to be.
cmake targets specifies dependencies that themselves include dedicated settings such as which headers to include, which dependencies they have, and ... |
67,999,580 | 67,999,894 | AVX-512BW emulation of _mm512_dpbusd_epi32 AVX-512VNNI instruction | There are AVX-512 VNNI instructions starting since Cascade Lake Intel CPU which can accelerate inference of quantized neural networks on CPU.
In particular there is a instuction _mm512_dpbusd_epi32 (vpdpbusd) which allows to perform multiplication of 8-bit signed and unsigned integers and accumulate them into 32-bit in... | I think this question does not have one correct answer.
On the one hand the fast emulation of _mm512_dpbusd_epi32 with using of AVX-512BW extension may be looked as:
inline __m512i _mm512_dpbusd_epi32_bw_fast(__m512i i32, __m512i u8, __m512i i8)
{
__m512i i16 = _mm512_maddubs_epi16(u8, i8); //possible overflow of I... |
67,999,880 | 68,000,295 | Is there any difference in perofrmance of unordered_set (C++) in case of strings vs in case of integer? | I was wondering that unordered_set uses hashing, so that should be faster in the case of integers than in the case of strings. The same would be the case for unordered_map. I found no definite answer on the web. It will be great if someone can clarify this.
|
Is there any difference in perofrmance of unordered_set (C++) in case of strings vs in case of integer?
There can be. The language specification doesn't have guarantees one way or the other.
You can verify whether this is the case for your program on your target system by measuring the performance.
If you're conside... |
68,000,045 | 68,007,665 | How to save a specific column into an array in C++? | I have a set of data in a .txt file that has an arbitrary number of columns, specified by the user in the input. I want to read that file, pick one of the columns and save it in an array. What is the best way to do this?
I have read this, this and this, but they all establish in the code the specific number of columns.... | I assume the user enters the coumn number over the console. So you can use the built-in cin function to read the input. You can use for loop and string streams to get the values. Code below; although you may have tweek it a little bit as per your needs
Edit: The code below has been edited a little bit. Now it should an... |
68,000,165 | 68,001,475 | fatal error: jni.h: No such file or directory. though I have included correct folder | I am trying to build a so file in my ubuntu 20.04 machine. I have created a Makefile to do the task. The content of the Makefile is given below
#
# 'make depend' uses makedepend to automatically generate dependencies
# (dependencies are added to end of Makefile)
# 'make' build so file 'libwebrtc-a... | You are using the .cpp.o implicit rule, which is (roughly) defined as follows:
.cpp.o:
$(CXX) $(CXXFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c $<
Your Makefile never sets CXXFLAGS or CPPFLAGS, so your INCLUDES variable is not used when compiling .cpp files. To fix it, do:
CXXFLAGS = $(INCLUDES)
|
68,000,265 | 68,000,506 | Template code that compiles in gcc 8.2 but not MSVC 19 | This example script compiles cleanly in gcc 8.2, but in Visual Studio 2019 it returns error C3200: 'bar<int>': invalid template argument for template parameter 'bar', expected a class template at the line where the 'new' occurs:
template<typename T, template<typename> class bar>
class foo;
template<typename T>
class b... | I admit, I don't know who is right or wrong here (see below). The confusion seems to be from the fact that inside the class template baz inheriting from bar<int> the identifier bar is interpreted as bar<int>. Strangely bar itself uses bar to refer to the template not to bar<T>. And the compilers do not agree. Anyhow, a... |
68,001,250 | 68,014,131 | Unable to link 'GLFW' in Visual Studio in #include<GLFW/glwf3.h> | I am trying to include
#include<GLFW/glfw3.h>
to create a window in OpenGL, but am getting this error, Error (active) E1696 cannot open source file "GLFW/glfw3.h" OpenGL E:\OpenGL\src\Application.cpp 1
Error image
Included Directory Screenshot
I have tried
this solution, but am still getting this same issue.
| I suggest you should check whether you are building a x86 project?
You need to make sure that you add the configuration properties to the correct build target and platform for your code.
And I suggest you could select "All Platforms" for the platform and select "All Configurations" for the Configuration when changing ... |
68,002,065 | 68,007,152 | C++ Dependencies directories between files | My compiler has a problem to search files in the directories. I'm on windows 10.
First of all, my files are organized in this way:
C:/mingw64/bin/g++ (my compiler is here)
C:/Users/Christophe/Documents/main.cpp (my file)
C:/Users/Christophe/Documents/SFML/include (my files.hpp)
C:/Users/Christophe/Documents/SFML/lib (... | if i was you, i wouldn't bother making a makefile myself.
Instead i will use cmake to generate the makefile and let him compile both my code and SFML.
If you want to do it like that, you can just download cmake on their website.
https://cmake.org/
don't forget to add cmake into your path variable if you are on window
... |
68,003,019 | 68,004,209 | Are static or unnamed namespace still useful when header and implementation are separated? | As answered in this question, I learnt that the static keyword to the function means it can only be seen from the functions in that file. I think unnamed namespace can be used for the same purpose.
However, usually, implementation and header files are separated. So, it seems to me that a programmer can hide all the "pr... | Keeping a definition in implementation file does not make it private in any sense. Any other header or implementation file can declare that function and use it. It's not always a bad thing - I used parts of private implementations of libraries when I really needed it (but I do not recommend doing that).
The worse part ... |
68,003,754 | 68,003,976 | C++ not running in vs code | I am trying to run my C++ code in vs code. I have installed global extension for C/C++ by Microsoft and also code runner extension.
When I run my code it shows this in the terminal.
user@LAPTOP-7LH95TTK MINGW64 ~/Desktop
$ cd "c:\Users\user\Desktop\" && g++ demo.cpp -o demo && "c:\Users\user\Desktop\"demo
bash: cd: c:\... | You can read through https://code.visualstudio.com/docs/cpp/config-mingw (if using MinGw).
If you have MSVC (MS C++ Compiler) installed, instead of 'g++' command you would be using the 'cl' command to compile (the guide for that is at https://code.visualstudio.com/docs/cpp/config-msvc).
Just a brief of the article:
Yo... |
68,005,907 | 68,006,142 | how to write this code without the need of more than one new operator? | I have a generic code with template <class T> that I want it to work without the need of T()
so for the copy constructor I have this:
template <class T>
SortedList<T>::SortedList(const SortedList<T>& list):
data(new T*[list.max_size])
,size(list.size)
,max_size(list.max_size)
{
for (int i = 0; i < size; i++)
... | If you do this:
template <class T>
SortedList<T>::SortedList(const SortedList<T>& list):
data(new T*[list.max_size])
,size(list.size)
,max_size(list.max_size)
{
for (int i = 0; i < size; i++)
{
T* new_element=new T(*(list.data[i]));
data[i]=new_element;
}
}
You are copying all the... |
68,006,208 | 68,006,262 | Why round() make my expression give wrong answer? | I'm currently facing a problem but I don't know why it wrong?
// ll ís long long
ll cnt = 24822089714520516;
cout << "xpow: " << xpow(10LL, 16) << endl;
cout << "cnt: " << cnt << endl;
ll a = xpow(10LL, 16) + cnt - 1;
ll b = round(xpow(10LL, 16)) + cnt - 1;
cout << "cur_num (without round): " << a << endl;
cout << ... | In many C++ implementations, the long long type is 64 bits long, and the double type is 64 bits long. When this happens, a variable of type double cannot exactly represent all possible long long values, and in particular large long long values might be approximated incorrectly by a double.
Here, round converts your lon... |
68,006,373 | 68,006,405 | Adding in one line differs from adding with loop | I was solving a simple problem that involves the addition of integers with the possibility of obtaining long long integers.
Consider the following array being the input [256741038 623958417 467905213 714532089 938071625]
If I use this structure
void miniMaxSum(vector<int> arr) {
sort(arr.begin(), arr.end());
lo... | The calculation arr[1] + arr[2] + arr[3] + arr[4] is done without seeing the type of variable the result is assigned and in the range of int.
In the second version, the addition max + arr[i] is done between long long int and int and therefore it is done in the range of long long int.
Cast one of that to long long int t... |
68,006,539 | 68,006,792 | Efficient non-trivial initialization of multiple members in C++ initialization lists | Suppose I want to write a class that represents an immutable normalized (norm == 1) vector in two dimensions along with a mutable int:
#include <cmath>
#include <iostream>
double norm2d(double x, double y)
{
return sqrt(x*x + y*y);
}
class NormalizedVector {
public:
NormalizedVector(double x, double y, int some_i... | Yes, you can have a private constructor that takes an additional parameter, and delegate to that.
class NormalizedVector {
public:
NormalizedVector(double x, double y, int some_int)
: NormalizedVector(x, y, some_int, norm2d(x, y)) {};
void set_some(int i) { m_some_int = i; }
private:
NormalizedVector(double x... |
68,006,615 | 68,006,908 | Node.js: How to create ES6 module in C++ | This is the old example of creating a Node.js addon in C++:
https://nodejs.org/api/addons.html
It can be built with node-gyp to a common JS module, which works fine with function 'require'. However, the compiled module can't be imported in .mjs file.
This works fine: node test.js
// test.js
var m = require("./build/Rel... | Node does not currently support loading native modules with import syntax.
In an ESM file, you will need to do:
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const m = require('./build/Release/addon');
console.log(m.hello());
|
68,006,844 | 68,006,923 | Why does Clang 12 refuse to initialize aggregates in the C++20 way? | As far as I understand, the following program should work in C++20 mode:
#include <vector>
struct B{ int a0, a1; };
int main()
{
std::vector<B> bs;
bs.emplace_back( 0, 0 );
}
And it really does in Visual Studio 2019 and gcc 11. But not in clang 12, which produces the error:
/opt/compiler-explorer/gcc-snapsh... | This is a C++20 feature that allows aggregate initialization through the standard constructor syntax, rather than the typical braced-list initialization syntax. (Note that this only works if the parameters cannot be used in a valid call to a default or copy/move constructor. If they could, that would be called instead ... |
68,007,027 | 68,007,163 | How to associate type with number as parameter to function? | Consider this example:
In a game there are some buildings you can build with a specific cost for each kind . for example a "House" can be built with the cost of 2 "Iron" and 3 "Wood" ; in which "Iron" and "Wood" are "Resources" pre-defined (there is "Resources" interface and "wood" and "Iron" and ... inherit from it )... | It sounds like you're wanting to map between building type and resource counts, so how about some kind of function that returns the mapping explicitly as a vector? Using a struct to keep track of it rather than a 2d array might be more maintainable and easier to follow:
enum class Resource {
Iron,
Wood,
...... |
68,007,068 | 68,014,293 | Eclipse Can't Find MinGW/Can't setup C++ on Eclipse | I am trying to setup c++ in Eclipse IDE. I have installed the C++ Development Tools and C++ Development Tools SDK. I have read "Before you begin" in "C/C++ Development Guide". I have installed MinGW on the page it provides. It installes it to C:\MinGW which Eclipse said it could recognize. I create a new makefile C++ p... | You need to tell Eclipse where to gcc.exe and g++.exe.
In your case I would expect that to be C:\MinGw\mingw32\bin or C:\MinGw\bin.
If there's no gcc.exe and g++.exe there, it would appear your MinGW setup is broken.
Note that plain MinGW is a not very well maintained or up to date. I would recommend switching to MinGW... |
68,007,110 | 68,009,079 | QComboBox in QItemDelegate to show only the portion corresponding to other column | I have two MySQL tables with one-to-many relations.
Table si:
id integer primary key auto_increment,
...
cur_verify_date date,
...
Table verify:
...
si_id integer, -- id in 'si'
verify_date date,
...
So I need a combobox delegate for a table si in QTableView to choose items of verify_date only with si_id for corresp... | Yes, you can do that with QItemDelegate, I would say that's your main solution when you want to show combobox in QTableView.
Check is signature of createEditor method from QAbstractItemDelegate:
https://doc.qt.io/qt-5/qabstractitemdelegate.html#createEditor
You can use QModelIndex parameter to define custom values for ... |
68,007,832 | 68,008,413 | How to manage objects' initialization data? | I have dilema and would be glad to hear from someone who is more experienced in c++.
To be exact my dilema is how to manage (create) initialization data for objects. For example I have several objects, each needs it's own unique set of data used to initialize this object. Each object is initialized on the beginning of ... | One very simple option:
#include <stdexcept>
struct A
{
int data1;
float data2;
char data3;
};
A factory(int option)
{
switch (option)
{
case 0:
return {1, 1.5, 'c'};
case 1:
return {2, 3, 'f'};
case 2:
return {42, 3.14, 'p'};
default:
... |
68,008,330 | 68,008,834 | Can std::string_view data() be pointer-compared across assignment and copy? | If I make a copy of a non-empty string_view, via assignment or copy-construction, are the data() pointers of the two string_views guaranteed to compare equal?
For example:
const char* base = "foo[blah]bar[blah]";
std::string_view b1{base + 4, 4}; // points to first "blah"
std::string_view b2{base + 13, 4}; // poi... | Yes, it is guaranteed.
See the copy constructor:
https://en.cppreference.com/w/cpp/string/basic_string_view/basic_string_view
|
68,008,582 | 68,008,599 | What ways are there to call a function that should have been defined earlier? | I was writing code, and I realized that I needed to call a function that internally called another function, but this function internally called the previous function. I know that the best way to do that is to predefine these functions in a structure or class that is defined before those functions, but I would like to... | Add a declaration of your function before where you need to use it.
void Start(); // declaration
void Stop() {
}
void Reset() {
Stop();
Start();
}
void Start() {
//Set internally the function Reset to be called when the action ends
}
|
68,008,583 | 68,008,634 | what does &fun() refer to in the program? | This is an example problem to demonstrate the use of references in c++. i'm a beginner and this is my first time learning about references. i don't understand why we use &fun(). what does it mean?
#include<iostream>
using namespace std;
int &fun(){
static int x = 10;
return x;
}
int ma... | Equivalent syntax is int& fun().
So this function returns a reference to 'x' (that is static), so later in main you can modify it (y = 20 does change the x inside the function).
So another invocation returns 20, as the x had been changed.
|
68,008,614 | 68,008,716 | Vulkan: Separate vertex buffers or dynamic vertex buffers? | So I'm starting to learn Vulkan, and I still haven't done anything with multiple objects yet, thing is, if I'm making a game engine, and I'm implementing some kind of "drag and drop" thing, where you drag, for example, a cube from a panel, and drop it into the scene, is it better to... ?
Have separate vertex buffers.
... | A growing vertex buffer is usually the way to go, keep in mind Vulkan has very limited buffer handles of every type and is designed for sub-allocation (like in old school C). Excerpt from NVIDIA's Vulkan recommendations:
Use memory sub-allocation. vkAllocateMemory() is an expensive operation on the CPU. Cost can be re... |
68,008,668 | 68,009,871 | CLR library compiles but C# call returns error CS0103 even with existing compiled metadata | I have a Visual Studio Solution with a Class Library (C#) and a CLR Class Library (C++). The CLR class library builds properly and it as simple as, for the header file:
public ref class CLRClass
{
public:
static void CLRMethod();
};
The cpp implements just an empty CLRMethod. In the C# library I added a reference ... | It's a problem of C# .Net Target Framework Version. Notice that you have this warning in your reference:
This is because the C# Class Library targets a Framework version that is older (4.7.1) than the one that the C++/CLI framework (4.8). Just retarget your C++ library.
|
68,008,696 | 68,010,348 | Why is setZero faster with Eigen dense dynamic matrix than static matrix? | I compiled the following code for testing
#include <iostream>
#include <Eigen/Dense>
#include <chrono>
int main()
{
constexpr size_t t = 10000;
constexpr size_t size = 100;
auto t1 = std::chrono::steady_clock::now();
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> m1;
for (size_t i = 0; i < ... | TL;DR: the performance results are strongly dependent of the target platform and the compiler.
First of all, this assertion is not always true. Actually, the dynamic version is faster on my machine since I get the result dynamic: 0.128093 static: 0.142624 (using -std=c++20 -O3 -DNDEBUG and GCC 10.2.1). The reason is th... |
68,008,839 | 68,009,591 | Load and duplicate 4 single precision float numbers into a packed __m256 variable with fewest instructions | I have a float array containing A,B,C,D 4 float numbers and I wish to load them into a __m256 variable like AABBCCDD. What's the best way to do this?
I know using _mm256_set_ps() is always an option but it seems slow with 8 CPU instructions. Thanks.
| If your data was the result of another vector calculation (and in a __m128), you'd want AVX2 vpermps (_mm256_permutexvar_ps) with a control vector of _mm256_set_epi32(3,3, 2,2, 1,1, 0,0).
vpermps ymm is 1 uop on Intel, but 2 uops on Zen2 (with 2 cycle throughput). And 3 uops on Zen1 with one per 4 clock throughput. ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.