question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
69,012,084 | 69,012,258 | Template parameter in std::function |
I have this piece of code and I do not understand why do not works.
During the compilation, in the lines where I call run(), I get:
Candidate template ignored: could not match 'function<double (const type-parameter-0-0 &, const type-parameter-0-0 &)>' against 'double (*)(const data_t &, const data_t &)'
this is the c... | Third argument to function run is declared to be std::function<double(const T &, const T &)>, however you pass a pointer to scoreValue1 causing type deduction to be impossible. In order to deal with this problem you need to either
declare argument to be a pointer to function
void run
(
const std::vector<T> & data... |
69,012,186 | 69,012,228 | Why using declaration is needed when an overload is deleted | Why do I have to reintroduce the name of a function having some of its overloads deleted ?
#include <string>
struct A
{
void f(int) {}
void f(double) {}
void f(const std::string&) {}
};
struct B : public A
{
using A::f; // needed to compile : why ?
void f(int)=delete;
void f(double)=delete;
};... | A single declaration of f in the B class hides all declarations of f from the base A class.
And even marking the functions as deleted is considered a declaration.
|
69,012,795 | 69,013,118 | Accessing a base class member with .*& (accessing priority_queue container) | I'm trying to understand the code below from
How to iterate over a priority_queue?
I gather that since HackedQueue is deriving privately from priority_queue, it can access its privates. So, I assume that *&HackedQueue::c returns the address of the base class object, and its called for q. Not fully clear, though, and ev... |
I'm trying to understand the code below from
Let's say in points:
.* is pointer-to-member access operator. See https://en.cppreference.com/w/cpp/language/operator_member_access
The code is using internal representation of the priority_queue, it's using the underlying container used by the queue to store data and acc... |
69,014,616 | 69,014,856 | I put a shared_ptr into a map, but why is the object destructed before the program ends? | I create a shared_ptr for my test object, and put it in a std::map, but its destructor is called before the program ends, and I don't know why.
Here is my test code:
class Test
{
public:
Test()
{
std::cout << "in constructor" << std::endl;
}
~Test()
{
std::cout << "in ~constructor" ... | operator [] of std::map will insert element if not present in the map. std::map::insert() will fail to insert anything if the element is already in the map. Thus, your insert() call fails. You can verify it by checking the return value:
auto [iterator, wasInserted] = datas.insert(std::make_pair("key", temp));
std::cout... |
69,014,886 | 69,015,068 | Why does std::weak_ptr<T>::lock return empty shared pointer here? | I'm trying to create an AABBTree structure where each node knows its parent and children.
Within my AABBTreeNode class, the parent is stored as a std::shared_ptr<AABBTreeNode> and the children as a std::vector<std::weak_ptr<AABBTreeNode>>.
This is done to avoid circular references as pointed out in this Stackoverflow p... | {
auto child = std::make_shared<AABBTreeNode>(shared_from_this(), m_Mesh, partitionBound);
m_Children.push_back(child);
}
Here, the automatic variable child is the sole owner of the newly created node. At the end of the scope, child is automatically destroyed, and as it is the last owner, the node is destroyed... |
69,015,115 | 69,015,668 | Negative result due to overflow despite using long long int | Why this the result of this program negative, despite having used the long long int data type?
Please help me. My code is below:
#include <iostream>
#define percent 10
int main() {
int A=200,B=400,C=150,D=210;
long long int non_Zero_value_number;
non_Zero_value_number=(percent*(A*B*C*D))/100;
std::cou... | You either need to declare one of the variables you're multiplying as a long or you need to cast it to long during the multiplication.
Declaring 1 variable as a long:
long A = 200;
int B = 400, C=150, D=210, ...
Declaring all variables as long:
long A = 200, B = 400, C=150, D=210, ...
Casting variable A to long during ... |
69,015,243 | 69,015,795 | Why do I get the same number when using rand/srand in a function before main? | Why am I getting a different random number each time I run my code in main, but when I run it in a function I am getting a static number?
(1) Random number in Main...
int main()
{
srand(time(0));
int loot = 1+(rand()%9);
cout << loot;
return 0;
}
(2) Random Number in a function outside of main...
using... | Right off the bat, you should know what the line std::cout << lootTable; does in your original code. It is equivalent to std::cout << <address of lootTable function>;, which is a non-zero value, which gets converted to a bool, which then results in printing 1. When compiling, it is highly recommended to enable warnings... |
69,015,429 | 69,015,552 | Inconsistency of visibility of data member in ordering class C++ | Since operator <=> was introduced in C++20, we first need to include <compare> before using (built-in, and defaulted).
However, I saw different implementations of each ordering (std::weak_ordering, std::partial_ordering, std::strong_ordering) in every implementation (maybe with a compiler), but the most notable one is ... | The standard defines the ordering classes in terms of "exposition only" members. These members are defined as private. Plus, there is no statement that any of these classes are structural types.
As such, you cannot assume that they are. So you cannot use them as NTTPs. An implementation may implement them as such, but ... |
69,015,615 | 69,024,479 | OpenMP For-Loops yield different Results with and without Multithreading | I am new to multithreading and I found the following issue while trying to parallelize some for-loops, in which I manipulate 3D Arrays.
When I run the code using only a single thread, I get the value of E_total I would expect. However when I use the same code with multiple threads and OpenMP, where I set #pragma omp pa... | The problem with this code is that there is a race condition between the different threads. The E_pot and E_int variables are shared between the worker threads and thus the threads are destroying each other's value from time to time.
To fix this, please apply the reduction clause (see Reduction Clauses and Directives ... |
69,017,187 | 69,017,420 | Passing Multidimensional array with variable size | Passing dimensions of the array to function but still getting an error!
Code (You can directly scroll down to the error it gives and see only those lines in code)
class Solution {
public:
int mod = 1e9 + 7;
int checkRecord(int n) {
int dp[n + 1][2][3];
memset(dp, -1, sizeof(dp));
ret... |
int checkRecord(int n) {
int dp[n + 1][2][3];
The size of an array variable must be compile time constant in C++. n + 1 is not compile time constant and as such the program is ill-formed.
If you want to create an array with runtime size, then you must create an array with dynamic storage duration. simplest way t... |
69,017,602 | 69,017,685 | Constructing an object other than specified parameters NOT giving me errors | I was going through a book called Programming Principles and Practices using C++ but found a strange behavior of class construction.
Suppose I have a class as follows:
class Foo {
public:
Foo(int x)
: y { x } { }
private:
int y;
};
and I have another class which has an instance of class Foo as its mem... | You can prevent this implicit conversion by declaring the Foo constructor explicit
explicit Foo(int x) : y { x } { }
in main this would require the caller to change their obj_2 instantiation to
Bar obj_2 { Foo{2021} };
|
69,017,762 | 69,017,909 | Condition_variable C++ | There is a simple example of using Condition_variable:
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable
std::mutex mtx;
std::condition_variable cv;
int global_... |
I change the value global_status from only one thread - why then they block it mutex
You need the mutex because you read the value in different threads.
|
69,017,978 | 69,018,335 | C++ - Hash/Map a std::vector<uint64_t> in a single uint64_t | I need to map a std::vector<uint64_t> to a single uint64_t. It is possible to do? I thought to use a hash function. Is that a solution?
For example, this vector:
std::vector<uint64_t> v {
16377,
2631694347470643681,
11730294873282192384
}
should be converted into one uint64_t.
If a hash function is not a good so... |
I need to hash a std::vector<uint64_t> to a single uint64_t. It is possibile to do?
Yes, variable length hash functions exist, and it's possible to implement them in C++.
C++ standard library comes with a few hash functions, but unfortunately not for vector (other than for the bool specialisation). We can reuse the h... |
69,018,304 | 69,018,744 | how do I assign a function to a declared function that has already been defined | In my C++ file OneDSystem.cpp I have the following:
OneDSystem::OneDSystem()
{
this->Particle = OneDParticle();
this->potential = &SHOPotential; // problem here.
this->MAXPOS = this->Particle.get().at(0);
this->MAXVEL = this->Quadratic(2 / this->Particle.get_mass(), 0.0, PotentialEnergy(this->MAXPOS));
... | You could make the class implementation static.
OneDSystem.hpp
class OneDSystem
{
private:
double (*potential)(double, double);
OneDParticle Particle;
double MAXPOS, MAXVEL;
static double SHOPotential(double mass, double position);
public:
OneDSystem();
OneDSystem(const OneDParticle Particle, ... |
69,018,912 | 69,019,084 | Why does -O3 in gcc seem to initialize my local variable to 0, while -O0 does not? | From What happens to a declared, uninitialized variable in C? Does it have a value?, I tried playing with Ciro Santilli's code, shown below.
int f() {
int i = 13;
return i;
}
int g() {
int i;
return i;
}
int main() {
assert(f() == 13);
assert(g() == 0);
}
The call to g() should reuse the same add... | As eerorika's answer says, your code invokes undefined behavior.
If you actually look at the assembly code generated, you get this
f():
mov eax, 13
ret
g():
ret
main:
xor eax, eax
ret
As you can see g() is a single ret instruction, compared to f() which sets eax to 13. S... |
69,019,397 | 69,019,462 | Problems casting an address to a pointer | I understand that the address-of operator & stores the actual address of the variable. A pointer stores a reference to an address that I can access using the dereference operator *. What I am not understanding is how to make a pointer point to a given address. Non of the following have worked.
void getDouble(double &ad... |
I understand that the address-of operator & stores the actual address of the variable
An operator doesn't "store" anything. When you pass a value as the operand of built-in address-of operator, the resulting value is a pointer to the object. If the operand is a reference, then the result is a pointer to the referred ... |
69,019,491 | 69,019,583 | C++ passing class to constructor = not passing same instance? | It seems that, when I pass an class it is not passing a persistant (the same) instance of that class as I would expect. I'm assuming this has something to do with memory state but I would appreciate it if someone could explain exactly what is happening. The issue is easily demonstrated as follows :
Main.ino
#include ... | You have two Debug values in your code. One global, one member of the Box class.
Those are two distinct values, since Box create or copy from a value to create its own, and there's the global one.
A solution would be to contain a reference or a pointer.
Here's the example with a reference:
class Box {
private:
... |
69,019,931 | 69,020,065 | Pointer-to-member-function performs virtual dispatch? | I executed the following code.
#include <iostream>
class Base
{
public:
virtual void func()
{
std::cout<<"Base func called"<<std::endl;
}
};
class Derived: public Base
{
public:
virtual void func() override
{
std::cout<<"Derived func called"<<std::endl;
}
};
int main()
{
... | Refer to [expr.call], specifically here
[If the selected function is virtual], its final overrider in the dynamic type of the object expression is called; such a call is referred to as a virtual function call
Whether you call the function through a pointer or by class member access is the same (ref); the actual funct... |
69,020,092 | 69,020,447 | Cannot push back a string into a vector of strings c++ | I'm trying to create a program to separate a single line into a vector of strings separated by the blank spaces in said line, so turn:
foo bar
into
["foo", "bar"]
This is what I have so far:
string command;
string command_temp;
vector<string> command_seperated;
std::cin >> command;
for (int i = 0; i < command.lengt... | What you are seeing is normal behavior of operator>>, which is used for reading formatted input. It skips leading whitespace (if the skipws flag is enabled on the stream, which it normally is), then reads until EOF or whitespace is encountered. So, in your example, std::cin >> command receives only foo even though yo... |
69,020,252 | 69,020,350 | Construct an std:array from a smaller std::array | I have a template class defining the number of elements in an internal std::array. How would I construct a new object from a larger object. So far I have the copy constructors defined but these do not compile as there is no proper constructor for std::array with different sizes.
The current class definition:
template<u... | How about something somewhat straight forward like this instead of the copy constructor you've got:
template<uint32_t MAX_LENGTH_RHS, /*enable_if...*/>
A(const A<MAX_LENGTH_RHS>& rhs) {
const auto& rhs_data = rhs.get_data_const();
std::copy(rhs_data.begin(), rhs_data.end(), data.begin());
}
|
69,020,498 | 69,095,113 | Comparing strings in this instances work differently, any reason? | Can someone help me with this, please? The block of code in the green box works fine, but the one in red works but not really. It's checking if the emails have both "@gmail.com" and "@yahoo.com". I want it to check both emails so that if they both contain only one "@gmail.com" or "@yahoo.com", it will exit the loop. Th... | You have some issues in the code
auto found = emailOne_.find(myArray[i]); will find the @gmail.com even if the entered email address is foo@gmail.com.uk, which is probably not what you want.
If the first entry in myArray doesn't match, you break out and don't test the next.
If the first entry is a match, you don't bre... |
69,020,664 | 69,024,196 | How to find the L3 cache index and NUMA node index for the current hardware thread | I'm building a topological tree of sockets, NUMA nodes, caches, cores, and threads for any Intel or AMD system in C.
Building this hierarchy, I want to ensure hardware threads are grouped together appropriately so it's clear who precisely shares what. I've found that I can set a thread's affinity and then use the cpuid... |
If a package/socket has multiple NUMA nodes, how do I get an index of the NUMA node for the current hardware thread?
You get this information from ACPI.
Specifically, there's a "System Resource Affinity Table" (SRAT) that contains a list of structures describing which NUMA domain different things (CPUs, memory areas,... |
69,020,949 | 69,021,081 | Need help Regarding Vectors in c++; | I initialized a vector like
vector<vector<int>> A;
and the used the following loop for random input in vector.
n in the following code represents number of elements in a square matrix.
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
A[i][j] = rand() % 10;
... | As pointed out in the comments, you must specify the size of your vectors before using the [] operator. Otherwise, your vectors will have zero size and any index you give will be out of range. Constructing with a size is easily done:
std::vector<std::vector<int>> A(n, std::vector<int>(n));
This line of code uses a std... |
69,021,441 | 69,021,537 | priority_queue with custom cmp | I trying to implement event queue that is sorted by an event field.
So i write something like that:
struct MyAlgo
{
MyAlgo() {
// some random generation of positions
for (auto pos : RandomPostions)
Queue.push({SiteEvent, pos, NULL});
}
struct Event
{
EventType Type;
FVector2... | You need a static function (to match the signature for the comparison operation). Also, you need to qualify the name:
static bool cmp(const Event& a, const Event& b) {
return a.Pos.Y > b.Pos.Y;
}
std::priority_queue<Event, std::vector<Event>, decltype(&MyAlgo::cmp)>
Queue { &MyAlgo::cmp };
Also, note that the ... |
69,021,792 | 69,025,164 | Expand parameter pack with index using a fold expression | I've got a template function taking a parameter pack. I want to expand it into calls to a second function while also supplying the index of the item in the pack. I probably can work out how to do it with recursion but I would like to try do it with a fold expression.
This is the function I want the parameter pack to... | In addition to another answer let me mention a simpler approach that doesn't need a helper function:
template<typename... Args>
void addRecord(Args&&... values) {
Record rec;
int i = 0;
(addToRecord(rec, i++, std::forward<Args>(values)), ...);
}
The comma operator , guarantees that all addToRecord()s will... |
69,022,929 | 69,025,088 | (OpenGL) Viewport wont change position on the y-axis | I'm creating a simple window manager for future projects and I seem to have run into a problem. I have a snippet of code which is supposed to change the viewport's position to the middle of the window whenever somebody resizes it, and it seems to work completely fine when changing position on the x-axis, as seen here. ... | I have run in a similar problem with SDL2 too.
I think the missing part is that you are not considering the aspect ractio value.
Also using SDL2 with Opengl you should consider that the drawable area can be different from the window area.
Assuming w and h the original sizes,
draw_w and _draw_h the current drawable area... |
69,023,071 | 69,023,313 | Vim: pattern matching only among the keywords | In vim, language-wise keywords are defined. I want to find patterns using regular expression only among these language-wise keywords.
My original motivation is highlighting the c++'s member variables, which is usually with an underscore in the end of the word. In the example below, I'd like to highlight only route_grap... | I don't know about matching keywords, but you can get there by replacing .* with something a little more selective.
\< and \> match word boundaries.
\w* matches word characters.
Put them together and you get:
/\<\w*_\>
Which matches just the desired identifier:
|
69,023,074 | 69,024,641 | What should i write inside a destructor of a class | I am currently studying for a programming exam and am supposed to write a destructor for the class "BTree" in one of the exercises. The following code is a Binary Tree. I don't know what should be in the body of the destructor because I haven't learned that properly yet. I think there should be something in there with ... | As in the post stated above, you should free your objects in memory. I'm not too sure, but I think if you don't free / delete those objects it will just random unused memory laying around in your program that you can use for something else.
Solution
class BTree
{
public:
vertex* root;
BTree()
{
r... |
69,023,595 | 69,042,079 | How to delete a large number of specified graphics in OpenGL with Qt? | I use OpenGL with Qt to draw millions of lines. There are some lines don't need to delete and other lines need to delete. So I put the pointer of lines which need to delete to a QList. When need to delete these lines, I delete pointer first, and then clear the QList. But I found the operation is time-consuming, especia... | If you have the memory budget for it, you can try to reuse Drawable objects instead of deleting them.
First, keep a (global) freelist:
QList<Drawable*> freelist;
Then, when you allocate a new Drawable, first see if there are any in the freelist:
Drawable *newDrawable() {
if (freelist.isEmpty())
return new ... |
69,024,198 | 69,024,810 | std::invoke - perfect forwarding functor | Trying to understand why the following example fails to compile:
#include <functional>
template <typename F>
void f1(F&& f)
{
std::forward<F>(f)("hi");
}
template <typename F>
void f2(F&& f)
{
std::invoke(f, "hi"); // works but can't perfect forward functor
}
template <typename F>
void f3(F&& f)
{
std::invoke... | std::invoke is itself a function. In your case, its first parameter is a rvalue reference while f is a lvalue, so the error occurs.
INVOKE(std::forward<F>(f), std::forward<Args>(args)...) is executed after the function std::invoke is properly selected and called. Basically, your lambda function is passed as follows:
or... |
69,024,451 | 69,024,501 | C++, getting i think the memory address instead of the string i want? | I'm new to working on structures and came across this problem:
In Germany, the house number is displayed after the street name; for example, Bahnhofstraße 1. Change the print_address function from this section so that it can print addresses in either format.
#include <iostream>
#include <string>
using namespace std;
... | Your print_address function is declaring a local variable StreetAddress s and leaving it uninitialized, and then trying to print out the uninitialized "data" it contains.
I think what you intended was to print out the fields in the address argument, instead.
|
69,025,027 | 69,071,708 | Esay way to include all header files from solutions explorer Visual Studio 2019 | I want include all header files from solutions explorer like this:
without add all directories with this option:
Is there an easy way to tell VS2019 to use and link all header files from solutions explorer automatically?
Why?
If I have a lot of source code directories and in each directory are the header files... I n... | Ok. There is no solution.
Possible alternatives:
All headers are in one place and one include path is required.
Or headers in the same directory like the source code files.
Or headers need to be include like #include "../../header.h"
Thanks.
|
69,025,029 | 69,025,124 | How to use dependent template default parameter with member accesses | I do not know how to solve a problem which can be illustrated with the following struct:
template <typename T, unsigned WIDTH=T::width>
struct Handler {
static unsigned const width = WIDTH;
};
There is a struct (in this case called Handler) which takes as template parameter a type T. In the codebase, where this st... | You can use a trait helper class to solve this. By default it'll use ::width but can be specialised for other types:
template<typename T>
struct width_trait
{
static unsigned const width = T::width;
};
template<>
struct width_trait<float>
{
static unsigned const width = 32;
};
template <typename T, unsigned W... |
69,025,611 | 69,026,718 | C++ - How do I return 2 values using tuple and auto[value1, value2] as c++ says value1 should be const? | I'm coding a Polynom class in c++. In the following link, it is explained how to return several values using tuple : Returning multiple values from a C++ function
So I tried to code as indicated to return the quotient and the remainder of the polynomial division but it does not work.
Here is my division method :
tuple<... | It might be that Structured Binding does not work with your compiler version (or the C++ version option). That requires C++17.
If you can't go for C++17, you might want to try out older ways to do this:
Instead of
auto [Q, R] = division(D);
use
Polynome Q, R;
std::tie(Q, R) = division(D);
(This requires #include <tup... |
69,025,745 | 69,025,842 | Can I pick a random element from an array in C++? | This has been bugging me for days:
#include <iostream>
using namespace std;
string words[] = {"cake", "cookie", "carrot", "cauliflower", "cherries", "celery"};
string word = words[rand() % 6];
string guess;
int lives = 3;
int main()
{
std::cout << "Can you guess what word I'm thinking of? I'll give you a hint: it... | rand() is a pseudo random number generator. That means, given the same starting conditions (seed), it will generate the same pseudo random sequence of numbers every time.
So, change the seed for the random number generator (e.g. use the current time as a starting condition for the random number generator).
#include <io... |
69,025,857 | 69,026,361 | Java Style Enum Classes in C++ | I am trying to implement enum class for data types similar to Java enums.
DataType.h:
namespace Galactose {
class DataType {
public:
DataType(const std::string& a_name, const size_t a_byteSize);
DataType(const std::string& a_name, const DataType& a_componentType, const uint32_t a_componentCount)... | static on a variable in namespace scope means this variable exists once per translation unit (.cpp file) using this header. The way of making sure all translation units share the same object would be to declare these variables it as extern and define them in DataType.cpp.
DataType.h:
...
namespace DataTypes {
... |
69,026,208 | 69,026,738 | how to read c++ iso standard? i mean the way | I'm reading n4860 now and i have some curiosity about this.
i don't know how to explain it so i will just show an example.
now i'm looking "unordered_set" and the draft said
template<class Key,
class Hash = hash<Key>,
class Pred = equal_to<Key>,
class Allocator = allocator<Key>>
class unordered_set;
and i ... | The requirements for std::unordered_map are listed in C++20 draft in section 22.2.7. The requirements for Hash are stated in 22.2.7.1.3 as:
Each unordered associative container is parameterized by Key, by a function object type Hash that meets the Cpp17Hash requirements ([hash.requirements]) and acts as a hash functio... |
69,026,383 | 69,026,682 | How to shorten existing c++ code without an existing database | I found some (stuipd) repeating If-Else code in a project. Now I'm looking for an idea to shorten and change the code. The problem is, no database or something else is allowed. The values has to be in the code.
Has anybody an idea to shorten following code? My idea was to use a map, but I'm not sure if this will work.
... | Something like this will be able to cleanup your code quite a bit:
#include <iostream>
#include <map>
#include <functional>
double basic_tt(const double dLengthComp)
{
double dValue{};
if (dLengthComp > 2000.0)
dValue = 1130.0;
else if (dLengthComp > 1800.0)
dValue = 930.0;
else if (dL... |
69,026,561 | 69,049,718 | can SFML and glad be used in the same project | I am compleatly new to both SFML and OpenGL. Following the holy LearnOpenGl tutorial I managed to make a triangle, but now I have used SFML for a lot of a project already and I need to do something in 3d, thus (I think) I need glfw and glad but when I try to glad gives me the following error: OpenGL header already incl... | From what I understand glad already includes the necessary GL headers. So just do what the error message tells you and remove your own "include" of OpenGL. Only include the glad headers.
Also from my experience you do NOT need GLFW when using SMFL, as SFML provides a valid OpenGL context for you when creating a window.... |
69,026,869 | 69,027,201 | `fout.write( reinterpret_cast<const char*>(&e), sizeof(e) );` why here casting into `const char*`? | Code
#include <iostream>
#include <fstream>
struct emp
{
char name[20];
int age;
};
int main()
{
emp e1={"Abhishek", 22},e2;
std::ofstream fout;
fout.open("vicky.dat", std::ios::out | std::ios::binary);
fout.write(reinterpret_cast<const char*>(&e1),24);
... |
Why it is necessary to do reinterpret_cast with 1st argument of write and read function ?
Because the first argument to write() is a const char* and the first argument to read() is a char*.
why we casting address of type emp particularly to const char* and char* in write and read function respectively ?
You can ca... |
69,027,286 | 69,027,774 | Static const variable in each subclass | I am currently building an interface for SQL database tables. My current class hierarchy looks like that, listed with some basic methods and variables:
class AbstractTable
{
public:
AbstractTable(QString tableName);
void addRow(); // it operates on tableName and colNames
private:
const QString tableName;
... | An easy way to do is to split the instance-specific behavior and the behavior shared by all instances into two classes, i.e. to introduce an additional indirection.
struct TableDescriptor {
std::string name;
std::vector<std::string> cols;
};
class AbstractTable {
protected:
AbstractTable(const TableDescrip... |
69,027,949 | 69,028,697 | Output doens't come out as expected | I tried to add an boolean array that will store current status of user.
This is my array:
bool enterStatus[5];
Later in the code, i will check the array based on the id i get and then if the id is false, set it true and vice versa.
Assume the id is 1,
if(enterStatus[id] == true){
enterStatus[id] = false;
} if(enterS... | your if's are wrong as your check if true and set to false, then if false (which it's now gaurenteed to be), will be set to true. please put an else before the second if
|
69,028,090 | 69,151,254 | btRaycastVehicle's btWheelInfo rotation is incorrect | I use C++ Bullet Physics. I spawn btRaycastVehicle on the btTriangleMesh. I update the wheel model by using
vehicle->getWheelTransformWS(i).getOpenGLMatrix(mat); matrix. As you can see in the clip below wheels steering turns OK, their positions in World Space are correct but rotations are completely off. btWheelInfo's ... | I found an issue and now it works, take a look here: https://youtu.be/s4ElFeGeAfM
The problem was that I was not setting vehicle coordinate system. Now when I do with vehicle->setCoordinateSystem(0,1,2); it works perfectly.
|
69,028,311 | 69,029,046 | C++ opencv method is slower than python | Trying to use opencv with c++. C++ Function cvtColor works 16 times slower than on python.
I created c++ and python programs to test efficiency of cvtColor function.
The cvtcolor s return same values on python and c++. Python cycle runs 650-750 times per second. C++ do it 25-35 times. How to fix it?
I have already trie... | There is some problem with your approach. I cannot point it out correctly but I am showing how I did it and my results.
Python
(Version: 4.5.1, IDE: VS Code)
import cv2
import time as t
img = cv2.imread("18JE0646.jpg")
t1 = t.time()
for _ in range(10000):
hsv_image = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
t2 = t.t... |
69,028,498 | 69,031,337 | C++ How to use relative error with `cout`? | While preparing for my first ever coding interview I found a question where I was requested to print a double number with an absolute or relative error of 10^(-6).
How can I do something like that with cout?
double test_var; // Holding Some value which changes according to my program.
cout << test_var << endl;
Plus, I... | You could have used std::setprecision.
#include <iostream>
#include <iomanip>
int main()
{
double f =3.14159;
std::cout << std::setprecision(5) << f << '\n'; //prints 3.1416
std::cout << std::setprecision(9) << f << '\n'; //prints 3.14159
std::cout << std::fixed; //Modifies the default formatting for floating... |
69,029,229 | 69,029,821 | How can I use signal handlers to stop and resume a child process? | I tried to stop and resume the child process using the signal handler function, my code is as follows, but the result does not seem to achieve what I want, why?
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include<sys/wait.h>
#include <unistd.h>
#include <sys/types.h>
#define ERR_EXIT(m) ... | The child catches the signal. In the child, global_pid is zero, so you are sending the signals to the process group.
|
69,029,587 | 69,029,776 | What is wrong with this code for the classic 'Subset Sum' problem? | Problem Statement: Given a list of integers (nums) and an integer x, check if some (possibly all) elements from the list, when added, give x.
Solution:
int dp[20001];
int recurse(vector<int>& nums, int x, int i) {
if (x == 0)
return 1;
if (i < 0 or x < 0)
return 0;
... | Your dp array depends only on the value of x. But it should depend on both x and i.
As an example:
Suppose nums = [1, 2, 3, 13] and x=13.
Then recurse(nums, 13, 3) should return 1, but recurse(nums, 13, 2) should return 0. With your code, if you called recurse(nums, 13, 2) first then dp[13] would be assigned an incorre... |
69,030,624 | 69,030,818 | c api expects char* memory (malloc) and how to avoid this malloc. Code refactoring | I have a c library API that expects something similar to below,
(I am doing refactoring on the old C++ code)
some c++ program.cpp which uses that clibrary:
char *getname = (char*)malloc(20);
getMeName(20, getname); //the c api
cout<<getname; //some operations wit the red data
free(getname);
the C API declaration:
int... | Assume that you want to allocate the string buffer directly on the stack, you could use:
char getname[20];
getMeName(20, getname);
cout<<getname;
In this case the memory will be allocated on the stack and identifier getname will be a pointer to the contents.
I would assume that API getMeName will include a Null termin... |
69,030,712 | 69,030,899 | Implementing traits for strong types with C++ concepts | I would like to have a nice way to enable functionality(e.g. ++, *=, /) of my strong types(e.g. StockPrice, Count).
I don't like using inheritance for that (CRTP/mixins), I understand some may like it but I prefer to not use inheritance for this use case.
So I have code like this:
template<class, template<class...> cla... | How about something like
// Different capability tags
struct Addable{};
struct PreIncrementable{};
// ...
template <typename Underlying,
typename TagType,
typename... CapabilityTags>
struct StrongT
{
Underlying val;
using Tag = TagType;
friend StrongT operator+(const StrongT& lhs, cons... |
69,031,126 | 69,046,748 | Using indices not working properly in open gles c++ | I am using glDrawElement() for rendering a plain but the indexing is not working as intended so i am getting an irrelevant object .I have used AAssetmanager for loading the coordinates from a wavefront object file .
here is my code for rendering :
GLushort squareindices[] = {
0 , 1 ,2,
0, 3, 2
};
GLf... | This are your vertex coordinates
0: ( 0.0, 0.0, 0.0)
1: (10.0, 0.0, 0.0)
2: ( 0.0, 0.0, -10.0)
3: (10.0, 0.0, -10.0)
0 1
+-----+
| |
| |
+-----+
2 3
Triangulate the quad with the following indices:
0, 1, 2, 1, 3, 2
0 1
+-----+ +
| / / |
| / / |
+ +-----+
... |
69,031,182 | 69,032,851 | Where do I set memory barriers so that conditional loops observe multithread value changes? | Assuming a thread running indefinitely until it's member variable stop is set. Like
while (!stop) {
// do something
}
I want to prevent it turning into this
if (!stop) {
while (true) {
}
}
So where would I set memory barriers / fences so that this optimization can't be performed?
Also, would such a fence alr... |
So where would I set memory barriers / fences so that this optimization can't be performed?
A memory barrier/fence restricts the memory ordering, which prevents the compiler from reordering two or more memory accesses in the same thread. However, memory ordering is not the issue here, as you are only talking about a ... |
69,031,265 | 69,031,545 | How to organize parts of a project that use common files? | I'm developing a C++ project. My project consists of two parts: backend and GUI. Both of them written in C++. Now I've finished developing the first part - backend. Now I want to start developing the GUI part, but I don't know how to organize git repositories and folders structure. Now I have a single repository with o... | What I would typically do with common libraries or any "generic" code is place them into their own repository. You can then pull the shared libraries into your other projects (backend and GUI) as Git submodules.
One great advantage of submodules is that the link in your parent project (GUI or backend) tracks the speci... |
69,031,680 | 69,032,072 | Multithreading template member function error | I'm testing how to create a thread using this code but I'm stuck with this error.
In file included from rasterization.cpp:1:
rasterization.h: In instantiation of 'void pipeline3D::Rasterizer<Target_t>::render_object(pipeline3D::Object<Triangle, type, Vertex_Shader>) [with type = char; Vertex_Shader = my_shader; Triangl... | My guess would be that it can't deduce the template argument types when using that constructor of std::thread. Maybe try something like this instead:
std::thread t1([this, &o]() {
render_triangle(o.mesh[i].v1, o.mesh[i].v2, o.mesh[i].v3, o.shader);
});
Alternatively if you don't want to go the lambda route, you co... |
69,031,751 | 69,052,316 | Deduce template parameter for a template function pointer with default template parameter | Though the question seems a little bit confusing. The code is simple as:
template <typename T>
void tfunc(T&& getter)
{
}
template <typename T = void>
void voidfunc()
{}
int main() {
tfunc(&voidfunc); // error: could not deduce template argument for 'T'
tfunc(&voidfunc<int>); // ok
voidfunc(); // calli... | As stated in the comments, this situation was not clear in the standard until C++20, where it was cleaned up in order to better support the new feature of constrained functions. The new specification makes sense in previous language versions (ignoring the possibility of constraints), so hopefully implementations will ... |
69,032,640 | 69,099,353 | Static variable getting pre initialized with random values | Can someone please explain why a member variable (char m_DBFileName[257]) of static variable (g_JournalDB) getting initialized with a random value? I expect it to be populated with '\0's.
More info: g_JournalDB is part of a dynamic library loaded on app startup via
public class MyApplication extends Application {
... | You have a massive class and I recommend that you initialize all member variables in the one contructor you have.
Example:
cAMPDatabase::cAMPDatabase() :
m_DBHandle{nullptr},
m_SqlObj{nullptr}, // see note
m_ErrorCode{0},
m_DBFileName{},
m_TableName{},
m_TableFldDef{},
m_Tables{},
m_T... |
69,032,737 | 69,033,005 | Qt How can I get a signal from int when the value changes? | So lets say I a QDialog class like this
class DiagExample : public QDialog
{
Q_OBJECT
public:
DiagExample(QWidget *parent);
private:
int myIntValue = 0;
QPushButton *AddToValue;
QPushButton *MinusToValue;
QLabel *counter;
};
And the implementation looks like this
DiagExample::DiagExample(QW... | Standard way of doing such things in Qt:
class DiagExample : public QDialog
{
Q_OBJECT
Q_PROPERTY(intValue READ intValue NOTIFY onIntValueChange)
public:
DiagExample(QWidget *parent);
int intValue() const;
signals:
void onIntValueChange(int);
private:
int myIntValue = 0;
QPushButton *A... |
69,033,020 | 69,033,129 | pointer comparision with int type in c++ | I executed the below program as: ./aout w.
#include<iostream>
using namespace std;
int main(int argc, char** argv)
{
if (argv[1] == "w")
{
cout << "this was worked";
}
else
{
cout << "this did not worked";
}
}
OUTPUT: this did not worked.
I tried executing: if(&argv[1] == "w")
... | The line
if (argv[1] == "w")
is equivalent to
char const* p1 = argv[1];
char const* p2 = "w";
if ( p1 == p2 )
i.e. you are comparing two pointers, not the strings that the pointers point to.
You can use std::strcmp. However, since you are using C++, you might as well use std::string.
if (std::string(argv[1]) == "w")
... |
69,033,366 | 69,033,494 | Interpolation search? | I have a uniform 1D grid with value {0.1, 0.22, 0.35, 0.5, 0.78, 0.92}. These values are equally positioned from position 0 to 5 like following:
value 0.1 0.22 0.35 0.5 0.78 0.92
|_________|_________|_________|_________|_________|
position 0 1 2 ... | You can get the integer part of the interpolation value and use that to index the two values you need to interpolate between. No need to use binary search as you are always know between which two values you interpolate. Only need to look out for indices that are outside of the values if that could ever happen.
This onl... |
69,033,631 | 69,033,847 | Inheritance from parents with same members | I am having trouble accessing members (with the same name) of parents under multiple inheritance. I have 4 classes (classic diamond problem) defined as follows:
class ClapTrap
{
public:
ClapTrap(void)
{ _hitpoints = 0; }
~ClapTrap() { }
protected:
int _hitpoints;
};
... | There's only one ClapTrap since you use virtual inheritance and with that, only one _hitpoints.
You can't have that one _hitpoints variable carry multiple values.
First, ClapTrap is constructed, assigning 0, then ScravTrap is constructed, assigning 1 and last, FragTrap is constructed, assigning 2 - all to the same _hi... |
69,033,956 | 69,036,867 | Executing several actions in parallel with std::jthread and comma operator in C++20 | In C++20 we got a new thread-class std::jthread that unlike old std::thread
waits
for thread termination in the destructor. So it becomes easy to execute several actions in parallel using unnamed jthread-objects and comma operator:
#include <thread>
#include <iostream>
int main() {
std::jthread{ []{ std::cout << "... |
there is really some risk associated with such jthread-usage?
Define "such usage" and "some risk".
The nodiscard attribute is entirely appropriate for jthread's constructors. Yes, you can write code where creating and discarding a jthread object is a meaningful, functional thing. But even if it is meaningful and func... |
69,034,018 | 69,036,086 | What happens if I reassign to a class containing a vector? Will it leak memory? | Like in the following example:
#include <vector>
class VectorContainer {
private:
std::vector<int> v;
public:
void AddStuffToVector() {
this->v.push_back(4);
this->v.push_back(3);
this->v.push_back(2);
this->v.push_back(6);
}
};
int main() {
VectorContainer a;
a.AddStuffToVector();
a = Ve... | since the std::vector has defined a assignment operator (will suppressed bitwise copy assiment), so the compiler will generate a implicit assigment operator for your "VectorContainer" class, like:
VectorContainer& VectorContainer::operator=(const VectorContainer &rhs)
{
v = rhs.v;
return *this;
}
|
69,034,335 | 73,309,383 | QT qSharedDataPointer dynamic casting? | I am trying to perform the following cast and I can't find a way either in the QT documentation or online to make this dynamic cast work which has been confusing:
class Entity : public QSharedData
{
public:
typedef QExplicitlySharedDataPointer<Entity> Pointer;
typedef QExplicitlySharedDataPointer<const Entity... | The problem is that you can only use dynamic_cast on raw pointers. Even though QExplicitlySharedDataPointer is a class that's meant to be used like a pointer, it's not a raw pointer, so you can't use dynamic_cast on it.
The solution is to get the raw pointer using QExplicitlySharedDataPointer's data() or constData() me... |
69,035,206 | 69,035,899 | Trigger added methods of derived class by method in base class | I want to implement a simple test structure. Here is how I created base class and derived class.
testBase.h:
class TestBase {
public:
TestBase() {}
virtual void TestStart() = 0;
virtual void TestEnd() = 0;
void RunTest() {
// I need code here to trigger a chain of calls
}
};
classifierTes... | You are basically asking for reflection which isnt present in C++ (yet). Now the quesiton is what comprosmise you are willing to make.
If you are fine with writing some code to manually register the test functions, then they don't need to be members and a possible solution is this:
#include <functional>
#include <vecto... |
69,035,592 | 69,035,674 | How to get the dictionary key? | I have a structure :
struct node {
map<string, string> data;
node* left;
node* right;
};
And I know there can be only one key-value pair in the data (I know I can use a pair, but the task is to do it with a map - realy strange task) )
So, how can I get the key in some node?
For example :
node t;
t.data...
... | t.data.begin()->first will do the work. But probably you should write the whole task 'cause it's really strange.
|
69,036,476 | 69,036,766 | How to retrieve audio session name similar to one in Windows' built-in mixer app? | I'm building a mixer app and need to get the user-friendly names for each audio session.
I tried:
IAudioSessionControl::GetDisplayName() method, but it returned empty string for each session.
Calling QueryFullProcessImageName() and GetModuleFileNameEx(), but they only output C:\Users\ since I have Cyrillic letters in... |
Calling QueryFullProcessImageName() and GetModuleFileNameEx(), but they only output C:\Users\ since I have Cyrillic letters in the path.
Then you are simply not displaying the path correctly. The presence of Cyrillic characters is not a problem.
I also tried getting all process names and PIDs like this, and later ma... |
69,036,493 | 69,036,727 | Optimize the trimming function | There is the void TrimRight( char *s ) function, which has a very long s-style string as an argument. A passed string consists of a lot of white spaces after a last word and, also, throughout its length. It is required that the function is to trim excess white spaces at the right.
I suggested an implementation looking ... | You never know where you may find a non-space character so you do have to look through the whole string.
You could do it with a lot less comparisons though.
Example:
void TrimRight(char *iterator) {
for(;; ++iterator) {
// Loop for as long as the string has not ended and non-space chars are
// found... |
69,036,530 | 69,036,758 | C++ Type deduction on template specialization fails on void parameter | I created a template class, where the constructor takes a std::function object.
The first template parameter indicates the return value of that function.
The second parameter defines the type of the parameter of that function.
#include <functional>
//Base
template<class R, class Arg>
class Executor {
public: ... | When you use the name Executor without explicit template arguments like in Executor<int, float>, C++ usually tries to figure out what you mean by class template argument deduction (or CTAD). This process doesn't look at any class template specializations (partial or explicit), only the primary template.
The primary tem... |
69,037,379 | 69,037,816 | How to convert a variable from an int into a template parameter only if it is convertable in c++ | I am trying to write a function that takes a variable of arbitrary type and sets it to an int value only if the type of the given variable can be converted to an int. My simplified code:
template <typename T>
void getInt(T& param)
{
int int_value = calculate_int_value();
if(std::is_convertible_v<int, T>){... | std::is_convertible_v was added in C++17, if your code uses it then this means that your compiler support C++17, which also has if constexpr:
if constexpr(std::is_convertible_v<int, T>){
param = static_cast<T>(int_value);
}
In a regular if, even if it always evaluates to false, whatever's in the if statement mus... |
69,037,788 | 69,037,860 | Does copy operator= exist for std::pair | I'm facing with an issue. Returning std::pair<T1, T2> from lambda function.
I'm trying to generate map with opened ifstream's, but compiler complains with this output:
/usr/include/c++/9/bits/stl_algo.h:4337:12: error: use of deleted function ‘std::pair<const std::__cxx11::basic_string, std::basic_ifstream >& std::pa... | std::pair is copyable only as long as whatever's in a std::pair is copyable. If you think about, for a few seconds, you will agree that this makes 100% sense.
std::pair<std::string, std::ifstream>
std::ifstream is not copyable. You cannot copy std::ifstreams. Putting it inside a std::pair doesn't make it copyable.
Bu... |
69,037,888 | 69,181,310 | How to solve TypeError: Failed to fetch in Qt for WebAssembly? | I am trying to run my Qt program in the browser using WebAssembly. I followed the guide and was able to get .html, .js and .wasm files in the end. However, when I try to run the index.html file by "double clicking" it, I get the above mentioned error. When I run using emrun --browser=chrome index.html, it works fine. H... | It turns out this behavior is expected: browsers such as Google Chrome disable reading from files, for security reasons. Uploading this to an online server will work.
|
69,037,985 | 69,038,206 | How to implement a method that creates a recursive lambda and returns it | I found a post on how to create a recursive lambda, but it is not clear how to return it from a function.
As far as I see, in the code below, captured func refers to a destroyed object:
#include <iostream>
#include <functional>
std::function<int (int)> make_lambda()
{
std::function<int (int)> func;
func =... | The Y combinator is your friend.
template<class R, class...Args>
auto Y = [] (auto f) {
auto action = [=] (auto action) -> std::function<R(Args...)> {
return [=] (Args&&... args)->R {
return f( action(action), std::forward<Args>(args)... );
};
};
return action(action);
};
now just:
return Y<int, in... |
69,038,057 | 69,038,673 | UNREAL: How do you store players progress on local device | Firstly I completely understand this will be fully documented somewhere, I just have no idea where to start due to being a beginner so please have a bit of mercy lol.
I just need to permanently store two pieces of data;
1: The amount of in game currency the player has collected
2: How many levels have been completed by... | Take a peak at the unreal engine docs. They should definitely be the first place to take your questions. Look at the FFileHelper module in the docs here https://docs.unrealengine.com/4.27/en-US/API/Runtime/Core/Misc/FFileHelper/. I believe that SaveArrayToFile() or another simmilar function would work for your case.
|
69,038,146 | 69,234,931 | Installing mouse causes segment fault in Dosbox | I'm making a simple program that supports GUI on DOS using Allegro4.
To implement mouse operation, I've created a shape object which presents current information of mouse.
Allegro provides lots of useful global variables such as mouse_x, mouse_y, mouse_b, etc. And these can be used only after the mouse driver is instal... | The reason was due to the engine I used for this program. It used to use a lot of CPU and RAM. After it is optimized and its CPU and RAM usage were decreased so much, it runs well in Dosbox, too.
But it is still slow, so I am on keeping on optimizing the engine.
|
69,038,199 | 69,328,120 | How can I use the third party library, Eigen, in Unreal Engine? | I'm working on an UE4 plugin and want to use the Eigen library. It appears that UE4 has already integrated the library, which you can see in Engine>Source>ThirdParty>Eigen.
I looked at other plugins, such as AlembicImporter, for guidance. To use Eigen, I see that they add "Eigen" in the build.cs file and write #include... | Looks like prebuilt UE4 doesn't include the "compiled" Eigen headers ("Dense", "Sparse", etc.), though it does include the Eigen "src" folder.
If you compile your Engine from source, you should have a complete Eigen install in the ThirdParty folder. You can then use that just like various Engine plugins do. But compili... |
69,038,256 | 69,038,461 | C++ Sort Array by 2nd Value | I am just beginning in C++, and I was wondering if there was a way to sort a 2D array by the second value in each array. I have not found any way to do in online, so I am asking here.
For example, you would start with:
int exampleArray[5][2] = {
{4, 20},
{1, 4},
{7, 15},
{8, 8},
{8, 1}
};
and after... | The short answer is: don't do that. C++ inherited it's built-in array from C, and it simply isn't really a very good fit for what you're trying to do.
Something that's reasonably similar and easy to implement would be to use std::vector instead of arrays.
std::vector<std::vector<int>> someVector {
{4, 20},
{1, ... |
69,038,861 | 69,039,034 | Inserting unique pointers in deep std::unordered_map | How do I insert unique pointers in this deep unordered map that I have?
std::unordered_map<uint64_t, std::unordered_map<uint64_t, std::unordered_map<uint64_t, std::unique_ptr<MyStruct>>>>
(C++14)
| Given a map
std::unordered_map<uint64_t, std::unordered_map<uint64_t, std::unordered_map<uint64_t, std::unique_ptr<MyStruct>>>> m;
and aunique_ptr
auto s = std::make_unique<MyStruct>();
you can insert the it in the map like this:
m[1][2][3] = std::move(s);
|
69,039,022 | 69,039,041 | Is an overridden pure virtual function, virtual? | Below you will see 3 classes. My question is why can I use override on the getArea() of the FunnySquare Class, even though it is not tagged as virtual in the Square Class.
My assumption is that an overridden pure virtual function is virtual even though it is not specified, but I am not sure that is true and could not f... | Yes, both Square::getArea and FunnySquare::getArea are virtual too.
(emphasis mine)
Then this function in the class Derived is also virtual (whether or not the keyword virtual is used in its declaration) and overrides Base::vf (whether or not the word override is used in its declaration).
|
69,039,030 | 69,039,164 | Wrapper efficiency: Vector of pointers vs vector of objects | This snippet of code implements a Detection object and a DetectionHandler that contains an array of objects std::vector<Detection>,
#include <iostream>
#include <vector>
#include <string>
class Detection {
private:
int id;
public:
int x, y;
Detection (int const& cx,int const& cy,int const& ci... | Storing pointers in your vector is usually less efficient than storing the objects directly, for the following reasons:
In most cases, you end up having to do a separate heap-allocation for each object (i.e. one new to create the object before adding a pointer to the object to the vector, and one delete after removing... |
69,039,366 | 69,041,988 | Can I pass a nested initializer_lists with different nested level in C++? | I am constructing a NestedInteger class to store mixed type of int, or vector of int, or vector of vector of int. For example: {1, {2, {3, 4}}, 5}.
It seems that the element types in the list should be the same, because I declare the constructor as this:
template <typename T>
NestedInteger(const std::initializer_list<T... | Use std::initializer_list<NestedInteger> for the parameter, and provide a constructor for single integers.
Example:
struct NestedInteger
{
NestedInteger(int x): stuff(x) {}
NestedInteger(std::initializer_list<NestedInteger> xs): stuff(xs) {}
std::variant<int, std::vector<NestedInteger>> stuff;
};
Test... |
69,039,450 | 69,039,673 | Aligning memory of SSBO that is an array of structs containing an array? | I'm flattening out an octree and sending it to my fragment shader using an SSBO, and I believe I am running into some memory alignment issues. I'm using std430 for the layout and binding a vector of voxels to this SSBO this is the structure in my shader. I'm using GLSL 4.3 FYI
struct Voxel
{
bool data; // 4
v... |
I'm not entirely sure what the alignment is
The specification is very clear as to what the base alignment of things are. Your problem is not in item #4 (std430 doesn't do the rounding specified in #4 anyway).
Your problem is in #2:
If the member is a two- or four-component vector with components consuming N basic ma... |
69,039,552 | 69,039,711 | Algorithm for creating an array of 5 unique integers between 1 and 20 | My goal is creating an array of 5 unique integers between 1 and 20. Is there a better algorithm than what I use below?
It works and I think it has a constant time complexity due to the loops not being dependent on variable inputs, but I want to find out if there is a more efficient, cleaner, or simpler way to write thi... | The simplest I can think about is just create array of all 20 numbers, with choices[i] = i+1, shuffle them with std::random_shuffle and take 5 first elements. Might be slower, but hard to introduce bugs, and given small fixed size - might be fine.
BTW, your version has a bug. You execute line choices[i] = generated; ev... |
69,039,624 | 69,039,663 | Why does is 'new' creating only one object and not an array of objects? | I am currently trying to make a Transposition Table for my chess engine, and am using a class with a dynamically allocated array member of a struct object.
class TranspositionTable {
private:
TranspositionEntry* data_;
public:
TranspositionTable() {
data_ = new TranspositionEntry[5]; //5 is an example b... | I just realized the problem. The array WAS actually being allocated. But since I was in the visual studio debugger, and the value was a pointer, I was actually only seeing the first value. HTHs for other people! My bad!
|
69,039,685 | 69,039,947 | How can I store reference of a class in the same type of class in C++? | I have a class Person and i want to store reference of another Person in that class but im getting the error : function "Person::operator=(const Person &)" (declared implicitly) cannot be referenced -- it is a deleted function
in the function getThem()
class Person {
private:
Person& them;
int number;
public:
... | I'm just answering this question, although I don't think it's a good idea to do things in your way. I believe what you need is std::list<Person> or something like this.
Let's get into the point. It's completely OK to contain a reference in class. But the problem is that, the auto-generated copy-assignment operator and ... |
69,039,822 | 69,049,208 | CBT Hook dll, to intercept window from being resized | I'm trying to write a dll to intercept a window from being resized, but i cant understand how to correctly specify the lParam in this case.
From the docs:
HCBT_MOVESIZE: Specifies a long pointer to a RECT structure containing
the coordinates of the window. By changing the values in the
structure, a CBTProc hook proced... | In the case of HCBT_MOVESIZE, the lParam contains the memory address of a RECT, so simply typecast the lParam to a RECT* pointer, eg:
extern "C" __declspec(dllexport) LRESULT CALLBACK CBTProc(
_In_ int nCode,
_In_ WPARAM wParam,
_In_ LPARAM lParam
)
{
if (nCode < 0) return CallNextHookEx(nullptr, nCo... |
69,039,836 | 69,040,690 | Increase maximum requests on chromium for http1.1 | I am compiling chromium/google-chrome and I am wondering how I can increase the maximum number of requests per domain for http1.1. I want to speed up the number of concurrent requests when accessing the cache. The cache is storing files in http1.1 & I'd like to fetch a large number of files concurrently. Currently the ... | This is here, in ClientSocketPoolManager.
net/socket/client_socket_pool_manager.cc:52
|
69,041,092 | 69,046,399 | How to export Chinese/Korean words to csv | I managed to export English text to a csv file and toimplement localization. Latin letters and words work fine for any language (e.g.: German) but my program cannot export Chinese/Korean words to the csv, instead showing weird characters:
For reference, the English version looks like this:
Here's the code I use to ge... | Microsoft products are notorious for using BOM in UTF-8 (which was initially invalid as by the Unicode specs, but due to widespread use in practice, is now allowed, but not recommended).
Excel uses it to determine the encoding of CSVs when you open them (e.g. by double click). If there is no BOM, it uses a locale 8-bit... |
69,041,202 | 69,041,270 | How to deal with WinAPI macros overriding some function names? | <windows.h> defines macroses for Ansi and Unicode versions of WinAPI.
I have a function named SendMessage in my class library. It works fine until <windows.h> is included before including my library. In this case SendMessage is overrided by the macros and the function name becomes SendMessageA or SendMessageW.
Is it p... | The real problem is that WinAPI's function definitions are at the C-preprocessor level, and so you have to write some ugly code to try to coexist with them.
If at all possible, you should rename your codebase's functions so that there is no collision with WinAPI.
Otherwise, you can write code like #undef SendMessage t... |
69,041,337 | 69,041,418 | bubble sort with with multiple conditions in for loop | Implementation 1
using namespace std;
void bubble_sort(vector<int> &a, int n)
{
for (int i = n - 1; i > 0; i--)
{
for (int j = 1; (j <= i) and (a[j - 1] > a[j]); j++)
{
std::swap(a[j], a[j - 1]);
}
}
}
This doesnt sort the given vector at all.
Implementation 2
using ... | for (int j = 1; (j <= i) and (a[j - 1] > a[j]); j++) {
std::swap(a[j], a[j - 1]);
}
is equivalent to
int j = 1;
while (true)
if (!(j <= i and a[j - 1] > a[j])) { break; }
std::swap(a[j], a[j - 1]);
j++;
}
whereas
for (int j = 1; j <= i ; j++) {
if(a[j - 1] > a[j])
std::swap(a[j], a[j ... |
69,041,667 | 69,041,942 | Template specialisation unable to resolve this-context method without forward-declaration | I have a template class which takes on roughly the form of the given code below.
template <int index = 0>
struct Thing {
void Hello();
void Greet(const char *name);
};
Which works just fine for its purpose, until one decides to try and call methods on itself. Say that you define the methods as shown below.
templat... | You might specialize the whole class to ensure that specialization are seen:
// Primary template
// generic one
template <int index = 0>
struct Thing {
void Hello() {/*..*/}
void Greet(const char *name) {/*..*/}
};
// Specialization for index == 0
template <>
struct Thing<0> {
void Greet(const char *name) ... |
69,042,071 | 69,070,958 | Connect mysql via ssh | how can I create a connection via ssh in c ++ in mysql?
It should work like this:
mysql -L -u <local database username> -h <database server ip address> -p
In any case, I would like to create the connection to the mysql database from a computer that is not in the same network and thus exchange data.
I just don't unders... | Here's a trivial implementation using boost::process:
bp::child c(bp::search_path("ssh"), "-N", "-L", "23306:localhost:3306", "user@hostname);
You can connect to localhost:23306 while c is alive.
|
69,042,428 | 69,042,761 | SSH session does not get terminated with cpp reboot command but with CLI command reboot | I have a small cpp application which will reboot the system. This works very well so far.
sync(); //need for data safety
reboot(RB_AUTOBOOT);
Unless you are connected via SSH and run this program on the connected device. Then the SSH connection hangs.
If you are connected via SSH and use the CLI commands
sudo reboot
... | The sudo reboot command will notify init that you want a reboot, init will kill all user-space processes and then do the actual kernel reboot.
The reboot syscall does the equivalent of sudo reboot -f (immediate reboot).
You could try to kill everything yourself and then invoke the syscall.
Or you could ask init, which ... |
69,042,787 | 69,043,956 | Creating a C++ makefile for an expected .o file? | I have two files, main.cpp and sub.h.
sub.h contains just this one line
int sub(int n, int *A, int *B, int *C);
and main.cpp is a very basic program where we take in user input for three int*s, A, B, C, and then call the int sub(int n, int *A, int *B, int *C) function. However, the implementation of int sub(int n, int... | Just include sub.o as a dependency of another target. No need to write a recipe for it.
For the main target you may do something like:
main: main.o sub.o
g++ -o $@ $^
This makes use of the built-in default rules that know how to compile main.cpp into main.o.
If the file ever goes missing, Make will come complain tha... |
69,042,891 | 69,049,804 | Problem in passing object to an function in main | How to pass object in main function. I want to show back to back send and received message by user1 to user 2 and user2 to user1, but when i calling a function using caller object it only shows user1 send msg
Please help me out to this. I am not understand what i do, can i make a separate copy of object of pass referen... | The problem is that in line 18 you're comparing this->msg.begin() to the end, instead of the actual position with the iterator.
Line 18: for (auto it = this->msg.begin(); this->msg.begin() != this->msg.end(); it++)
Should be
for (auto it = this->msg.begin(); it != this->msg.end(); it++)
The error you're getting is beca... |
69,042,905 | 69,043,260 | Create a boost asio ssl context from SSL_CTX | Is it possible to create an boost::asio::ssl::context from an existing SSL_CTX?
I would like to avoid copying all the options from one to the other (thus risking a bug).
| The first two constructors I see are
/// Constructor.
BOOST_ASIO_DECL explicit context(method m);
/// Construct to take ownership of a native handle.
BOOST_ASIO_DECL explicit context(native_handle_type native_handle);
So the second would logically be the one you're after:
Live On Coliru
#include <boost/asio.hpp>
#inc... |
69,043,068 | 69,043,117 | C2244: 'MyTemplateClass<T>::MyFunction': unable to match function definition to an existing declaration | Could someone explain why the following code compiles on GCC, but not in Visual Studio.
I get error C2244: 'MyTemplate::List': unable to match function definition to an existing declaration at the noted line.
#include <array>
enum class MyEnum
{
MAX = 5,
};
template<typename E>
class MyTemplate
{
public :
st... | As workaround, you might use:
template<typename E>
auto MyTemplate<E>::List()
-> std::array<int, NUMBER>
{
return std::array<int, MyTemplate<E>::NUMBER>();
}
Demo
|
69,043,140 | 69,043,403 | Should I use ExitThread() or Return from threads in C++ | I'm developing a server app to which multiple clients will connect. For every new client, I create a new thread and want to free all the resources of each client once the client disconnect.
My main thread doesn't need return values from client(s) so I just want to safely terminate threads and deallocate the resources u... | Does this answer your question? Sometimes it is very useful to read the reference:
ExitThread
Remarks
ExitThread is the preferred method of exiting a thread in C code. However, in C++ code, the thread is exited before any destructors can be called or any other automatic cleanup can be performed. Therefore, in C++ code... |
69,043,185 | 69,043,330 | Bypassing protected with inheritance and function pointer | I've seen the following pattern used a couple of times to access protected member functions.
class A{
public:
virtual ~A(){};
protected:
void foo(){}
};
class B : public A{};
class Hacky : public B{
public:
using B::foo;
};
int main(){
B b;
A& a = b;
auto ptr = &Hacky::foo;
(a.*ptr)(... | The type of ptr is void (A::*)(), not void (Hacky::*)(), so it is fine.
|
69,043,758 | 69,044,021 | Move overload and destructor theory. Can someone please answer if I'm right? | I'm trying to understand C++ move overloads and destructor calling right.
So I make test. My theory: The "foo" which returns foo_test() is created by move constructor, returned(as a copy ??) and then the "foo in" is destroyed. The returned "foo" from foo_test() is with move=overload assigned to "foo my" and then is des... | The presence or absence of move operators makes no difference, whatsoever, on how constructors and destructors work. Each object is constructed, and at some point gets destroyed, via its destructor. This is fundamental to C++. Move semantics doesn't change that. This is the first important thing to understand.
A move c... |
69,044,106 | 69,044,146 | Why is it not allowed to assign const char * to const variable? | char* name;
const char* _name = "something";
name = _name; // conversion from const char * is not allowed
I know it is deprecated in c++, but I want to know why...
Why C++ banned name to point some literals _name points to?
| Because name is non-const, it implies you are allowed to change the values.
For example:
*name = 'S'; // Change from "something" to "Something"
But _name was declared const, meaning you cannot change it.
You cannot take fixed, constant data, and assign it to a different variable; that is saying "It's OK if you change ... |
69,044,884 | 69,052,152 | Cannot link with glfw3.lib c++ | I am trying to compile a c++ file on command line with g++
i have this file
#include <iostream>
#include "C:\Users\Shaurya\Documents\Opengl\Dependencies\GLFW\include\GLFW\glfw3.h"
using namespace std;
int main(){
GLFWwindow* window;
if(!glfwInit()){
cout << "Window not initialized";
return -1;
... | So i solved this. First i was using the wrong libraries. I was provided with multiple versions of Libraries and i was using VC version. But when i used MinGW Version , it worked.
Moreover , i was using relative paths without typing ./ before them.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.