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 |
|---|---|---|---|---|
64,568,072 | 64,568,573 | Using std::unique_ptr in multiple inheritance | I'm writing a program that runs a simulation with two types of Animals - Wolfes and Rabbits.
In my code i have virtual interface class IAnimal, and base class called Animal. So, in one part of code, I need to make new instances of my animals, and I wrote this:
void Simulation::age_and_multiply_and_die() {
for (auto *an... | Your breed method returns a unique_ptr, so you should write your calling code to receive a unique_ptr:
std::unique_ptr<IAnimal> child = animal.breed();
Because unique_ptr doesn't support copying, you should move it when inserting into your data structure:
if (child)
{
animals.push_back(std::move(child));
}
Note... |
64,568,587 | 64,570,202 | How to make my CPP console app installable/redistributable which depends on some external files? | I am new to this coding world. So forgive me if any dumb question is asked or I made any mistakes
I am making a cpp tool which works well on my machine & also on others too. But inside it there is a function which works with some BAT & VBS files stored in a separate folder. Now the problem is when I am sharing the EXE ... | How about creating installer using setup creator(https://installforge.net). You can package multiple files in the installer and select installation directory to something like c:/program files/your_application_name.
That way your executable and other files will be in the same folder and it will also create a start menu... |
64,568,689 | 64,569,860 | C++ Struct : Function definition does not declare parameters | I created 2 Structures tnode and node.
struct tnode
{
int data;
struct tnode *left;
struct tnode *right;
};
struct node
{
struct tnode *treenode:
struct node *next;
};
struct node* InsertNode(struct node *head, struct tnode *_treenode)
I got these errors:
[Error] function definition does not decl... | The definition of struct node has the line struct tnode *treenode:. It should end with a semicolon not with a colon. If you change that, everything works fine. Sadly the compilation errors are not helpful at all to find that out.
|
64,568,708 | 64,568,888 | c++ member initializer with const getter in a class | Hi I get the runtime error with memory acccess violation when trying to run the following:
class MyMutable{
private :
std::string m_name;
mutable int m_DebugCount;
public:
MyMutable()
: m_name(" "), m_DebugCount(0) {}
MyMutable(std::string& newName)
: m_name(newName), m_DebugCount(0) {}... | You should avoid c-style casts and use static_cast instead as it is safer. Changing your code to use static_cast:
const MyMutable k(static_cast<std::string&>("Hello"));
Results in the error:
error: non-const lvalue reference to type 'std::string' (aka 'basic_string<char>') cannot bind to a value of unrelated type 'con... |
64,568,828 | 64,568,959 | Why does "inet_pton" return 0 when I'm using localhost? | I'm working on a socket interface where an application is trying to connect to another, this is my socket initialisation:
const char* pszLocalHost = "localhost";
int intSocket = socket(AF_INET, SOCK_STREAM, 0);
if ( intSocket == 0 ) {
clsDebugService::exitWhenDebugQueueEmpty("Failed to create socket!");
}
str... | That same manual clearly states that the first argument must either be an IPv4 address of the form "ddd.ddd.ddd.ddd" or an IPv6 one. Since "localhost" is neither of those, the call fails. Using "127.0.0.1" should work though.
Here's the quote regarding IPv4 from the manual:
This function converts the character string ... |
64,568,945 | 64,569,268 | use class template in its definition | In the following code, why no recursive instantiate
template <class T, T v>
struct integral_constant {
static constexpr T value = v;
using value_type = T;
using type = integral_constant<T, v>; // no recurse?
constexpr operator value_type() const noexcept {
return value;
}
constexp... | Your code does result in infinite recursion, you can use
integral_constant<long, 1>::type::type::type as many times as you like.
This isn't a problem though as the compiler only instantiates templates that you are using not all the templates that you could possibly use.
You would have an error if you tried to declare a... |
64,569,156 | 64,569,236 | Can the this pointer be polymorphic? | I thought that typeid was supposed to reveal the most derived type of it's parameter. But when I use it in a constructor like the below, it seems unaware of what the real type of the pointer is.
When I pass it off to another class, it also seems to not know what the type is.
Is this because the this pointer doesn't kno... |
Can the this pointer be polymorphic?
Yes, if the pointed class is a polymorphic class... but not during its onstruction because when the constructor of the base is running, then the derived class constructor will not have completed yet.
Is there a way around this to determine the real derived type of the this pointe... |
64,569,281 | 64,638,901 | Overwrite std::cin read-buffer after reading password | After reading a password from std::cin
std::cout << "Password: ";
SecureString pw{}; // secure string, wipes automatically on destruction
SetConsoleEcho(false); // hide input in terminal
std::getline(std::cin, pw); // input the password
SetConsoleEcho(true); // switch echo back on
the password stays stored in the read... |
Or is there a way how to avoid using the buffer in the first place?
I found a cross-platform way (Linux, Mac, Windows) how to avoid the read buffer of cin using a readline replacement library. I used replxx but other readline replacement libraries will likely do as well.
I created a simple wrapper class PasswordInput... |
64,569,529 | 64,569,657 | Two way communication using sockets | I am trying to implement two way communication using sockets and not quite sure where I'm going wrong. I have an application that launches a child application, the child application then tries to communicate with the application that launched it, but I am not getting anything.
In the application that launches the chil... | This is operating system specific.
For Linux, read Advanced Linux Programming then syscalls(2), socket(7), unix(7), fifo(7), pipe(7)
With Qt, consider using QSocketNotifier in your main thread.
You might also want to use POCO, ONCRPC, JSONRPC, Wt (perhaps with libcurl) or libonion.
You could get some inspiration by stu... |
64,570,163 | 64,570,239 | Update script that is running in the background with command line arguments | I want to make a script that can run in the background, but work like a command line tool at the same time. I have no experience with making daemons, so I have no idea if that could do what I am describing better.
I would like a loop that uses some values, and I want to be able to change these values through the Linux ... | You'll need two programs -- one that runs in the background, and a second one that communicates with it to tell it to update its values.
There are various options on how to do this depending on your requirements. One possibility is to have the background program accept TCP connections and take commands over them. Ano... |
64,570,178 | 64,570,270 | Is there unit tests for STL containers? | Is there ready unit tests for testing if STL containers are working correctly, something that was used by compiler creators?
I'm making a simple port of the STL in C and need to test the data structures and thought that STL unit tests already existed, but didn't find anything
|
Is there unit tests for STL containers?
STL does not exist anymore. Read the C++11 standard n3337 and see this C++ reference website. Consider also using Boost.
Both recent GCC and recent Clang provide testsuites for the standard C++ containers library, whose implementation is practically tied to the compiler (becaus... |
64,570,318 | 64,570,636 | c++ comparator sorting using auxillary array | I have an array (say values) that that cannot be modified. I want to know if the values in this array are sorted what will be their eventual position/index. So, for this I am simply using code as below:
#include <iostream>
#include <algorithm>
#include <vector>
#include <numeric>
int main() {
std::vector<unsigned>... | Your code sorts the indices by their value in the array. So the output will have at the first position the index of the smallest value, in the second the index of the second-smallest and so on.
To get what you want out of that, you can, for example, do the following:
std::vector<unsigned> result(position.size());
for(u... |
64,570,871 | 64,574,434 | Create instance of singleton class in C++ | I have a Singleton class foo:
class foo
{
static foo* pointer;
foo();
public:
static foo* instance();
static void destroy();
}
foo::foo()
{
}
foo* foo::instance()
{
if (pointer == 0)
pointer = new foo();
return pointer;
}
void foo::destroy()
{
delete pointer;
pointer ... | If MockClassfoo if inherited from foo, make foo not final:
make the constructor and the static foo pointer;* protected
define a getInstance in you Mock class that allocates a MockClassFoo instead of the foo one
It should do the trick.
Some hints about your code:
A ponter in C++, should be initialized using nullptr ... |
64,572,061 | 64,572,866 | A simple tic-tac-toe program in Visual Studio 2019 causes Windows Defender to report threat | Create a new C++ console application using Microsoft Visual Studio 2019.
Add a file, name it tictactoe.c.
Paste the code given below -
#include <stdio.h>
int main(void)
{
int player = 0;
int winner = 0;
char board[3][3] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'} };
//The main game lo... | It appears to be a false positive from Windows defender.
Similar problem has occurred with other compilers like MinGW. Refer to Code::Blocks MinGW Windows Defender Trojan:Win32/Fuery.C!cl for one such instance.
The way to circumvent this is to mark your binary as an exception in Windows 'Allowed threats' window in 'Vir... |
64,572,293 | 64,572,400 | Cannon run an overridden method | There is a class "Mario". This one has an virtual method: void mission(). I want override this method and run it from base class code in parallel.
But output of the following code is:
Mario works hard
LOL
Code:
#include <iostream>
#include <thread>
class Mario
{
std::thread workingField;
bool hasStarted = fal... | The problem is, the main thread is too fast. Your main method ends, the deconstruction of mw starts, MarioWorker gets destructed and once it starts destructing the Mario it joins the thread. The thread never sees the MarioWorker as it was already destructed, all it sees is the Mario.
|
64,572,350 | 64,572,965 | Error in ofStream, Qt 5.14.2 can 't write string into file | I am trying to write my program from VS (MVCS) for Qt(MinGb)
I am using ofstream and has a following code:
#include <fstream>
#include <string>
#include <iostream>
#include <exception>
using namespace std;
void WriteToFile(ofstream* fileToWrite, std::string StringNeedsToWrite)
{
if (fileToWrite)
{
if (I... | They differ in their make files and project files. A common problem is that moving a project from one environment to another entails big mistakes.
For example, MinGW under Linux does not have standard streams, but there is windows.h.
Such problems should be taken into account and studied at the stage of developing a pr... |
64,572,766 | 64,573,197 | Save and pass to function list of template arguments in C++ | I want to save and pass list of template arguments to function.
Like std::thread passes arguments to a thread. Types of arguments are templated and arguments count is not static.
Example, how it will work:
class CallbackList {
public:
Callback(/* Type of list of template args */ args) {
this->saved_args = a... | If you do not want your callback to depend on the types of the arguments you have to use some kind of type erasure. You can, for example, use std::function from <functional>:
#include <functional>
#include <iostream>
class Lazy_Callback
{
public:
template <typename F, typename ...Args>
Lazy_Callback(F && f, Args ... |
64,572,884 | 64,573,818 | Passing array element to template | I think code below is self explanatory. I can easily pass static variable to template parameter and it work as expected. Using static array will cleanup code, so it look nicer, but unfortunately it doesn't compile due to error I pasted in comment. Note that it was compiled by gcc 10.2 with c++17 flag.
So the question i... | There were an answer here (which was deleted) that gave me an idea how to solve it. It's not perfect, but also not bad.
#include <iostream>
#include <vector>
#include <tuple>
using DataTransfer = std::tuple<char, int>;
using DataPool = std::vector<DataTransfer>;
typedef struct Event
{
DataPool dataPool;
c... |
64,573,619 | 64,573,963 | Retrieve pointer that can acess all the elements of arrays stored in a std::vector | Is it possible to have a pointer that points to the contiguous buffer that is used by a vector?
For example (see below please), here std::vector<unsigned char*> vec contains two differently sized unsigned char* pointers. I need to have a buffer pointer that points to all pushed data in this vector. I'd guess that this ... |
Does buffer point to all data in vec? i.e. buffer[0] = a, buffer[1] = b, buffer[2] = c, buffer[3] = x?
It doesn't. It points to the beggining of the array stored in first element of the vector.
Are the two ways of printing the elements of the vector I use in this example fine?
They are not, those arrays are not nul... |
64,573,971 | 64,574,310 | C/C++ What does casting do in the low level? | Somebody told me that type-casting C conversions does only change how the system interprets the information (for example, casting the char 'A' into int does return 65 when using cout to print it since in
memory it stays as 01000001).
However, I noticed that, when casting floating point numbers into same width integers,... | If you want to get Y = 4614256650576692846, you can use:
double X = 3.14159;
long long Y = *( (long long*)(&X) );
This will cast a double pointer to a long long pointer, and then the compiler thinks that (long long*)(&X) is somewhere a long long stores.
But I don't advise you to do so because the result is based on ho... |
64,574,214 | 64,574,829 | Reference collapsing rules not applying as expected? | I am refreshing my memory on how perfect forwarding works in C++. I realize that a call to std::forward is forced to provide an explicit template parameter for a reason (i. e. when dealing with rvalue references that are actually lvalues), however when doing a sanity check on actual code, I was surprised by this (somew... | Actually, no referencing collapsing occurs. The relevant function template to pay attention to, i.e., the one selected, is:
template<class T>
T&& fwd(T& t) { // <-- not a forwarding reference
return static_cast<T&&>(t);
}
Note that this function template has no forwarding references – the function parameter, t, is... |
64,574,316 | 64,574,494 | What's with allocator in vector? | vector<int> data(istream_iterator<int>(cin),
istream_iterator<int>{}); cout<<"Size is : " << data.size() << endl; //compile success
vector<int> data1(istream_iterator<int>(cin),
std::allocator<int>{}); cout<<"Size is : " << data1.size() << endl; //compile failure
error: no matching function for call to ‘std::ve... |
Why is the first statement fine
Because vector has a constructor that accepts two iterators (and an allocator with default argument). Those iterators represent beginning and end of an input range.
but second [is not]?
Because vector doesn't have a constructor that accepts a single iterator and an allocator.
|
64,574,662 | 64,624,054 | Allocating and Deallocating memory across shared lib boundaries | When working with windows dll's, it is established that we should limit the memory allocation/deallocation within the dll boundary since the dll could be using its own heap.
So we have export allocators and free functions to from dll.
IsomeInterface* getObject();
void freeObject(IsomeInterface *object);
This way the o... | As long as you stick with Glibc or other "normal" allocators (jemalloc, tcmalloc, etc.) the heap state will be shared by all libraries and thus you'll be able to free memory allocated somewhere with malloc anywhere you want.
In theory it may be possible to circumvent this. For example some library may be linked with cu... |
64,574,685 | 64,574,741 | Run-Time Check Failure #2 - Stack around the variable 'c2d' was corrupted. with c++ | I'm studying for an exam and this is on my practice test. The question is "Which type of error does the following code fragment cause?"
Why is there an error?
struct C2D {
double x, y;
};
class Polygon {
int point;
C2D arr[];
public:
Polygon(int point_, C2D arr_[]) {
point = point_;
mem... | You didn't specify number of elements for the member
C2D arr[];
so there are no memory allocated for that.
You should use std::vector to allocate elements dynamically.
#include <iostream>
#include <vector>
#include <cstring>
using std::cout;
using std::endl;
struct C2D {
double x, y;
};
class Polygon {
... |
64,574,964 | 64,576,884 | Replication of same behaviour without using decltype | The code below comes in handy for fast debugging. It can pretty print containers like vectors from the STL while also being able to provide the printing-ness property for fundamental and streamable types using SFINAE techniques.
I would like to replicate the same behaviour without the use of decltype. Any other neat te... | Sure, here's an implementation using sizeof:
template<class T, class = std::false_type>
struct is_streamable_object : std::false_type {};
template<class T>
struct is_streamable_object<T,
std::bool_constant<sizeof(std::cerr << std::declval<T>()) == 0>> : std::true_type {};
Example.
Other keywords you could use inc... |
64,575,376 | 64,580,477 | Error when adding NORMAL to the inputLayout | I'm trying to add the NORMAL vector into the inputLayout but when I add this line, I have this error :
D3D11 ERROR: ID3D11Device::CreateInputLayout: The provided input signature expects to read an element with SemanticName/Index: 'NORMAL'/0, but the declaration doesn't provide a matching name. [ STATE_CREATION ERROR #... | You cannot change the layout order in Direct3D 10 or later due to shader linkage rules.
Either make your shader use:
struct VSinput
{
float3 pos : POSITION;
float3 test : NORMAL0;
float2 textCoord : TEXCOORD0;
};
-or- make your input layout use:
{"POSITION",0,DXGI_FORMAT::DXGI_FORMAT_R32G32B32_FLOAT,0,0,D3D11_INPUT_PE... |
64,575,784 | 64,575,920 | Is std::move overkill in this situation? | I was wondering if using the std::move() in this example is overkill or computationally more expensive than simply copying it? I would really like to know.
class Student
{
private:
std::string _studentName;
int _studentGrade;
public:
Student() : _studentName("No Name"), _studentGrade(0)... | Reading the core guidelines at F.call: Parameter passing, we can deduce a few recommendations.
Use move only when you want to optimize for rvalue. If you find that it does an improvement on performance, it's up to you to do it.
You could receive by value then move as it optimises rvalues calls into your setters, but it... |
64,575,860 | 64,576,089 | Is there a better way to define a global variable? | I'm looking for a better way to define a global variable. This is just a small banking app to practice using functions. Is this the correct way to define the variable according to C++ standards? I'm not 100% sure on this one. I defined it outside of main(), but if I remember correctly, this is a no no. I tried creating... | You can pass total to a function with & in front of it. It is known as reference in C++ and you can modify given object inside a function, not only it's copy. Examples. And in your code:
int deposit(int &total) { ...your code... }
Overall I don't think calling menu inside every function is a good idea. With each func... |
64,576,236 | 64,593,890 | Android 11 - System.loadLibrary for native C++ library takes 60+ seconds, works perfectly fast on Android 10 and below | In our game application for Android which is based on the game engine cocos2d-x, with most of the code being written in C++, we have a very strange and critical issue since Android 11:
When the native library gets loaded in onLoadNativeLibraries it now suddenly takes 60+ seconds. Before Android 11, it all worked fine a... | Short Answer:
It's a bug in Android 11 fixed by google but not deployed yet.
Meanwhile, if you don't care about calling static and thread_local variables destructors in your lib when program is exiting/library is unloaded, pass the flag -fno-c++-static-destructors to the compiler. (see long answer for a more granular s... |
64,576,289 | 64,583,669 | Undefined reference when trying to use Box2D's b2Body::SetUserData(void*) | Here's some simple code to reproduce the problem:
#include <box2d/box2d.h>
int main()
{
b2World world(b2Vec2_zero);
b2BodyDef bdef;
b2Body* body = world.CreateBody(&bdef);
body->SetUserData(body);
return 0;
}
That should compile according to everything I've read, and (for the pedants) I guess it t... | Turns out SetUserData was recently removed in Box2D 2.4.1. I've also noticed some of my old code that used the b2BodyDef method (I had forgotten I used that in the past) would no longer compile; previously it was just a direct void* pointer without the issue I mentioned.
Instead of doing foo->SetUserData(bar), now it s... |
64,576,392 | 64,576,561 | What is the C++ equivalent using std::priority_queue (C++ STL) of this Java code | basically, it's gonna be a min-heap of vectors where priority is based on index 1 (0-based) of the vector.
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> (a[1] - b[1]));
I tried
priority_queue<<vector<int>, vector<vector<int>>, [](vector<int> a[1], vector<int> b[1]){
return a[1] < b[1];
}>
| The elements of the queue are vectors, and thus that is the type of object that are being compared to each other. vector<int> a[1] is not a vector, but an array of vectors of length 1 (although as a function argument, it will be adjusted in this case to be a pointer to the element of that array i.e. pointer to vector).... |
64,576,641 | 64,576,680 | How do you make the CreateFileA WINAPI function work in this form? | I have this WINAPI function:
HANDLE file{ CreateFileA((LPCSTR)"\\\\.\\" + (???) ", FILE_APPEND_DATA,FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL) };
I have a global variable "Path" of type std::string & a username which is type TCHAR*, I assume I need to convert those two variables to LPCSTR, howeve... | Simply concatenate the two std::strings into a new std::string, and then use its c_str() method, eg:
std::string Path = ...;
std::string username = ...;
std::string fullpath = Path + username;
HANDLE file{ CreateFileA(fullpath.c_str(), ...) };
Or simply:
std::string Path = ...;
std::string username = ...;
HANDLE fil... |
64,576,827 | 64,580,394 | C++ DirectX 9 unresolved external symbol | Yes I included all the libs but every time I run my program in x64 it gives me an unresolved symbol but works perfectly in x32??
Severity Code Description Project File Line Suppression State
Error LNK2019 unresolved external symbol Direct3DCreate9Ex referenced in function "int cdecl DirectXInit(struct HWND... | With the legacy DirectX SDK, you have to set up distinct x86 vs. x64 library include paths:
In VC++ Directories for 32-bit configurations:
$(IncludePath);$(DXSDK_DIR)Include
$(LibraryPath);$(DXSDK_DIR)Lib\x86
In VC++ Directories for 64-bit configurations:
$(IncludePath);$(DXSDK_DIR)Include
$(LibraryPath);$(DXSDK_DIR)L... |
64,577,173 | 64,577,590 | Define multiple C++ class member function | class myclass {
public:
myclass();
myclass(int);
void func();
~myclass();
};
What I am currently doing is like:
myclass::myclass() {
cout << "Default Constructor";
}
myclass::myclass(int a) {
cout << "Normal Constructor";
}
void myclass::func(){
cout<< "function f";
}
But every definition ... |
Can I do something like: ... Gathering all the member functions under the same class and define them together?
Not when defining the functions outside the class definition. Repeating the class name for each member function is necessary in that case.
|
64,577,242 | 64,577,421 | Insert element '0' in the middle of the queue, if the number of elements is even, and if it is odd, then after the middle element | #include <iostream>
#include <queue> // подключили библиотеку queue
using namespace std;
int main() {
setlocale(LC_ALL,"rus");
queue <int> q; // создали очередь q
cout << "Пользователь, пожалуйста введите 7 чисел: " << endl;
for (int h = 0; h < 7; h++) {
int a;
cin >> a;
q.p... | Queue jumping is not allowed. A queue does not have an operation for inserting into the middle. As such, queue is probably not a good choice of data structure for your use case.
In order to achieve the corresponding result, following algorithm can be used:
repeat initial size / 2 times:
push front element of the ol... |
64,577,661 | 64,578,768 | why return type of getInstance method should be return by reference? | #include<iostream>
using namespace std;
class A{
private :
A()
{
cout<<"Constructed"<<endl;
}
~A()
{
cout<<"Destructed"<<endl;
}
public:
static A& getInstance()
{
static A a;
return a;
}
};
... | Just a few more additions:
The return type doesn't have to be a reference, but since the destructor of the class you are returning is private, any function (not this specific one) which returns an object of that type cannot return the actual object.
This is because the caller cannot make a copy of that object. When pas... |
64,578,042 | 64,578,458 | Can't Assign 64 Bit Number to 64 Bit Min in C++ | I'm new to C++, so sorry if this sounds like a dumb question. I'm attempting to assign the 64 bit minimum (-9223372036854775808) to an int64_t (from cstdint), however I'm getting the current error message:
main.cpp:5:27: warning: integer literal is too large to be represented in a signed integer type, interpreting as u... | This is exactly why the INT_MIN family of macros are often defined like -INT_MAX - 1 on a 2's complement platform (virtually ubiquitous and compulsory from C++20).
There is no such thing as a negative literal in C++: just the unary negation of a positive number which produces a compile time evaluable constant expressio... |
64,578,304 | 64,581,031 | Nested CMakeLists.txt files in CLion | Using CLion, I have a project structure that looks like this:
You'll see that in the root there are an include directory, a src directory, a lib directory, a cmake-build-debug directory, a CMakeLists.txt file (see red arrow), and a tests directory. The project builds a shared object into lib using the root-level CMake... | You don't execute a CMakeLists.txt. It is read by cmake (the root CMaksLists.txt file), which is called by CLion. However, CLion only passes the root CMaksLists.txt file to cmake. Even if you call cmake yourself you would only pass this root CMaksLists.txt file.
If you want to define targets (or anything) in other CMak... |
64,578,397 | 64,578,520 | c++ access other members of instantiating class from member object | I am fairly new to c++ and now trying to solve the following problem:
There are two user defined classes in separate files. I want to access the members of the instantiating class (Master) from one of its members (MyObject). So in this example I want to access the other_member_ variable from the my_object instance:
Mas... | //master.h
#pragma once;
class MyObject; // declaration (incomplete type, but ok)
class Master
{
// ...
public:
Master();
MyObject* my_object_;
int other_member_;
// ...
};
// Master.cpp
#include "master.h"
#include "MyObject.h"
Master::Master() : my_Object_(new MyObject(this)) { }
You probably... |
64,579,702 | 64,579,787 | Assigning a const_iterator to an iterator | I have the below snippet of code (which you can run here: http://coliru.stacked-crooked.com/a/2f62134b5c125051)
#include <iostream>
#include <set>
#include <map>
int main()
{
std::set<std::pair<const int, const int>> const mySet{{0,0}}; // value_type = std::pair<const int, const int>
for (std::set<std::pair<c... | You cannot modify a sets elements. Keys must be const to ensure the invariant promised by the set: elements are sorted and unique. A maps elements are sorted too, but you can modify the mapped value of the elements (keys are const as well). Elements of a std::map<A,B> are std::pair<const A,B>.
On cppreference you can r... |
64,580,017 | 64,580,041 | Program crashes while adding a new node in linked list in c++ | I am trying to implement an insert function of the linked but as soon as I add the third element the program just crashes and execution is stopped, even though the same code worked on hackerrank's compiler.
Here is my code.
#include<bits/stdc++.h>
using namespace std;
class Node{
public:
int data;
... | The line
while(head -> next != nullptr) current = current -> next;
in the function insert_tail is wrong. It will run endlessly when head->next is not nullptr.
It should be
while(current -> next != nullptr) current = current -> next;
|
64,580,432 | 64,581,272 | How to pass and save a 2D array to an object using the constructor | There are a lot of solutions available for passing 2D arrays to an function, but I can not figure out how to assign that array to my object in the constructor. Any help would be appreciated.
I have an array of bytes:
int demo1_rows = 9;
int demo1_id[9] = { 0x0A1, 0x0A2, 0x0A0, 0x0A1, 0x0A2, 0x0A0, 0x0A1, 0x0A2, 0x0A0 }... | If you want to fix your current code, with minimal changes, and store the multidimentional array as a reference, you can do this:
typedef the array type, and store it as a reference. Then use the member initializer list in the constructor to take the reference and assign it. This will be similar to storing the pointer ... |
64,580,487 | 64,580,860 | unable to read and write using same fstream object in c++ | I'm trying to use same fstream object for first write the file and after that read the file.
when I'm using below code then the codes of writing the file is working but I'm getting junk output instead of texts which written in the file.
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int mai... | This code has two separate problems. The first (which others have already pointed out to at least some degree) is that your loop isn't detecting the end of the file correctly. In fact, almost any time you use while (!file.eof()) or while (file.good()), it's going to be a mistake--it won't detect end of file at the righ... |
64,580,758 | 64,580,866 | Variadic templates: One method per template argument | Is there a way to automatically create one method per variadic template argument?
For example, in the code below, I want to be forced to override void x(a &v) and void x(b &v) in class i:
#include <type_traits>
#include <stdlib.h>
#include <stdio.h>
class a {
};
class b {
};
template <typename ...T>
class t {
public... | You can make a t_impl that holds the virtual function for a single T like
template <typename T>
class t_impl
{
public:
virtual void x(T &v) = 0;
};
and then t would inherit from it like
template <typename ...T>
class t : t_impl<T>... // can use public, protected or private inheritance
{
public:
using t_impl<T>... |
64,581,229 | 64,581,519 | CMD cannot read input characters correctly | I tried to use system function to run a cmd command, but I can't get the command output, Because My Windows is Italian When I type / in my system() function to call cmd its getting actually - and not getting / I tried this in my cmd and is receiving this - instead / ,I tried to use chcp 437 for English cmd but , it did... |
You should never use system(). You are programming in C++. There is no need to use system() since you have access to everything in the, well, system :D. system() was written in C after all.
And there is the security risk: someone could replace system() or the command you are trying to run using system() in your machin... |
64,581,292 | 64,581,350 | Type conversion (*void[] to vector C++) | In the following code:
// TODO: -- original
// void *buf[n]; // <== no variable length arrays in (V)C++
// TODO: -- C++
// std::vector<void*> buf(n);
for(unsigned i=0; i<n; ++i)
buf[i] = tlsf_malloc(impl->tlsf, chunk_size);
bool outOfMem = false;
for(unsigned i=0; i<n; ++i)
outOfMem |= (buf[i] == nullptr)... | Just replace void *buf[n]; with std::vector<void*> buf(n);. Everything should work. Do not use push_back().
|
64,581,638 | 64,582,256 | Can someone explain the following C++ Syntax? | I recently came across a line that I do not quite understand in a C++ computer vision project someone else wrote. The project uses OpenCV library. The line is inside the constructor of a struct called Board.
struct Board {
BoardID id;
Origin origin;
Vec<int> offset;
std::vector<std::vector<int>> pattern... | Looking at the documentation for OpenCV, it appears cv::Mat has an overloaded operator= that takes a scalar: see this overload. This overload writes the value on the RHS to all elements of the LHS matrix.
The other part of the key is that apparently copying a cv::Mat is a shallow copy: that is, no data is copied, just ... |
64,582,042 | 64,591,733 | Problem understanding code from C++: Concurrency in Action | I'm studying Concurrency in Action (first edition, C++11) and I have some problems understanding part of code from chapter 8, page 228, in which the autor shows a multithreaed-version of QuickSort in the context of dividing data recursively.
The whole code is:
template<typename T>
struct sorter
{
struct chunk_to_s... | The code uses std::partition to divide the data into two parts: those less than the partition value, and those not less than the partition value.
Then it uses the splice member function of std::list to move the nodes that are less than the partition value into a new list, and adds it to the list of chunks to sort. It s... |
64,582,785 | 64,601,914 | Executable Without .RELOC Section | I am using MSVC 2019. I have compiled a simple C++ code (Hello World...). When I compile it in release mode in x86 architecture, there is a .reloc section, but when I compile it in x64 architecture, the .reloc section does not exist.
What is the reason of this? I need executables with a .reloc section.
Best regards.
ED... | The question is about the PE layout generated by MSVC in x64 builds. Leaving out details that are not relevant, it can be restated in plain C as follows.
// main.c
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
int __stdcall rawMain()
{
OutputDebugStringA("Hello World!\n");
return 0;
}
The minimalistic C p... |
64,582,810 | 64,582,949 | Problem with For Loop and Base Class Pointer which points to a derived class | I'm slightly perplexed. In my int main() I have created two std::unique_ptr, one which points to the parent class "User" and another one that points to the derived class "Admin". I subsequently std::move() these two std::unqiue_ptr to a std::vector of std::unique_ptr. I then pass the std::vector to a stand-alone functi... | You can do it by using dynamic_cast(), like so:
void DisplayPrivileges(std::vector<std::unique_ptr<User>>&users) {
for (std::unique_ptr<User>&user : users) {
user->BasicUserFunction();
auto admin = dynamic_cast<Admin *>(user.get());
if (admin) {
admin->AdminFunction();
}... |
64,582,899 | 64,583,074 | Invalid initializer for array member | I'm trying to specify an attribute of a class as being a array of 5 position of the type Stock like follows:
#include "stdio.h"
#include "string"
#include "array"
#include "./stock.h"
#ifndef WALLET_H
class Wallet {
public:
Wallet(std::string name, Stock stocks[5]) : name_(name), stocks_(stocks) {}
//! Cal... | In your Wallet() constructor, the Stock stocks[5] parameter is just syntax sugar, the compiler is actually passing Stock *stocks instead. A fixed-size array can be passed in a parameter only by reference or pointer. But you can't initialize an array from a pointer, which is why your code fails to compile.
In this cas... |
64,582,904 | 64,582,998 | I need to convert an int parameter into a linked list field | I created a link list and an integer field to represent the linked list.
Then I assigned the integer field to 0.
I don't know how to convert the int parameter into the linked list.
template<typename T>
struct Node{
T data;
Node* next;
};
class Integer{
private:
Node<int>* real_num;
public:
Integer(){
re... | The constructor assigns a value to a variable in a structure which has been declared but not itself constructed.
Add this to the top of your constructors.
Node<int> * real_num=new Node<int>;
Only after the Node has had memory allocated, etc is it valid to reference a variable in the struct that real_num only points to... |
64,583,297 | 64,583,346 | Printing My Vector Doesn't Work (No Compiler Errors) | What I must make:
A program that makes a double vector with at least 30 negative and positive elements. I also must have functions to calculate/print the standard deviation, the mean value, the highest value, and the lowest value of the vector. Next, I will need a split() function to split the values of the double vect... | Your vectors
vector <double> positive;
vector <double> negative;
are empty, so accessing their elements is undefined behavior. You need
if (data[i] >= 0)
{
positive.push_back(data[i]);
} else if (data[i] < 0)
{
negative.push_back( data[i]);
}
|
64,584,010 | 64,584,079 | Why derived class pointer which points to base class can call derived class member function? | #include <iostream>
using namespace std;
struct Base {
void doBase() {
cout << "bar" << endl;
}
};
struct Derived : public Base {
void doBar() {
cout << "bar" << endl;
}
};
int main()
{
Base b;
Base* b_ptr = &b;
Derived* d_ptr = static_cast<Derived*>(b_ptr);
d_ptr->doBa... | Yes, it is undefined behavior.
There is no compile-time error because you used static_cast - this is a way to tell the compiler "I know the type better than you do". You are telling your object is Derived. You lied to the compiler - thus the undefined behavior.
It happened to work because doBar() does not use any Deriv... |
64,584,239 | 64,591,626 | Is it possible to use QML and QtQuick without QApplication? | I am looking for a way to write an audio plugin using Qt. Audio plugins usually are dynamic libraries, not applications (http://teragonaudio.com/article/How-to-make-VST-plugins-in-Visual-Studio.html). While searching, I found on the audio forum contains the post QT etc for vst UI:
QtQuick/QML is perfect for any GUI de... | I read through all the posts in your link and I think the author was being very loose with his terms. When he says:
It's really just best to avoid all the QApplication and old Qt graphics framework techniques.
He appears to simply be referring to avoiding Qt Widgets. The docs say "QApplication specializes QGuiApplica... |
64,584,449 | 64,584,608 | Pass std::vector to constructor without copy | After a 2 years break, I've started using C++ again, and I'm pretty rusty. I'm trying to implement a 5-coloring algorithm for a graph, but I'm having trouble with vectors.
I've 3 classes (snippets below). The problem is that somewhere in Graph::Graph(), a copy constructor is called on both vectors (While troubleshootin... |
Pass std::vector to constructor without copy
Move instead of copy:
Graph(std::vector<Edge> edges, std::vector<Vertex> vertices)
: _edges(std::move(edges)), _vertices(std::move(vertices))
// example usage
Graph g(std::move(edges), std::move(vertices));
However, avoiding copying of the vector is not sufficient fo... |
64,584,593 | 64,584,724 | Is there a way to not have a union "over-compensate" alignment? | I have a structure that looks like this:
class Foo {
union {
size_t cap;
char buff[15];
};
bool isHeap;
};
I would like sizeof(Foo) to equal 16, but sizeof(Foo) is 24 on 64 bit computers. I think this is because size_t forces the alignment of the union to be 8, and thus there is 1 wasted b... |
struct {
size_t cap;
char ignore[7];
bool isHeap1;
};
C++ doesn't have anonymous structs. This is ill-formed in C++.
But it relies on undefined behavior as you don't know whether to check isHeap1 or isHeap2 until you have already accessed one of their values.
If the order of the m... |
64,584,779 | 70,576,298 | Generated constructors if class has a member with same name as class | I had a class with a std::vector member that had the same name as the class and had no user-defined constructors; later I had a factory method that generated one of these objects:
#include <vector>
class data {
std::vector<int> data;
};
data create()
{
data d{};
// ...
return d;
}
When I try to build... | According to the standard class.mem#21
if class T has a user-declared constructor, every non-static data member of class T shall have a name different from T.
So your code above is valid, and the compiler must accept it. Bug reported: https://developercommunity.visualstudio.com/t/generated-constructors-if-class-has-a... |
64,584,867 | 64,585,124 | C++17 Template argument deduction failed | I wanted to simulate timer which would call a function (callback) periodically for that i wrote following snippet (naive though) wherein,
Argument deduction is failing at line Timer/<int, int, float>/.. in main function. I am compiling this code with c++17 std. How I can fix this? or those arguments necessary?
Any help... | There are 2 issues with template argument deduction here. The std::function parameter can't be deduced from the lambda argument, and deduction only works for parameter packs when they are trailing.
To fix this, you can change the order of the arguments to the constructor, like this:
Timer(std::function<void(Args...)> f... |
64,586,526 | 64,587,470 | Accelerating a nested loop in C++ | I have the following piece of C++ code. The scale of the problem is N and M. Running the code takes about two minutes on my machine. (after g++ -O3 compilation). Is there anyway to further accelerate it, on the same machine? Any kind of option, choosing a better data structure, library, GPU or parallelism, etc, is o... | On my machine which has enough memory to avoid swapping your original code took 86 seconds.
Adding reserve:
for (auto& v : res)
{
v.reserve(N);
}
made basically no difference (85 seconds but I only ran each version once).
Swapping the loop order:
for (int j = 1; j < M; j++) {
for (int i = 0... |
64,586,683 | 64,586,854 | Passing class pointer as an argument in a constructor error | my_world.hpp
Class my_world :: public I_my_world
{
public:
my_world(hello_world* dev);
virtual ~my_world() {};
virtual int trees();
private:
hello_world* const p_dev;
}
I_my_world.hpp
Class I_my_world
{
public:
virtual int trees() = 0;
protected:
virtual ~I_my_world() {};... | This code certainly looks curious
my_world::my_world(hello_world* dev) : p_dev(nullptr)
That should be
my_world::my_world(hello_world* dev) : p_dev(dev)
Because p_dev is null, you get a crash here
int my_world::trees()
{
p_dev->plant();
return 0;
}
|
64,586,972 | 64,587,064 | std::make_move_iterator vs. std::move for vector concatenation | (This is about the std::move from <algorithm>: https://en.cppreference.com/w/cpp/algorithm/move)
AFAIK, there are two common ways to move the content of one vector to the end of another.
First:
std::vector<T> dst, src;
...
dst.insert(dst.end(),
std::make_move_iterator(src.begin()),
std::make_move_... | Either should get the job done, but there is a subtle difference. When you use insert, the vector has the chance to allocate memory enough to hold all elements in one allocation. When you use back_inserter, that's the equivalent of multiple push_backs which may do multiple allocations and moves.
|
64,587,110 | 64,587,235 | clang ++ build failed, but gcc build successfully | I'm learning C + +. The following is a simple demo. I can compile successfully with gcc-10.2 on MacOS, but clang-12.0 fails
class Person{
public:
string name;
int sex;
int age;
Person(string name, int sex, int age){
this -> name = name;
this -> sex = sex;
this -> age = age;
}... | There are several errors in the source code, but I think it's better to let you discover and correct them yourself.
Back to your question, you missed a const after operator==.
bool operator==(const Person &person) const {
return xxx;
}
A better one would probably add constexpr and noexcept too (for modern c++).
con... |
64,587,119 | 64,587,271 | doing deep copy vector of pointers in copy constructor got both vector member changed? | i need deep copy in my project and for now i memcpy the srcObj into destObj then
if destObj owns pointer members, i just create all the obj and do this method recursively
here's the pseudo:
class B
{
public:
B(int id_) : id(id_) {};
int id = 0;
};
class A
{
public:
vector<B*> vecInt;
B objB = 111;
... | The memcpy() is absolutely wrong and needs to be removed. It is corrupting your A object’s data members. It may work for the objB member, but definitely not the vecInt member.
But, even with thae memcpy() removed, you would still have undefined behavior as you are trying to assign to vector elements that don’t exist ye... |
64,587,362 | 64,588,494 | Is there a good way to ensure that specific switch statement handles all enum values? | I have an enum
enum class Colors {
RED,
GREEN,
BLUE
}
and a switch statement:
switch (Colors) {
case Colors::RED:
//do something
break;
case Colors::GREEN:
//do something
break;
case Colors::BLUE:
//do something
break;
}
Is there a good way to en... | Basically configure compiler options in desired way.
The simplest choice (which will cover other common mistakes) is to use -Wall -Werror for gcc or clang and /W4 /WX for msvc (/W4 do not cover respective warning so /we4062 is needed, /WX /Wall detects to much issues from standard header files).
https://godbolt.org/z/3... |
64,587,454 | 64,682,952 | How to create instruction in function without basic block by LLVM C++ API? | I want to insert instructions into function without basic block, for example:
define void @_Z2f2v() nounwind {
%a = alloca i32, align 4
%b = alloca i32, align 4
store i32 2, i32* %a, align 4
%1 = load i32* %a, align 4
%2 = icmp sgt i32 %1, 0
ret void
}
But I read LLVM document, all C++ API I have are:
Basi... |
I want to insert instructions into function without basic block, for example:
define void @_Z2f2v() nounwind {
%a = alloca i32, align 4
%b = alloca i32, align 4
store i32 2, i32* %a, align 4
%1 = load i32* %a, align 4
%2 = icmp sgt i32 %1, 0
ret void
}
That function contains exactly one basic block, not ... |
64,588,022 | 64,588,157 | Input 300 000 sets of numbers with cin or scanf | Hi,
I am participating in programming contest. My algorithm is fine with number of sets to 5000.
Sets of values are consist of three integers.
But I enter 300 000 sets of numbers, it takes too long.
Limit of running program: 14s.
Fetching data: 576s. (Way too long)
My formatted input is:
300000
a b c
300000 - number o... | How do you know the std::cin part is the problem? Did you profile your code? If not, I suggest doing that, it's often surprising which part of the code is taking up most time. See e.g. How can I profile C++ code running on Linux?.
You're doing a lot of unnecessary work in various parts of the code. For example, your ma... |
64,589,062 | 64,600,479 | How to read mat file in C++ without help of MATLAB API | I have a mat file with nested struct. I have attached an image for a better understanding.
I try the following procedure:
1. Convert the mat file to hdf5 format. (Using any language)
2. Read the hdf5 file in C++.
But the problem is I can not able to convert the mat file to hdf5. Is there any way to convert .mat file ... | If you save your data in MATLAB using the -v7.3 flag, the MAT-file will be a HDF5 file. See the documentation:
Version 7.3 MAT-files use an HDF5 based format that requires some overhead storage to describe the contents of the file. For cell arrays, structure arrays, or other containers that can store heterogeneous dat... |
64,589,354 | 64,589,496 | Why some of the string variable not taking inputs from structure to void function? | In the below code some of the string is taking inputs but some are just skipping. I checked everything didn't discover anything. It would be ideal if you let me know where I am fouling up.I need to mention that I have a lot more work to do on this problem that's why I created functions
Expected Output
:::::::::::::::::... | cin>>stu.Phone;
Is fetching an integer from the command line so it doesn’t read the \n character at the end which getline reads immediately after.
Before getline, write fgetc(stdin) to read the newlîne.
|
64,589,456 | 64,623,933 | Unexpected behavior of fstream binary write/read, unable to read valid values from file | To write to file, I use the following function:
void writeDBToFile_BinaryMode(std::vector<structDB::citizen> dataBase,
std::string fileName) {
std::fstream fileToWriteTo;
fileToWriteTo.open(fileName, std::ios::binary | std::ios::out);
for (auto &citizen : dataBase) {
if (citizen.fullName ... | Issue solved. Final functions I used are partly based on Suthiro's code.
Here they are. Write:
void writeDBToFile_BinaryMode(std::vector < structDB::citizen > dataBase,
std::string fileName) {
std::fstream fileToWriteTo;
fileToWriteTo.open(fileName, std::ios::binary | std::ios::out);
for (auto & citizen: dat... |
64,589,490 | 64,589,666 | STL algorithms return type cast without possible data loss | I am trying to create a template function that returns the result of a STL algorithm function without any "possible data loss" warning.
template<typename T>
T sum(vector<T> A) {
return accumulate(A.begin(), A.end(), 0);
}
int main() {
vector<float> A;
sum(A);
return 0;
}
but this gives me:
Warning C... | You have a vector of float's, so desired return type of accumulate should be also float. Now it is int, because such type was deduced based on third passed parameter of accumulate - type of 0 numeric literal is int.
To solve this problem, you should pass value_type of vector as float with default initialization (to zer... |
64,589,785 | 64,590,052 | Can you help me to solve errors in this code? | I started studying C ++ recently and I'm trying to create a "calculator" with a few operations.
But I'm stuck in string 26 (cin >> choose;), which seems unresponsive. Why?
//CALCULATOR
#include <iostream>
using namespace std;
int main()
{
int start;
int choose;
int first;
int second;
int unic;
int result;
cout << "... | There are several issues in your code,
In C++ = stands for assignment to check value equivalency you have to use ==
if (choose = 1, 2, 3){
...
// this doesn't work in C/C++
// change it into
if (choose == 1 || choose == 2 || choose == 3)
When you have more than one line of code under a condi... |
64,590,141 | 64,642,838 | CMake creates huge binary when I incude a standard library | I've just created an Helloworld in C++ using Cmake.
Output binary is, as expected, 10KB.
When I add #include <string> in main without using any strings, the generated binary turn to 100KB.
When I manually compile same main.cpp file gcc main.cpp -o helloworld, the output binary has same size, with or without #include <s... | I've got the problem.
In my CMakeLists.txt file was present
add_compile_options(-Wall -Werror -std=c++17 -g)
So
-DCMAKE_BUILD_TYPE=Release
did not have any effect.
I just removed -g parameter and Debug symbols simply disappear from output binary
|
64,590,176 | 64,602,360 | Iterating over arma::mat and retrieving element locations | I'm trying to set the values of an arma::mat element-wise and the value of each element depends on the multi-index (row, column) of each element.
Is there a way to retrieve the current location of an element during iteration?
Basically, I'd like to be able to do something like in the sparse matrix iterator, where it.co... | Looking at the armadillo source code, row_col_iterator provides row and column indices of each element. This works like the sparse matrix iterator, but doesn't skip zeros. Adapting your code:
mat X(10,10,fill::randu);
mat::const_row_col_iterator it = X.begin_row_col();
mat::const_row_col_iterator it_end = X.end_ro... |
64,590,382 | 64,590,520 | find by hash value from an unordered_set which element is cumtomed type | For example I have a class like this:
struct Foo {
std::string unique_name;
unsigned id;
struct HashFunc {
size_t operator()(const Foo &foo) const {
return std::hash<std::string>()(foo.unique_name);
}
};
struct KeyEqual {
bool operator()(const Foo &lhs, const Foo &rhs) const {
return... | In order to do something like my_set.find("Bar") you need to do two things:
Your C++ compiler must support the C++20 standard and you must enable C++20 when compiling your code.
Implement your comparison and hash classes to be "transparent". This boils down to implementing overloads that hash a std::string (or a cons... |
64,590,706 | 64,590,843 | Not able to traverse linked list, can't figure out whats' wrong in my approach? | #include<iostream>
using namespace std;
struct node{
int data; // structure for each node of list
node *p;
};
class LinkedList{
node *head,*tail;
public:
LinkedList(){ //empty LinkedList used for overall stru... | Your LinkedList::addnode has following errors:
The condition in if(head=NULL){ is wrong. = is an assignment operator in C++ and it will set head to NULL and will be evaluated to false. This will have tail->p=temp; with tail = NULL and it will lead to Segmentation Fault.
temp=head; temp=tail; is also wrong. It is overw... |
64,591,264 | 64,592,484 | What is the equivalent of std::thread::join in QThread C++ | How can I wait for the finish of a QThread or What is the equivalent of std::thread::join() method in QThread
In std::thread, I can do it like the following
void foo()
{
// simulate expensive operation
std::cout << "starting first thread1...\n";
std::this_thread::sleep_for(std::chrono::seconds(1));
}
voi... | Thank you @Alex F for your suggestion.
Here is what I tried then:
#include <QApplication>
#include <QThread>
#include "mydialog.h"
#include <QDebug>
void foo()
{
// simulkate a long work
qDebug() << " Starting Qthread1 ..." ;
QThread::msleep(5000);
}
void bar()
{
qDebug() << " Starting... |
64,591,303 | 64,591,454 | Getting shared pointer from this of derived class in C++ | I want to get shared_ptr from this of derived class.
std::enable_shared_ptr_from_this inherited by base class and gets std::shared_ptr<Base>, but not std::shared<Derived>. I can use std::reinterpret_pointer_cast or std::dynamic_pointer_cast but
is so much code
is it safe when multiple inheritance used?
Or it is the on... | It's perfectly fine and safe to do it the way you're currently doing.
#include <memory>
class Base : public std::enable_shared_from_this<Base>{
public:
virtual int32_t getid() = 0;
};
class Derived : public Base{
public:
int32_t id;
Derived(int32_t id){
this->id = id;
}
~Derived(){
... |
64,591,348 | 64,593,018 | Segfault during custom collation creation sqlite using qt | I'm trying to add a custom collating function into a qt project, using sqlite.
I'm getting a segfault that i don't understand, thus can't fix.
It comes from the following code, in the sqlite3_create_collation sql function.
bool create_collate(QSqlDatabase *db)
{
QVariant v = db->driver()->handle();
if (!v.isVal... | If you have installed Qt using the online installer then it has been compiled not using the system sqlite so you have to download the sqlite amalgation (the version of sqlite depends on the version that was used to compile Qt which you can get using SELECT sqlite_version(), in Qt 5.15 you get 3.31.1 so you have to down... |
64,591,549 | 64,610,675 | Correct threshold for HoughCircles() circle detection opencv c++ | I want to detect circles in an image with opencv in c++. I have tried various thresholds for the dp, parm1, and parm2 but I could not find the correct ones.
The radius of the circles is around 40 pixels.
I have added a link to sample images. Which values do I need to use in the HoughCircles() for correct results?
Link ... | You can use following parameter values. These settings are able to detect the circles in your images.
cv::Mat img = cv::imread("75.bmp");
cv::Mat img_gray;
cv::cvtColor(img, img_gray, cv::COLOR_BGR2GRAY);
img_gray.convertTo(img_gray, CV_8UC1);
std::vector<cv::Vec3f> circles;
double minDist = 20;
double dp = 1;
double p... |
64,591,641 | 64,591,673 | Why I can't define a static field in the declaration? | So it looks like I can't do this for some reason...
class MyClass
{
static std::string name = "Whatever";
};
I don't get it, for me it would make sense to define something in the declaration, even if is static, but instead, I have to do this... ¿?¿?¿?
class MyClass
{
static std::string name;
};
std::string MyC... |
Why I can't define a static field in the declaration?
You can!
#include <string>
class MyClass
{
static inline std::string name = "Whatever";
// ^^^^^^
};
Isn't name private by default? Then why can I change its value from outside the class?
You can't!
You're defining/initialising it, not changing it... |
64,591,696 | 64,591,804 | How to create an empty std::map object? | I tried this:
std::map<int,int> m;
and it works -- m becomes an empty map. But this approach may not work if the compiler choose to not initialize m to an empty map by default. Better solution?
|
Any better solution?
Taking your question literally, no. There is no better solution.
This will create a default constructed, and therefore empty std::map<int,int>.
std::map<int,int> m;
|
64,591,747 | 64,592,043 | Is there any performance pros/cons from returning from void functions | Consider the two simple functions
void foo()
{
// do stuff
return;
}
void bar()
{
// do same stuff as foo()
}
where the only difference between them is foo() contains a return statement and bar() will return after "dropping" out of the function (for a lack of better terms). I assume that the return statement... | The compiler will always insert a RET instruction at the end of a void function (assuming it does not end by throwing an exception). An explicit return; statement here is not needed, and will have no effect.
The generated assembly in your example is identical:
foo():
ret
bar():
ret
(link to godbolt)
Th... |
64,592,066 | 64,592,376 | Identifier not found for function defined in a .h file | I keep getting the "Identifier not found"-error, when I try to run my program...
I've declared the function in a .h file, implemented it in a .cpp file and I try to use it in my main file.
Can you help?
//main.cpp
#include <iostream> // using IO functions
#include<fstream>
#include "SokobanSolver.h"
using namespace... | As has been pointed out in the comments, you need a SokobanSolver object to call the member function loadFile:
int main() {
SokobanSolver solver;
solver.loadFile();
system("pause");
}
|
64,592,095 | 64,600,661 | CMake + ccache: RULE_LAUNCH_COMPILE or CMAKE_<LANG>_COMPILER_LAUNCHER | When using ccache with CMake, there seems to be two ways to setup the project.
The first one is with RULE_LAUNCH_COMPILE
find_program(CCACHE "ccache")
if(CCACHE)
set_property(GLOBAL PROPERTY RULE_LAUNCH_COMPILE "${CCACHE}")
endif()
The second one is with CMAKE_<LANG>_COMPILER_LAUNCHER:
find_program(CCACHE "ccache"... | The first one will use the launcher for all languages in the build. The second one will use the same launcher for C and CXX but not for other languages. The two methods are slightly different as the second one would allow for a different launcher for different languages. The second method allows for finer control an... |
64,592,353 | 64,593,757 | Replacing global operator new / delete and allocating memory within these, leading to heap corruption | #include <cstdlib>
#include <memory>
#include <unordered_map>
template <class T>
struct allocator {
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef T value_type;
allocator()... | From std::allocator::allocate allocator allocates n "things" not n bytes. You should change:
T* allocate(std::size_t n) const { return (T*)malloc(n); }
to:
T* allocate(std::size_t n) const { return (T*)malloc(sizeof(T) * n); }
Why do i corrupt the heap in the constructor of allocations_map?
Because the constructor ... |
64,592,944 | 64,593,380 | Integrating GTest with existing CMake Project: share the same target_sources | I have a large C++ library, and want to do some testing with GTest.
At the moment, the build is handled with CMake, in particular there is one CMakeLists.txt file in the root directory like the following
make_minimum_required(VERSION 3.13.0)
project(mylib)
find_package(PkgConfig REQUIRED)
set(CMAKE_BUILD_WITH_INSTALL... | You can split the current mylib executable target into two targets
mylib, a library target that is very much like the current mylib target, but without the run.cpp file
mylib_exe an executable target that compiles run.cpp and links to mylib
Now your test files can link to mylib.
|
64,593,165 | 64,593,579 | What would be the proper implementation of a concept describing a raw pointer (to objects)? | This might be of academic interest only.
Because I noticed that my practical example might not be the suitable one to raise that question.
Originally I had written something like
auto bak_ptr{ptr}; // think of an `int* ptr`
to make a backup of an address.
Now I wondered if I could do better by replacing that dumb auto... | Just building up upon std::is_pointer there should be nothing wrong with
template <class T>
concept pointer =
std::is_pointer_v<T>;
Thanks to @cigien for that idea.
And I would say that in the simple backup example the choice of std::copyable instead is exactly right. As that's what you want to do with the backup, r... |
64,593,697 | 64,594,983 | Reducing cyclomatic complexity in c++ | I want to ask that for a simple if else statement with multiple conditions how
can the cyclomatic complexity be reduced ?
For istance:
std::string x;
if(cond)
x = "Value1";
else if(cond2)
{
if(cond3)
x = "Value2";
else if(cond4)
x = "Value3";
else
x = "Value4";
}
... | You can use the bits in an unsigned int to declare properties, and combine those properties to define masks. A dispatch function uses the x value and a flag value to test the bits and respond accordingly.
#include <cstdint>
#include <iostream>
// Properties
static constexpr const auto C1 = 1u << 0;
static constexpr co... |
64,593,698 | 64,652,508 | Why does jemalloc memory profile evaluated by jeprof seem to show all memory allocations? | We are trying to track down a memory leak in proxysql (2.0.14) which uses jemalloc (5.2.0). We compiled proxysql with debug symbols enabled. The jemalloc configuration that is baked into proxysql is the following:
xmalloc:true,lg_tcache_max:16,prof:true,prof_leak:true,lg_prof_sample:20,lg_prof_interval:30,prof_active:f... | I think this may reflect some of the ambiguity in what "leak" means. Tools like Valgrind will traverse the pointer graph of the program at shutdown, and treat things as leaks if that traversal does not find some live allocation.
Other tools treat "leaks" as simply anything allocated but not freed. The profiling mode in... |
64,593,829 | 64,594,223 | std::function from "new" and type | Let's assume I have the class Class.
Now I'd like to create a std::function<Class*()> object which creates a new object of type Class, uses the default constructor and returns it.
Is there some extremely simple way to bind new with a type and be done with it?
Or do I have to make a function/lambda that does it and bind... | std::bind takes a callable entity as the argument.
new Class() is an expression. An expression can't be "called". To make an expression "callable", it can be wrapped in a lambda. But then you don't need std::bind anymore.
|
64,594,113 | 64,594,309 | Cannot Implement Searching By Name | So I have created a program to store the info of students in a file and the program creates the file and stores the info but does not search upon selecting the option and says the name not found. I have tried to implement a search by name here. I am a beginner so any help would be appreciated, Thanks!
#include<iostream... | You have a simple mistake in the for loop. You are breaking from loop if not found in the first iteration. If not found you have to loop until last element of the array.
int Students::search(){
string n;
cout<<"Enter the name you want to search: "<<endl;
cin>>n;
for(int i=0; i<5; i=i+1)
{
if... |
64,594,137 | 64,618,254 | WidgetSeekProgress not showing the media elapsed and full time of Video Vlc-qt Qt | I am developing a media player in Qt using vlc-qt module as my base. So I am able to load the video in the VlcWidgetVideo and using the WidgetSeekProgress to show the elapsed time and full time of the video.
The problem is that after creating and loading the video into the widget, when I create the object of the Widget... | I just need to add the player into the WidgetSeekProgress object After the media player instantiation.
m_instance = new VlcInstance(VlcCommon::args(), this);
m_player = new VlcMediaPlayer(m_instance);
ui->m_seek->setMediaPlayer(m_player);
|
64,594,254 | 64,594,546 | Why do the two functions give different results? | I defined two functions using RcppArmadillo package and save them into the file cxxFuns.cpp. The only difference between f01 and f02 is the positions of V(0, 0):
#include <RcppArmadillo.h>
using namespace Rcpp;
// [[Rcpp::export]]
arma::mat f01 (arma::mat x) {
unsigned int p0 = x.n_cols ;
unsigned int iR = 0, ... | The last execution in the first block is when iR = p0-1.
The last execution in the second block is when iC=p0-1.
Since iC starts as iR+1, your last execution is for iR=p0-2.
Printing the value of iR before computing V(0,0) or running under a debugger should have immediately made this clear.
|
64,594,330 | 64,594,578 | C++20 default equality / inequality | C++20 gives us the spaceship operator and even allows us to default it, generating all comparisons with default semantics, which will remove a lot of boilerplate from our code bases, great!
But how about equality and inequality? Does C++20 also give us a way to default equality and inequality? According to cppreference... |
Does C++20 also give us a way to default equality and inequality?
Yes (but see the last paragraph). The syntax is same:
friend bool operator==(const T&, const T&) = default;
friend bool operator!=(const T&, const T&) = default; // not needed if == exists
The ordered inequality can be defaulted also:
friend bool oper... |
64,594,355 | 64,683,971 | Q: DX12 Error in creation of graphics pipeline state | By following the Microsoft documentation and creating the PSO, I receive the following D3D12 errors.
Error code
Considering the first error states that the encoded signature size doesn't match the specified size.
I compared the shader and the signature.
D3D12_INPUT_ELEMENT_DESC inputElementDesc[] =
{{
"PO... | Chuck Walbourn Helped me find the solution.
The blob did not get the results from compiling similar to D3DCompileFromFile().
By utilizing the IDxcOperationResult in the last parameter of the compiler.
You are fetching the results from the compiler like this:
ComPtr<IDxcOperationResult> result = nullptr;
....
... |
64,594,703 | 64,595,185 | Cannot dereference double pointer, " no match for operator* " | I'm trying to search through an array of pointers to objects of class Shape. I have written the following code. However, I'm getting this error: "no match for operator*", and I don't know where to go from here. Any help is appreciated.
Shape** shapesArray;
bool doesNameExist(string name) {
for (int i = 0; i < shap... |
shapesArray is a Shape**
shapesArray[i] is Shape*
(shapesArray[i])->getName() is dereferencing shapesArray[i] and calls its
member getName
So far nothing wrong. I guess this is what you actually want to get, but you add another *:
*(shapesArray[i])->getName() tries to dereference what was returned from getName (a... |
64,594,709 | 64,598,423 | Using sigc::mem_fun by accesing parent of container | I'm trying to make a simple software with Gtkmm3.
I want to have a window with a grid inside. At a click on a button inside that grid, a method of the window should be triggered to delete the current grid and replace it with another one.
I'm able to use a method of the grid like this :
button.signal_clicked().connect(s... | Without any code, it is hard to know what exactly you are looking for. Here is how I would do it: I would keep a reference to the parent Window inside the grid. For example:
#include <iostream>
#include <memory>
#include <sstream>
#include <gtkmm.h>
class MyWindow : public Gtk::Window
{
public:
MyWindow()
:... |
64,594,738 | 64,614,424 | The application crashes and runs at the same time | I draw the application menu, having previously written the menu class and the function of this class.
When I launch the application, the menu works for 5-7 seconds, but in Windows the cursor are spinning in the form of a blue circle, which does not bode well. If these 5-7 seconds are idle, the whole screen
turns white,... | I SOLVED MY PROBLEM!
If you have same problem, just write in "while" loop checking of closing window:
while(isMenu)
{
Event event;
while (app.pollEvent(event))
{
if (event.type == Event::Closed)
app.close();
}
//some code
}
|
64,595,758 | 64,596,028 | How to define common interface in C++ | I have following abstract class in C++
class Converter
{
public:
virtual void enable(void) = 0;
virtual void setReferenceValue(double) = 0;
virtual void registerAlarmListener(AlarmListener*) = 0;
virtual void confirmAlarm() ... | You can do that with polymorphism: define BaseParam and BaseAlarm classes and use vectors of pointers to them as an argument to your functions.
Alternatively, you can use vector of std::variant
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.