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 |
|---|---|---|---|---|
63,440,181 | 63,440,216 | How to store arguments list to vector? | How can I store variadic constructor arguments to vector?
Example with my failed tries:
class Combo
{
public:
template <class... Args>
Combo(Args... args)
{
// this->keys_.push_back(args...);
// this->keys_.push_back(args)...;
// this->keys_.push_back(std::forward<Args>(args...));
... |
C++11
for(auto &&i: {args...}) keys.push_back(std::move(i));
C++17
(keys.push_back(args), ...);
Oh, sorry, I've missed the obvious:
template<class... Args> Combo(Args... args): keys_{uint8_t(args)...} {}
|
63,440,222 | 63,442,801 | How to download and compile external library only once with CMake? | I am using the Unity testing library in my project. Ideally, I would like to automatically download the source code from GitHub and put it in the external/ directory, build the library once, regardless of how many different CMake configurations I have (one Debug and one Release CMake configuration), and link the librar... | I was able to make it work using ExternalProject. This is what my CMakeLists.txt looks like now:
include(ExternalProject)
set(UNITY unity_project)
ExternalProject_Add(
unity_project
GIT_REPOSITORY https://github.com/ThrowTheSwitch/Unity.git
GIT_TAG cf949f45ca6d172a177b00da21310607b97bc7a7
PREFIX ${PROJE... |
63,440,542 | 65,011,811 | UE4 Creating a UStaticMesh from an external .FBX file returns NULL | I'm trying to load an .fbx file from an external file to my game during gameplay.
I have created a function to load a mesh from path, however the function ''LoadMeshFromFile'' returns NULL, I tried to change the path to the path of an existing .uasset and it works fine, however my goal is to import an .fbx file to the ... | You can't load an fbx file directly at runtime in ue4.
You need to use some external plugin to do that
|
63,440,600 | 63,446,888 | store and access data in library dll | I have a dll and associated lib file which contains a number of std::vector instances e.g.
In data.h I have:
namespace xyz{
extern DllExport std::vector<double> delays;
...
And in data.cpp I have:
namespace xyz{
std::vector<double> delays{0, 1, 4, 24, 52, 104};
...
data.cpp is compiled and linked into mydata.lib,myda... | The answer and links provided by dxiv helped me to fix things. In my file data.h I now have
#ifdef EXPORTING
#define DllExport __declspec(dllexport)
#else
#define DllExport __declspec(dllimport)
#endif
and I compile mydata.lib, dll with -DEXPORTING
|
63,440,670 | 63,440,743 | Uses for cpp struct variables passed in templates | I just want to ask if there are any uses for passing variables in cpp as template arguments
template<int a> struct foo {
int x = a;
};
int main() {
foo<2> bar;
std::cout << bar.x;
}
Something like this compiles, works and cout's 2 but the same thing can be done by doing
struct foo {
int x;
foo(int... | When you pass a variable through a template argument, it can be used in compile time.
For example, if you need to create a statically sized array in your class, you could use the template argument to pass the size of your array:
template <int TSize>
class Foo {
[...] // Do whatever you need to do with mData.
privat... |
63,440,753 | 63,440,985 | Idiom for a C++11 enum with methods and static instances? | I'd like to do the following (which won't compile):
class Foo {
int value;
Foo(const int arg)
: value{arg}
{}
public:
static const Foo a{0};
static const Foo b{1};
static const Foo c{2};
Foo func(const Foo& foo) {...}
};
so that the the instances of Foo are strongly controlle... | You can do it quite easily but you need to put the definitions of your constants outside the class:
class Foo {
int value;
// In C++17, you could make this constexpr.
Foo(const int arg)
: value{arg}
{}
public:
// in C++20, you could make these constinit.
static const Foo a;
static ... |
63,441,230 | 63,442,518 | C++ initialize differently in container vs as local variable | This question came up while I was trying to write an RAII wrapper class for an OpenGL buffer object. The way that OpenGL creates buffer objects is by a call to void glGenBuffers(GLsizei n, GLuint* buffers) which "returns n buffer object names in buffers." Also, note that the object name 0 is special to OpenGL, being... | C++ object initialization is not, and cannot be, predicated on where that object is created (with the exception of default-initializing objects of trivial types, which zero-initialize when used for global variables, but not for automatics).
If you give a type a non-trivial default constructor, you are making a strong s... |
63,441,307 | 63,441,426 | multiply two negative numbers in c++ | when I tried to multiple two negative numbers the value it is zero in c++,
for example -5 * -3
the result is zero,
why?
this is my code
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
void Multiply(const int v_arr[], const int m_arr[][3], int signed
o_arr[], int size)
{
for (int i... | Your issue is here:
for (int k = 0; k < 3; k++)
o_arr[i] += v_arr[k] * m_arr[k][i];
}
You access elements at indices 0, 1 and 2 in v_arr, but it only has 2 elements. That's Undefined Behaviour.
Assuming this is matrix*vector multiplication code, it should look like this (untested):
for (int k = 0; k < 3; k++)
... |
63,441,622 | 63,442,243 | Is it possible to forward function calls with matching template type for a std::any-like container? | I haven't found a way to achieve what I want but I'm not knowledgeable enough to know if its impossible. Help would be appreciated.
The main data data container in our software behaves a bit like a std::variant or std::any: It has a base class BaseContainer that provides a type enum. The derived instance DataContainer ... | You cannot pass overloads by name, but you can pass functor with overloaded operator() as generic lambda have.
So
template <typename F>
auto dispatch(BaseContainer& vContainer, F f) {
switch (vContainer.getType()) {
case DataTypes::INT8:
return f(dynamic_cast<DataContainer<int8_t>&>(vContainer).... |
63,442,018 | 63,442,054 | Is a potentially-throwing function signal-safe? | According to support.signal,
An evaluation is signal-safe unless it includes one of the following:
...
throwing of an exception;
control entering a try-block or function-try-block;
...
A signal handler invocation has undefined behavior if it includes an evaluation that is not signal-safe.
Does it mean calling a pot... | "throwing of an exception" should be taken literally, and precisely: an exception gets thrown. Nothing more, nothing less.
Entering a scope that potentially throws an exception is not the same thing. As long as the code does not actually throw an exception, signal safety is not violated.
g() does not end up throwing an... |
63,442,264 | 63,442,374 | How can I define "recursive" function type in C++? | I have tasks, the task does something and returns True if it has to be called again.
function<bool()> currentAction;
I originally was going to go with something like this to manage my current task.
if (!currentAction())
currentAction = []() { return false; };
Then I changed my mind and wanted something like this
... | You can create class:
struct Action
{
Action operator() { return next(); }
std::function<Action()> next;
};
Demo
|
63,442,463 | 63,442,535 | Can't bind signal to slot in my Qt application | I'm new to Qt and I have a very simple demo app. It just include a QLineEdit widget and I want to invoke a function test() when I press ctrl+p in the QLineEdit.
Below are the related files.
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QShortcut>
MainWindow::MainWindow(... | You have 2 misconceptions:
The connection indicates the link between the object that emits the signal, the signal, the object to which the slot belongs and the slot. In your case it is obvious that the object to which the slot "slot" belongs is this.
If the old syntax (SIGNAL & SLOT) is to be used then "test" must be... |
63,442,780 | 63,443,267 | passing parameters to the concatenate function | i'm confused with *this = *this +rhs; , should i use this = this +rhs; instead or it will be wrong because the Mystring Mystring::operator+(Mystring &rhs) const expect object not reference of object???
i'm using the concatenate function to do the assign and concatenate.
////concatenate
Mystring Mystring::operator+(Myst... | Look at it like this:
this = this + rhs;
// is the same as:
pointer_to_MyString = pointer_to_MyString + MyString;
That doesn't make any sense!
You need to deference them first. Or in other words, remove the "pointer"
*this = *this + rhs;
// is the same as:
MyString = MyString + MyString;
|
63,442,909 | 63,443,075 | Why does * need to be put before (&a) to subtract a (a is an array)? | I was learning how to find the length of an array and I'm baffled by this solution. I tried to find an explanation online but there seems to be none.
int arr[5] = {5, 8, 1, 3, 6};
int len = *(&arr + 1) - arr;
cout << "The length of the array is: " << len;
| The memory address of the array is the same as the memory address of the first element, and when you add to or subtract from a pointer, it is done by the size of the type it points to, so:
arr refers to int, and &arr refers to int[5].
&arr+1 increments the memory address in the size of five integers.
If you do (&arr+1... |
63,443,210 | 63,443,490 | What is the default encoding that used with string variables without using the Unicode symbol? | When creating a string variable (char*) without using any symbol of Unicode u8 etc, for example:
const char *str = "Hello 日本語 سلام Ä भारतीय ไทย";
How to specify the default encoding to read that variable in popular platforms or depend on what?
|
What is the default encoding that used with string variables without using the Unicode symbol?
There are two encodings to consider here. One is the encoding of the source file. This is the encoding which you have used to write the file. The compiler has to interpret the source using the same encoding that you used to... |
63,443,329 | 63,443,390 | restrict permissions on a java, c++, python program | Suppose I have to run a java, c++, or python3.8 program on my machine, but I don't want these programs to access my system information, run os commands, or perform any malicious activity. Is there a way to do this for each of the aforementioned languages?
| Java theoretically has a solution for this: The 'SecurityManager'. You can set one up within your java code (you can tell the system: Here is some code; load it as the manager please).
A securitymanager gets called before certain things happen and can deny the operation. It's mostly anything that feels security sensiti... |
63,443,614 | 63,454,786 | Am I paranoid while using boost:asio? | I am write an app using boost:asio.
I have a single io_serice::run() thread, and many worker threads. All the worker threads may send msg at any time.
Here is how I implement the send_msg().
// Note: send_msg() could be called from any thread.
// 'msg' must be 'malloc'ed, and its owner ship will be transfered to '_sen... | Yes, indeed. The documentation details this here:
Threads And Boost Asio
By only calling io_service::run() from a single thread, the user's code can avoid the development complexity associated with synchronisation. For example, a library user can implement scalable servers that are single-threaded (from the user's poi... |
63,443,681 | 63,443,879 | Creating a shortcut .lnk using Windows API | I'm having a problem with creating a shortcut using C++.
The .lnk file is created, but the target has a nonsense path.
Can you explain why this code is not creating a correct shortcut? Can someone could help me fix my code?
Here is the code
// RepChrome.cpp : Defines the entry point for the console application.
//
#in... | When calling sprintf_s(), %s expects a char* string, but you are giving it a wchar* string instead. Also, you are passing in the wrong value for the second parameter of sprintf_s() and swprintf_s().
You really should not be using any char data in this code at all, especially since you are just converting it to wchar a... |
63,443,702 | 63,454,953 | How can unspecified types be used in C++20 'requires' expressions? | I'm trying to write a C++20 concept to express the requirement that a type have a certain method, which takes an argument, but for the purposes of this concept I don't care what the argument type is.
I've tried to write something like:
template <typename T>
concept HasFooMethod = requires(T t, auto x)
{
{ t.Foo(x) ... | Something close to this can be accomplished by defining an adapter type that can implicitly convert to (almost) anything:
struct anything
{
// having both these conversions allows Foo's argument to be either
// a value, an lvalue reference, or an rvalue reference
template <typename T>
operator T&();
... |
63,443,997 | 63,451,185 | Fancy hack to get reflection breaking locally but not in online compiler | Some smart guy:
get the number of fields in a class
https://www.youtube.com/watch?v=abdeAew3gmQ
Figured how to use template meta programming to get some basic reflection going.
Well, I am trying to integrate that with my code and it's causing issues.
In an online compiler this works:
#include <iostream>
#include <tuple... | The problem is that the original code must (for reasons that escape me) return a value according to its signature, but it never does.
The solution is to make it actually return something to prevent segfaults:
template <class T, std::size_t I0, std::size_t... I>
constexpr auto detect_fields_count(std::size_t& out, std::... |
63,444,018 | 63,481,552 | Press enter to export Keyboard Hook message | I've written a program to get keyboard hook. What I want is, when a user presses Enter, the typed text, for example: "hello world", which I stored in exportMsg, should be returned from the function.
I want to make a dll and export exportMsg.
Here is my code. Thanks in advance.
#include <Windows.h>
#include <stdio.h>
#i... | As std::cin doesn't work in Unity, I needed to use Keyboard Hook to scan qrCode through a QR Code Scanner Machine and send the scanned string to the Unity.
This algorithm capture the key strokes and returns the string when Enter is pressed.
My DLL code looks like this:
Header file:
LRESULT CALLBACK KeyboardProc(int nCo... |
63,444,277 | 63,444,344 | LD_LIBRARY_PATH vs build time argument | I am building an application using OpenGL. I have multiple OpenGL installed on a server.
I noticed that even after specifying link path for OpenGL libraries at runtime in Makefile, when running the application it still looks for library in different places, resulting error.
The correct openGL path is /usr/lib/nvidia-41... | You need to understand what is rpath, what is library search path and the rules for searching libraries.
For rpath and library search path, please check this one:
What's the difference between -rpath and -L?
For the rules for searching libraries, please check this one:
https://unix.stackexchange.com/questions/22926/whe... |
63,444,429 | 63,444,554 | Outputs get changed after removing one printing statement | #include <iostream>
//Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
ListNode* addTwoNumber... | Your code has undefined behavior.
In addTwoNumbers(), the final_ll and carry variables are both uninitialized, and both are being used before they have been assigned valid values.
carry holds a random value when declared, throwing off your while loop if that value is not 0.
If l1 and l2 were nullptr, and carry happened... |
63,444,531 | 63,444,583 | Member of nested class isn't being initialized by the constructor | I have two classes, Outer and Inner. Outer contains no data members. Inner contains one data member, inner1_. When I call the constructor for outer, I create an instance of the class Inner, inner1. When the constructor for inner1 is called, its data member, inner1_, should be a vector of length n. However, after inner1... | You have redeclared inner1_ in the ctor which is overshadowing the class variable. You probably want to resize the vector. This is how one resizes the vector:
inner1_.resize(n);
|
63,444,688 | 63,444,788 | How to calculate a hash of const char* with given size and content examination by using standard tools | I have a sub_string struct and I would like to use standard tools to calculate a hash of it:
struct sub_string
{
const char* ptr;
size_t size;
};
Here are some restrictions:
It has to be done by standard tools provided by c++11.
const char* doesn't have to be NUL-terminated.
I don't want to use std::hash<cons... | You can't do what you want without relaxing one of your restrictions.
std::string's precise hashing algorithm is implementation defined. So the only way to mimic it would be to rely on std::string's hashing algorithm either by making a std::string or borrowing the implementation manually for your own type. Since you wo... |
63,444,812 | 63,473,418 | "A matching symbol file was not found in this folder " . Getting this error when i try to debug using dump file | We are having some issue in customer site. So we generated the dump in their site.
Now to find out the issue we are loading the dump file from visual studio.
I had given the correct symbol path also.
Error which i am getting
A matching symbol file was not found in this folder
Error msg (Eventhough pdb is present is sam... | Thank you.
There was a signature mismatch b/w my dll and pdb .I used Chkmatch tool to check , and i corrected the pdb using the same tool .And it worked .
Link for the tool http://www.debuginfo.com/tools/chkmatch.html
Commands :
chkmatch -c ExeFile/dll DebugInfoFile(pdb)
--> This command will tell whether your pdb and ... |
63,445,042 | 63,445,118 | What is the difference between the two codes | I have been doing a question recently and I used a similar approach to the editorial. Link to the question is below : https://www.spoj.com/problems/STPAR/
Editorial Code (Though it is from a third party site, I have tested it and it gives AC)-
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <stack>... | You haven't initialized the t value. And also you're not decreasing it.
As per question there is no input of no of test cases. So remove variable t and while loop as well(i mean remove while loop not the code inside it). Run it again.
|
63,445,048 | 63,445,261 | Why does the vector returned by my C++ function contain garbage values in the caller? | I've created a simple C++ program to read and tokenize input from cin. However, while the tokens in my helper function are correct, the tokens in the caller function (main) are garbage values.
As an example, if I enter "a b c" as the input, the vector of tokens in my helper function (get_input_tokens) contains "a", "b"... | It's because a StringPiece holds pointers into the string it is a piece of.
In your case, that's input, which is destroyed when the function returns and makes all the StringPieces invalid.
You need a different type for the tokens.
I'm not familiar with folly, but if the creators haven't lost the plot completely, std::s... |
63,445,072 | 63,445,405 | Efficient way to enumerate unique undirected paths | Given a subset of nodes {1,2,...,N} is there any STL or boost function that returns unique undirected tours over all of them?
std::next_permutation() gives all N! directed tours, where 1-2-...-N is different from N-N-1-...-2-1.
However, in this case, I don't want both of them, but only one of them. Essentially, I would... | If you want to stay with next_permutation rather than make own generator routine, the simplest way is filter out a half of permutation with some condition.
Very simple one: the last element should be larger than the first one.
#include <vector>
#include <algorithm>
#include "stdio.h"
int main() {
std::vector<int> ... |
63,445,225 | 63,445,921 | Disambiguation rule concerning member and free operators | I have a program that looks like this:
class B {};
class A
{
template<typename T> int operator+(const T&) const { return 1; } // Function 1
};
template<typename T, typename P> int operator+(const T&, const P&) { return 2; } // Function 2
int main()
{
A a;
B b;
std::cout<<(a + b);
return 0;... |
Now Function 1 will be called, even though in both cases Function 1 is basically identical. What's the reasoning behind this?
Partial ordering of overloaded function templates is performed to select the best match here.
Informally "A is more specialized than B" means "A accepts fewer types than B".
Function 1 is mo... |
63,445,236 | 63,447,671 | i have data in json format and want to convert it to csv | #include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
ofstream myfile;
myfile.open("newtest.csv");
mongocxx::instance instance{};
... | Here's one way to do it. There are a few more bsoncxx::types than I've cared to decode in this example. If you need them, you'll have to add them. This should be enough output your bson data as csv though.
I've put the support functions in a class to support streaming to any std::ostream.
bson_csv_adapter.hpp
#ifndef B... |
63,445,675 | 63,445,882 | Why does the initialization of an std::initializer_list seem to fail in VS2019 | The following piece of code fails on Visual Studio 2019 compiled in Release mode.
#include <iostream>
#include <iterator>
#include <initializer_list>
int main( int, char** )
{
std::initializer_list<int> v = {};
std::initializer_list<int> i = { 1, 2, 3 };
v = i;
std::copy( v.begin(), v.end(), std::ostr... | Just to be clear, the only initialisation of v takes place in the line:
std::initializer_list<int> v = {};
The other two are assignments rather than initialisation:
v = i;
v = { 1, 2, 3 };
And it's the difference between those two assignments that provides the solution.
Copying an initialiser list does not necessaril... |
63,446,008 | 63,446,109 | Is a function pointer really a pointer? Or it's an object? | I have this doubt because at first I think a function pointer is just plain pointer as it literally reads. But then I found some clues that indicates it doesn't look like a plain pointer but it's more likey to be an object.
From C++ Primer 5th (emphasis mine):
When we define a lambda, the compiler generates a new (unn... | As mentioned in the text you quoted, a lambda is equivalent to a struct with operator() defined. Your second program is very similar to:
int the_function(int i) { return i + 3; }
struct foo
{
int operator()(int i) { return the_function(i); }
using Ftype = int(int);
operator Ftype *() { return the_function... |
63,446,022 | 63,446,104 | C++ - Extract template parameter from derived class | Can I extract the type parameter from the derived class? Something like this:
template<typename T>
class A {
...
};
struct TheType {};
class B : public A<TheType> {
...
};
template<typename DerivedClass>
class C {
// If DerivedClass is B
// Can I extract the type parameter T of B:A<T> inside of C?
DerivedClass... | You can add a type in A:
template<typename T>
class A {
protected:
using type = T;
...
};
Then you can use typename DerivedClass::type in C.
|
63,446,295 | 63,447,292 | Parse comma-separated ints/int-ranges in C++ | Given a string in C++ containing ranges and single numbers of the kind:
"2,3,4,7-9"
I want to parse it into a vector of the form:
2,3,4,7,8,9
If the numbers are separated by a - then I want to push all of the numbers in the range. Otherwise I want to push a single number.
I tried using this piece of code:
const char ... | Apart from @J. Schultke's excellent example, I suggest the use of regexes in the following way:
#include <algorithm>
#include <iostream>
#include <regex>
#include <string>
#include <vector>
void process(std::string str, std::vector<int>& num_vec) {
str.erase(--str.end());
for (int i = str.front() - '0'; i <= s... |
63,446,429 | 63,446,606 | How to convert LPCTSTR to std::string in C++ | I am having a function which takes arguments as LPCTSTR
I want to concatenate that argument in that function with a std::string
As per one of the suggestions I used following conversion:
std::string PlaybackStart(LPCTSTR i_bstrCameraName)
{
wstring cid = (WCHAR*)i_bstrCameraName;
string fcid;
for (char x : ... | LPCTSTR is an alias for const TCHAR*, where TCHAR is either char or wchar_t, depending on project configuration.
The cast of i_bstrCameraName to WCHAR* is wrong if your project is configured to map TCHAR to char. Just use the char data as-is instead.
And the conversion of wchar_t characters to char in the for loop is w... |
63,446,930 | 63,446,997 | How can I work with vectors if I don't initialize it first? | I am working with <algorithm> library in C++.
I have an exercise with std::vector.
How can I use vector if I don't initialize it first like this std::vector<int> v(10,0); ?
std::vector<int> vec;
int i = 0;
std::generate_n(vec, 10, [int& i](){i += 10; return i});
I want it to be vec={10,20,30,40,50,60,70,80,90,100}
| You can use std::back_inserter (and std::back_insert_iterator), which performs push_back on the container to insert elements. E.g.
std::vector<int> vec;
vec.reserve(10); // if the size could be determined in advance
int i=0;
std::generate_n(std::back_inserter(vec), 10, [&i](){i+=10; return i;} );
|
63,447,619 | 63,447,946 | Preserve list of lists in C++ | I'm trying to fetch some data from a large string. I want to split a string to smaller strings and save it to a list. After that I want to loop every string in that list and split it again on smaller list of strings and after that append that list to one big list of lists. When I'm trying to insert small list to big l... | insert inserts each item of the iterated object (servers) in the target list. Each item is a std::string. Also you are inserting the items into a std::list<std::string>, which does not allow sublist items (since items must be strings). If you want a list of lists, you need to create one, e.g.
std::list<std::list<std::s... |
63,447,643 | 63,451,684 | Why does my PZEM-004T module not measure? | I have a task at work to measure power consumption of devices with Arduino and a PZEM-004T module. I connected the Arduino Mega R3 2560 to the PZEM (PINs 18 and 19 for TX and RX). The Arduino Mega is connected to a computer through USB (A to B). This is the code:
#include <PZEM004Tv30.h>
PZEM004Tv30 pzem(18, 19); // S... | Solved the problem. Pins 10 and 11 support SoftwareSerial on Arduino Mega R3 2560 so I had to move them from pins 18TX and 19RX.
|
63,447,892 | 63,448,880 | Can I hold a shared_ptr without knowing the type parameter? | I would like to hold a shared_ptr of a template class. However, I don't want to make the class B as a template class too. In my understanding, shared_ptr with any type will have the same memory layout. So I am wondering any workaround in this scenario?
template<T>
class A {
...
};
class B {
...
std::shared_ptr<A<T>>... | When the type doesn't matter at all, void can be used.
template <typename>
class C {};
std::shared_ptr<void> p = std::make_shared<C<int>>();
Adding a monomorphic base class allows restricting the type that can be stored.
class AnyC {};
template <typename>
class C : public AnyC {};
std::shared_ptr<AnyC> p = std::mak... |
63,448,294 | 63,448,329 | how can i write this code so that it will accept "space" as a part of address? | here i wrote a code for taking address as input from user, but when user enters "space" between address, compiler takes the next word as next input .how can i write it so that it will take "space" as a part of address.
note:i have to do this using constructor and copy constructor only
#include<iostream>
#include<string... | You should use std::getline instead.
i.e. replace
address() {
cout << "Enter your current address"<<endl;
cin >> add;
}
with
address() {
cout << "Enter your current address" << endl;
getline(cin, add);
}
and then do the same for when you want to get the new address if needed.
|
63,448,453 | 63,449,376 | Using E notation in wxSpinCtrlDouble | In a C++ wxWidgets GUI, I am trying to implement a way for the user to change the value of an optimization problem parameter. The value has only meaningful impact on the problem if it changes by an order of magnitude. So the most convenient way to do it would be to display the current value in E notation (e.g., 1e-3) i... | There is no built-in way to do it, other than the obvious one: use wxSpinCtrl for just the exponent and a separate control (or maybe even a static 1) for the mantissa.
|
63,448,672 | 63,510,006 | QThread: slot quit() is never invoked and hence the thread wait() is forever | I have the exact same problem as described QThread won't stop / does not process a signal but with a twist. I cannot get it to work even with QCoreApplication::processEvents() to my while loop. I followed this blog post and ended up like as follows:
MediaController.cpp
void MediaController::buttonPlayClicked(bool check... | After trying out a lot of suggestions i still couldn't figure out why emit finished() doesn't quit the thread. So, as a last resort, i used this->thread->quit() to achieve the same.
But thanks to all the commenters here, i narrowed down on laggy/choppy gui issue.
My emit data(std::tuple<QImage, QImage, QImage>>) was se... |
63,448,728 | 63,448,768 | Load text from a file in a QRC file in QML | I’m trying to load some text to TextArea from a file in QRC. But I don't know how to do that. QML file QRC file
I tried to do that in C++, too. Code:
QFile file(":/assets/CREDIT.md");
But I just get an error: QIODevice::read (QFile, ":\assets\CREDIT.md"): device not open Cpp file
| The error is clear, you have to open the file:
QFile file(":/assets/CREDIT.md");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
|
63,448,863 | 63,451,898 | "Procedural" playground generation in c++ console application | Adventure for learning basics and more in c++ (Total noob). Now i made a Playground Array for all the fields to visit, but when it comes to the rand() function in a for loop it repeats the Nummber so it's not random generated. Some ideads to fix this issue? Note that iam not very into the rand func.
Thanks in advance!
... | time requests the current time in seconds as an integer. if your program takes less than a second to execute, then you will "seed" the random number generator with the same value every time. pseudo random number generators (i.e. your rand() call) return a deterministic series of values based on this state you seeded.... |
63,449,420 | 63,449,515 | No warning from CMake when not including sources with `target_sources` | I have a project which depends on foo.cpp
add_library(App SHARED app.cpp)
target_link_libraries(App Module)
target_sources(App PRIVATE foo.cpp)
add_executable(app main.cpp)
target_link_libraries(app App)
which works perfectly. However if I remove line 3 to have
add_library(App SHARED app.cpp)
target_link_libraries(App... |
Can I avoid this to get warnings/errors more up-front?
Do you mean you want to get those errors during the build stage? You can't. That is a loader error, which basically means that it was unable to find the referenced symbol because the library was not found or something. And no there is no way to avoid it.
Suppose ... |
63,449,470 | 63,449,985 | Is it necessary to null your pointers after deleting multidimensional dynamic array | I'm Trying To avoid memory lack and I need to understand if I need to set nullpointer to my
Multidimensional dynamic array after deleting an array. Here is my code.
int*** arr = new int** [lists];
for (int i = 0; i < lists; i++)
{
arr[i] = new int* [row];
for (int r = 0; r < row; r++)
{
arr[i][r] =... | Memory leak will not happen in your case , but for Good Practice you need to null your pointer after deleted that pointer , otherwise if you later dereference the same variable, your program will have undefined behavior
"unhandled exception error" may occur.
if(arr)
also not help this kind of case.
so use the null ... |
63,449,509 | 63,449,731 | C++ decoding LZ77-compressed data using std::fstream too slow | I have a function in my code which decodes a file compressed using the LZ77 algorithm. But on 15 MB input file decompression takes about 3 minutes (too slow). What's the reason of poor performance? On every step of the loop I read two or three bytes and get length, offset and next character. If offset is not zero I als... | You could try doing it on a std::stringstream in memory instead:
#include <sstream>
void uncompressData(long block_size, unsigned char* data, fstream& out)
{
std::stringstream file_out; // first line in the function
// the rest of your function goes here
out << file_out.rdbuf(); ... |
63,450,032 | 63,909,136 | C++: Represent variable in class diagram with two different possible types depending on preprocessor directive | I have a class that uses one varibale that can have two different types according to a preprocessor directive (#ifdef #else #endif). How should I cleanly represent this variable's type without creating another UML class diagram?
| Preprocessor tricks vs. OOP design
You use the preprocessor to influence your class definition in a way comparable to this example:
class A {
#ifdef X
V myvar;
#else
W mywar;
#endif
...
};
This trick uses the preprocessor, playing with token substitution, instead of using a proper OOP design to ach... |
63,450,434 | 63,450,448 | Why doesn't the below program crash? | I have written a small program but couldn't understand why it does't crash when a is accessed out of bounds?
#include <iostream>
using namespace std;
int main()
{
double *a = new double[4];
a[0]=1;
a[1]=2;
a[2]=3;
a[3]=4;
cout <<"size of double:"<<sizeof... |
Why doesn't the below program crash?
From perspective of C++: Because the behaviour of the program is undefined. The program is neither guaranteed to crash nor to not crash. Nor are there any other guarantees about the behaviour.
From perspective of the operating system: Assuming the compiler did not remove the acces... |
63,450,437 | 63,453,033 | How to pass array contents back and forth between managed (C#) and unmanaged (C++) code | I'm trying to pass an array of floats from C# to a C++ dll which will do some work on that array and then pass back an answer in the form of an array of float (not necessarily of the same length).
I have code that will pass the array, modify it and then return it, but the values in the array are not as expected though ... | I have managed to get things working.
I changed the GCHandle.Alloc method so it made a Pinned Object pointer and everything worked.
I also removed an unnecessary GCHandle call in the TestCallBackFunction
The full changed code is:-
C#
public delegate void CallBack1(IntPtr param, int len);
[DllImport("TestDll.dll", Calli... |
63,450,537 | 63,451,557 | How to link against Vulkan with MinGW and QMake? | I tried to link against Vulkan with:
LIBS += -L$$(VK_SDK_PATH)/Bin -lvulkan-1 # Doesn't work at all
LIBS += -L$$(VK_SDK_PATH)/Lib -lvulkan-1 # Works with MSVC
But I couldn't get it linking with MinGW.
INSTALLED:
VulkanSDK (1.2.148.1)
Qt (5.15.0; MSYS2)
MinGW (10.2.0; MSYS2)
| I installed the Vulkan Runtime and retried
LIBS += -L$$(VK_SDK_PATH)/Lib -lvulkan-1
with MinGW again and it works. Nevertheless, thank you for helping me out.
|
63,451,373 | 63,451,848 | Confusion in different ways of creating nodes in C++? | I was trying to solve merge two sorted linked list problem from leetcode.
I solved the problem but here's something which I'm not understanding, When I try to create nodes and their pointers using 'new' keyword(which stores the nodes in heap memory) it works, but when I change it to first creating node and then creatin... | The automatic variable dummy is both the cause of your problem, and simultaneously unnecessary.
Merging two lists simply means crafting a node chain from the other nodes, which are already allocated. Since you have no list "wrapper" (i.e. an object that contains both the node chain and other information such as a count... |
63,451,917 | 63,451,957 | why Copy Constructor was executed here | I could not understand why the copy constructor was executed when I just simply create one Object and execute one function.
using namespace std;
class Line {
public:
int getLength( void );
Line( int len ); // simple constructor
Line(const Line &obj);
~Line(); ... | This function:
void display(Line obj) {
cout << "Length of line : " << obj.getLength() <<endl;
}
takes the Line parameter by value, which calls the copy constructor when you invoke display here:
Line obj(10);
display(obj);
If you don't want to copy the argument then pass it by reference:
void display(Line &obj) {
... |
63,452,699 | 63,452,993 | Loading a C++ class with polymorphism using dlsym() | I have a C++ program which I need to open a shared object (.so) and load a C++ class from it. I have seen this done on the internet and I have loaded many things using dlsym() in both C and C++, so I know how everything works. However, there is a slight difference I need to make. The class I am loading with dlsym() mus... | As it turns out, the destructor and the typeinfo were the symbols which were undefined. Given how many times I've done things like this, I should have seen that, but nobody's perfect. Anyway, all I did to fix this was add = default for BaseClass::~BaseClass and = 0 for BaseClass::function. Thanks a lot to user G.M. in ... |
63,453,503 | 63,453,757 | Minimalistically building a test for a simple header using CMake | I have a C++ header which contains a class with a method like below. Lets say its a header only library I have.
// MyHeader.hpp
#pragma once
#include <string>
namespace myheaderonlylibrary {
class MyClass {
public:
unsigned int Func1(const std::string& str) {
if (!str.empty())
return 10;
... | Just like a normal C++ program you need to have a main function to execute, for a googletest unit test you can use the following:
int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
This will run your TEST function when executed.
To use ctest to actually run your ... |
63,453,595 | 63,455,090 | Prevent non-const object being used after container takes copy | I have a function which modifies an object and then a container takes a copy and stores:
void modifyObjectAndStore(Obj& obj)
{
obj.a = 5;
obj.b = 8;
// there's state set here which isn't possible to set in the caller
_container.takeCopy(obj);
// From this point on obj should not be modified/used di... | Posting my comment as an answer:
I would pass the parameter by rvalue reference: Obj&& obj.
This lets you move the object into the container instead of copying it.
There's also an implication that an argument passed to this function shouldn't be used after the call, but the compiler won't enforce this.
|
63,453,639 | 63,454,606 | fstring not reading from .txt file | I am trying to write a program that will read a .txt file that is called when the program is run from terminal.
the command used will be;
$ ./myexecutable input.txt
My program and the input.txt are in the same directory. My code so far is as follows
#include <string>
#include <fstream>
using namespace std;
int main(i... | This is the corrected code!!
You were opening myFile twice!!
First time in this statement ifstream myFile (filename);
Second time in this statement-myFile.open(filename);
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
int main(int argc , char* argv[]){
str... |
63,453,741 | 63,453,888 | Incremented iterator std::next when swapping | Consider the code:
list<int> a{ 4,3,1,2 };
auto i = a.begin();
swap(*i, *(++i));
Why does the swap do nothing? While the following works as expected?
list<int> a{ 4,3,1,2 };
auto i = a.begin();
swap(*i, *(next(i)));
| In the first code, the order of evaluation of the two ops *i and *(++i) unspecified after c++17, hence the second one may execute before the first, and then the swapping swaps two equivalent values.
In the attached link, u can see that
f(++i, ++i); // undefined behavior until C++17, unspecified after C++17
But ... |
63,453,743 | 63,454,208 | Map a memory address to a variable | How do I map a memory address to a variable to create a structure at that memory location? I tried the following piece of code to create a struct at the given memory address but it simply dumps the segmentation fault?
The memory location in the code is an Input Region where I need to set certain data and ring the doorb... |
Map a memory address to a variable
There is no way in C++ to choose the exact location of any variable. You can only choose storage class: automatic, static or thread local. The language implementation chooses the address.
How do I map a memory address to ... to create a structure at that memory location?
It is pos... |
63,453,815 | 63,459,239 | c++ Overload operator variable (int) in class | I have simple class with multiple variable for the same type :
class Hello : public HelloPure
{
private :
int X;
int Y;
int Z;
I understand how overload work, but i can't find a way to make the following logic work :
mh->X/*Or GetX()*/ += somevalue;
mh->Y/*Or GetX()*/ += somevalue2;
mh->Z/*Or GetX()*/ += s... | A common solution is to use one or more reference wrapper classes. Depending on how different your three cases really are, you may wish to use one wrapper with mutable data, or multiple wrappers:
class Hello {
void* m_PointerToManaged = nullptr;
public:
class XRef {
void* m_PointerToManaged;
public:... |
63,453,948 | 63,454,103 | Paint Icon with win32api c++ | I'm trying to paint an Icon onto my window with the win32 api. Here is where I load the image.
case WM_CREATE: {
HANDLE image = (HICON)LoadImage(NULL, TEXT("Button.ico"), IMAGE_ICON, 16, 16, LR_LOADFROMFILE | LR_LOADTRANSPARENT);
break;
}
Here is where I try to paint the icon onto the screen.
case WM_NCPAI... | One, you are not supposed to use BeginPaint() in a WM_NCPAINT handler, only in a WM_PAINT handler. Per the WM_NCPAINT documentation, use GetDCEx() instead.
Two, you likely have STRICT Type Checking turned on (which is a good thing), that is why you are getting the compiler error. Under STRICT, an HGDIOBJ (aka void*) c... |
63,453,975 | 63,455,952 | is an argument of type long OK for %x printf specifier? | I found this on Win32 docs:
// Check the smart card context handle.
// hContext was set previously by SCardEstablishContext.
LONG lReturn;
lReturn = SCardIsValidContext(hContext);
if ( SCARD_S_SUCCESS != lReturn )
{
// Function failed; check return value.
if ( ERROR_INVALID_HANDLE == lReturn )
printf(... |
is an argument of type long OK for %x printf specifier?
No, it is not OK in C++. %x is for unsigned int, not for long.
Is this well defined behavior?
No, this is undefined behaviour. Quote from C standard draft (which is where the format specifiers are defined):
x,X The unsigned int argument is converted to ... un... |
63,454,499 | 63,455,053 | How to force the user to enter function parameters as a Unicode string? | For example, I have a function/method which takes a string parameter of type const char* as follow:
void func(const char* str){
// ..........
}
// When using, the user has two options:
func("Hello 日本語 سلام Ä भारतीय ไทย"); // option 1, non-UTF-8
func(u8"Hello 日本語 سلام Ä भारतीय ไทย"); // option 2, UTF-8
How to ... | Given a const char* str, there is no way to enforce at compile time that it points to a string with particular encoding. At run time it is possible to inspect whether the string contains invalid unicode sequences, but lack of such invalid sequences is not a guarantee that the string is necessarily unicode.
Until C++11,... |
63,454,784 | 63,454,907 | Storing new object in pointer vector c++ | With the following code i need to store new object in pointer vector. I've done it but now it wont show any information about object in loop (where I go trough vector). In class Tvrtka (company) I have pointer vector of Zaposlenik(worker). For every object I store it goes to vector.
class Tvrtka{
public:
string oib... | In this loop
for(int i=0;_z.size();i++)
{
zaposlenici.push_back(_z[i]);
}
_z.size() is used as loop condition and this is not dependent with i.
This means that if you pass non-empty vector as _z, the loop will go infinitely and it will run out of memory.
It should be
for(int i=0;i<_z.size();i++)
{
zaposlenici.... |
63,455,352 | 63,463,360 | Remote DLL Debugging from ctypes in Visual Studio | I'm making a dll for python using c++ and importing functions using ctypes library.
I know that to do remote debugging you go to Debug -> Attach to Process.
I put a breakpoint in python code before imported function is called, but I don't know what process to attach to. I tried attaching to python.exe, but that didn't ... | The process which need to be attached to is the process that needs to call the dll. If you want to remote debug dll, I suggest that you could refer to this link about Remote Debugging a C++ Project in Visual Studio. Also, you could refer to this link about Debug DLLs in Visual Studio.
I suggest that you could look in t... |
63,455,427 | 63,456,129 | fatal error: opencv2/opencv_modules.hpp: No such file or directory #include "opencv2/opencv_modules.hpp" | Hello all I am trying to use opencv-c++ API (version 4.4.0) which I have built from source. It is installed in /usr/local/ and I was simply trying to load and display an image using the following code -
#include <iostream>
#include <opencv4/opencv2/opencv.hpp>
#include <opencv4/opencv2/core.hpp>
#include <opencv4/openc... | The solution is to just include_directories path till /usr/local/opencv4 and it works perfectly.
However, the best way I believe is to use the find_package function. I updated my Cmake to the following and it takes care of linking during build.
cmake_minimum_required(VERSION 3.15)
project(opencvTest)
set(CMAKE_CXX_STA... |
63,455,486 | 63,455,638 | How to call a specific function from an array of functions? | I'm working on building a watch based on the Arduino/ATMega. The primary goal for now is to switch between "modes” (different functions) by pressing a button on the side. Initially, I had a long if statement like this:
if (counter == 0)
mode1();
enter code
else if (counter == 1)
mode2();
.... Repeat..... | The type is wrong - instead of int you need void (*)() as type (because you have an array of void someFunction() function pointers, not an array of integers - and while the former can be converted to the latter in a way, as memory address, you cannot call an integer).
void (*Modes[3])() = {showTime, flashlight, antiAnx... |
63,455,928 | 63,456,005 | Why is_integral_v<string> is true? | I guess the title of the question does not make much of a sense, but I hope the problem description will spread the light.
Can someone please explain how on earth this is passing the compilation?
template<typename Cont, typename = std::enable_if<std::is_integral_v<std::string>>>
void print(const Cont& cont)
{
for ... | std::enable_if<false> still exists as a type, and that's what you've deduced your unused type parameter to be.
It just exists as a type which does not itself have a nested public member typedef type. That's why you have to use std::enable_if<EXPR>::type or std::enable_if_t<EXPR> to get the behaviour you expect.
You can... |
63,456,410 | 63,456,458 | Pointer gives whole array instead of one character in C++ RayLib | I am very new to C++ and decided to start off by making tic tac toe with RayLib as a graphics engine.
The code below sets up a screen, draws the grid and checks for an input.
The part I was working on is showing an X or O in the fields that were clicked on.
I finally got the program to draw text but it seems to draw th... | C-style string is terminated with null character (\0), so you must add that or you have it read out-of-bounds and invoke undefine behavior.
Therefore,
char text = matrix[i];
should be
char text[] = {matrix[i], '\0'};
and
DrawText(&text, textX, textY, 20, LIGHTGRAY);
should be
DrawText(text, textX, textY, 20, LIGHTGR... |
63,456,924 | 63,456,966 | What to expect when processing TCP data | I am using a POSIX OS (vxWorks) and want to understand how to process TCP data. I understand in UDP everything is really up to you and TCP is a lot more managed underneath.
Suppose a remote socket I am connected to promises to send me JSON data. The documentation simply says, once established, we will send you JSON dat... | TCP has no idea about application messages. You need to implement the protocol layered on top of TCP to find message boundaries, if your protocol has one.
|
63,456,999 | 63,457,108 | (How) can I cast between an aggregate type with one member and that member's type? | Is it possible to do this?
struct compound_type {
int member;
};
void func()
{
compound_type foo {384};
int bar = sole_member_type_cast<int>(foo); // doesn't compile; there's no such thing
// reinterpret_cast wouldn't compile here
std::cout << bar << std::... | Yes, you can do:
int bar = *reinterpret_cast<int*>(&foo);
This is well defined since objects of compound_type and int are pointer-inter-convertible. The address of foois the same as the address of its first data member which is an int, and so the reinterpret_cast is well defined.
As pointed out in the comments by @R... |
63,457,163 | 63,457,249 | Can you have two classes with the same name and the same member function in different translation units? | Suppose I have two translation units:
//A.cpp
class X
{
};
//B.cpp
class X
{
int i;
};
Is the above program well-formed?
If not, no further questions. If the answer is yes, the program is well-formed (ignore the absence of main), then the second question. What if there is a function with the same name in those?
//... |
Is the above program well-formed?
No. It violates the One-Definition Rule:
[basic.def.odr]
There can be more than one definition of a
class type ([class]),
...
in a program provided that each definition appears in a different translation unit and the definitions satisfy the following requirements.
Given such an en... |
63,457,241 | 63,457,550 | How to work with pointers into raw memory provided by custom allocators (without UB)? | I am trying to write an allocator-aware container. Suppose I want to allocate a chunk of memory for three objects:
T* chunk = std::allocator_traits<Allocator>::allocate(allocator, 3);
(I know that allocators can have custom pointer types and therefore I should use std::allocator_traits<Allocator>::pointer; I am using ... | In the latest standard draft (C++20):
[tab:cpp17.allocator]
a.allocate(n) - Memory is allocated for an array of n T and such an object is created but array elements are not constructed.
allocator_traits::allocate(n) simply calls a.allocate(n).
So, given that the array is created, the pointer arithmetic is well defin... |
63,457,481 | 63,458,018 | Unable to call function in main (Inheritance in UDP Client App using C++) | I have created a separate UDP Server Application and a Client Application, and they are communicating with each other. I have tried to implement inheritance as the next step for this application (Base class : udp, child class: udpClient). I have developed the code for the client which I have presented my code below wit... | udp_client::udpworking requires two arguments, that you need to pass in parameters (in the parenthesis).
Also as mentioned in the comments void main() is not a valid signature for this function. Only int main() (which ignores all parameters) and int main(int argc, char **argv) (which takes in the command line parameter... |
63,457,513 | 63,492,464 | What notification is provided for a lost connection in a C++ gRPC async server | I have an async gRPC server for Windows written in C++. I’d like to detect the loss of connection to a client – whether a network connection is lost, or the client crashes, etc. I see references to the keepalive channel arguments, and I’ve tried various combinations of those settings, such as:
builder.AddChannelArgumen... | You can use ServerContext::AsyncNotifyWhenDone() to get a notification when the request has been cancelled.
https://grpc.github.io/grpc/cpp/classgrpc__impl_1_1_server_context_base.html#a0f1289f31257e6dbef57bc901bd7b5f2
|
63,457,560 | 63,457,832 | How to write function with the matching const modifier on argument and return types? | I want to write a function that extracts a pointer field from a struct. The requirement is that if I pass the struct as a const argument, the returned type should be const. If not, the returned type should not be const.
For instance,
struct S {
char *p;
};
// approach 1: two overload functions with duplicate body
... | Here's a solution with a single function template:
template<typename T,
typename = std::enable_if_t<
std::is_same_v<
std::remove_cv_t<
std::remove_reference_t<T>>, S>>>
auto extract(T&& input)
-> std::conditional_t<
std::is_cons... |
63,458,933 | 63,458,964 | C++ Deleting objects in vector and replacing them by new objects | I want to delete objects inside a vector and replace them with new objects in my SFML C++ project. When I run the program, the old objects disappear and nothing appears in their place.
Here's the createObjects function:
vector<Object> createObjects(float numberOfObjects) {
vector<Object> v;
v.push_back(Object()... | You are not replacing the original vector at all, you are assigning the output of createObjects() to a local vector that goes out of scope immediately. You need to get rid of the local v variable that you are assigning to, by changing this:
vector<Objectk> v = createObjects(numberOfObjects);
To this:
v = createObject... |
63,459,269 | 63,459,328 | What if a reference is declared to point to itself? E.g. int& x = x; | The following code compiles successfully in g++ version 10.1.0:
int main()
{
int& x = x;
return x;
}
The compiler even has a warning defined for this, suggesting it's intentional that it isn't an error. When compiled with -Wall, it returns the following output:
<stdin>: In function ‘int main()’:
<stdin>:3:14: ... | The reason that this code is accepted is because the C++ grammar allows for it; not because there is any practical reason for it.
In the C++ grammar, the first part of the definition introduces the name identifier which may be in in the rest of the scope, including in the same statement. This is what allows you to have... |
63,459,428 | 63,514,445 | SDL keyboard strange behaviors | Only function keys get caught by SDL_KEYDOWN and they get printed normally , normal letters and numbers sometimes get caught by SDL_TEXTINPUT(unpredictably) but when i try to print them i get either nothing or things like "Æëçó" , the key dosen't get caught at all by the if statement . Does anyone have the same proble... | You would not access g_event.key.keysym.sym in a SDL_TEXTINPUT event.
It gives you a parameter as g_event.text.text where you have the inputed text as a char array.
|
63,459,644 | 63,477,196 | How to stream a fixed number of samples from a USRP using UHD | I am trying to stream a fixed/exact number of samples from a USRP X310 device using the UHD library. I have referenced some example code on the UHD GitHub page. I am using a while loop as recommended to stream data into a buffer one packet at a time. My problem is that the last partial packet (see example below) is nev... | After much trial and error, I figured out that this problem comes up because the sample rate parameter has not been set on the USRP. So before trying to stream samples be sure to set the sample rate!
usrpDevice->set_rx_rate(50e6);
// stream samples
|
63,459,871 | 63,460,136 | And odd use of conditional variable with local mutex | Poring through legacy code of old and large project, I had found that there was used some odd method of creating thread-safe queue, something like this:
template < typename _Msg>
class WaitQue: public QWaitCondition
{
public:
typedef _Msg DataType;
void wakeOne(const DataType& msg)
{
QMutexLocke... | Its legal to have a local condition variable. But it normally makes no sense.
As you've worked out in this case is wrong. You should be using the member:
void wait(DataType& msg)
{
QMutexLocker cvlock_(&mx);
while (que.empty())
QWaitCondition::wait(&mx);
msg = que.front();
que.pop(... |
63,460,249 | 63,461,596 | Find which sector a point lies in inside a rectangle split along it's diagonals | I have a program, which needs a function that returns an int (0 - 3) based on an x and y input. The return int should be based on the 'sector' that the point lies inside of a rectangle that has been cut on its diagonals.
This is my current code
int liesIn(double x, double y, double w, double h){
//x and y are reli... | One diagonal (from 0,0) has equation
y * w - x * h = 0
Another diagonal has equation
y * w + x * h - h * w = 0
Substitution of point x,y into these equations gives quadrant (result sign tells us at what side of diagonal point does lie).
int liesIn(double x, double y, double w, double h){
if (y < 0 || y >= h || ... |
63,460,950 | 63,461,063 | "No instance of overloaded function" error with static friend template function | I have a class A that is trying to call a nonmember function DoTheThing. DoTheThing is a friend of class A so that it can call a private member function TheThing of A. DoTheThing is a template function so that it can call TheThing in multiple user-defined classes. Because the error references an overloaded function, I ... | You are not constraining the friend declaration with an ad-hoc requires clause, so you are actually not granting friendship to the same DoTheThing function you want. You need to replicate the requires clause in the friend declaration as well:
class A {
template<class Component>
requires requires (std::vector<do... |
63,461,151 | 63,461,334 | Can struct be Initialized this way? | Below is my code, I define a struct containing int and string variables. I remembered that In c/c++,
struct can be initialized like this A a={0}, And I do this below, However, When I print out its string member b. program crashed with terminate called after throwing an instance of
'std::logic_error' what(): basic_str... | Your code is working fine, check the execution here.
Your, output will be empty as, strings in c++ is by default empty i.e. by default size of strings in c++ is 0. So, no output.
|
63,461,348 | 63,461,541 | how to design a single write and multiple read when the protected resource need to be return by getter as a shared_ptr in modern c++? | I have one writer thread write to a map in an object, and many reader object each in their own thread to perform read only on the map, my currrent design is like below,
class MyClass {
private:
shared_ptr<map<int, int>> my_map;
mutable shared_mutex mu;
public:
void update_or_add(pair<int, int> entry);
s... | Here is a really simple shared resource:
template<class T>
struct shared_threadsafe {
template<class F>
auto read(F&& f)const{
auto l = lock(); // shared lock
return f(t); // const access
}
template<class F>
auto write(F&& f){
auto l = lock(); // exclusive lock
return f(t); // non-const access... |
63,461,798 | 63,463,915 | C++ templated metaprogramming, checking if a struct has a field | So I recently discovered C++ does have reflections, it just happens no one, not even the C++ committee knew it yet until a Russian genius opened the door to an impossible to debug world of possibilities.
With that preface, let's look at this crime against humanity:
template <typename T, typename D = decltype(T().field)... | You might wrap in a functor (as lambda):
// C++20
#define HasField(C, Field) \
[](){ \
return overloaded{[]<typename T>(int) -> decltype(std::declval<T>().Field, void(), std::true_type()) { return {}; }, \
[]<typename T>(...) { return std::false_type{}; }}.operator()<C>(0); \
}... |
63,461,810 | 63,461,862 | Is there any coincidences I've done while templatizing this function in C++, using void swap()? | I am currently using C++ 17, and I wanted to simplify my program down. However, I am thrown error:
more than one instance of overloaded function \"swap\" matches the argument list: -- function template \"void swap(T &a, T &b)\" -- function template \"std::enable_if<std::__and_<std::is_move_constructible<_Tp>, std::is_m... | You should just use std::swap rather than your own.
But, for an explanation of your error:
using namesapce std;
Assuming that actually says namespace in your code, that is the problem. There is a swap in namespace std.
If you remove the using directive and qualify your std uses with std:: then you can call your swap u... |
63,461,923 | 63,486,215 | How to get source code of entire content of a webpage programmatically? | I would like to get source code of entire page including contents that is generated dynamically. I've tried wininet and curl but i just get the contents that rendered in code behind.
Example:
As you can see below, the list of people doesn't show up as source.
Page source:
<!DOCTYPE html>
<html>
<head>
<title>Prest... | I've found 2 solutions; IWebBrowser2 and WebView2.
IWebBrowser2 is using older versions of IE and some websites require higher versions. And there is no way of switching to Edge. There is a registry trick but it's not actually changing the version of IE. So this one is a bit problematic.
WebView2 is using latest vers... |
63,462,012 | 63,468,708 | How to change this code from recursion to iteration | I've trying to make the following code implement by iteration instead of recursive(the "hit" function of the BVH_node class),but I've no idea how to do this.I did found some topic about this,but they are not very helpful.Could anybody help me?thanks so much.(by the way this is the third time I ask this question ,people... | Follow up on the approach mentioned in a comment of Alan Birtles:
Let us focus on the hit function. In order to make our life easier, it's better to first rewrite it as follows:
bool hit(Ray& ray) {
if(!aabb.hit(ray)) return false;
if (is_node_or_geo == 0) {
if (L_node->hit(ray)) return true;
i... |
63,462,425 | 63,462,783 | What is related and unrelated processes? | Can someone please clarify the definition of related and unrelated processes?
I know that fork creates two related processes
fork()
However, I am not sure whether the process is still considered related when we call exec* family functions to replace program image:
if (child) {
exec("path to binary", ...) <- Is it s... |
Can we say that any process created with fork() regardless of whether
exec or original program image is used is always related?
Yes, we can.
Regardless of whether you call exec in child, parent and child processes can still talk to each other using pipes. See below example of creating child process, which will change... |
63,462,974 | 63,463,197 | traverse std::list , holding 2 last values | I need to traverse the std::list holding 2 last values,i.e if my list is [1,2,3,4,5,6]
iteration1 : v1 = 1, v2 = 2
iteration2 : v1 = 2, v2 = 3
iteration3 : v1 = 3, v2 = 4
iteration4 : v1 = 4, v2 = 5
iteration5 : v1 = 5, v2 = 6
I tried to
auto next = _contour.begin();
auto prev = next;
while( next != _contour.end())
{... | The problem, as you've hinted at, is that you check if next != _contour.end() before incrementing it, and after incrementing it you cannot be certain that it's not equal to the end iterator.
To solve this problem, switch around the logic in your loop such that you test the new value of next before each iteration.
For e... |
63,463,230 | 63,463,337 | How to run Command Prompt from a C++ program | I'm hoping to write a simple program in C++ that would allow me to run a Command Prompt through a C++ program, i.e. input commands in the C++ program are sent to the Command Prompt (CMD terminal will be hidden) and messages returned in the Command Prompt terminal are displayed in the C++ program.
I know about running .... | Declare a built-in string class type object firstly. Now, in an infinite loop, ask the user to input something in the beginning of each iteration. Execute the commands with the help of system() (put .c_str() member function after the identifier of the string which will convert them and represent as a char array because... |
63,463,475 | 63,463,591 | Player detecting wall in array in C++ | I want my player 'P' to be able to move around the map, but not move onto or past the walls. The code will work fine until I implement an if statement to check for walls.
My thought process to doing this was if the player moves in a direction, check if there's any walls in that direction first. If there is a wall, then... | The problem is most likely how you check for wall colisions.
For example if we look at map[py][++px] == '#' we see that you modify px, so even if that position is a wall the player position is modifed.
This also leads to problems in the else part, as you then "clear" the position where the player isn't, as well as modi... |
63,463,837 | 63,463,913 | Why can't I use chrono library? | Hello I am doing some easy exercise with thread, I want my t1 to sleep 2 seconds but I am getting this error: unable to find numeric literal operator ‘operator""s’
How is that possible?
#include <iostream>
#include <chrono>
#include <thread>
void printt1(int i)
{ std::this_thread::sleep_for(2s);
std::cout << i<<... | From https://en.cppreference.com/w/cpp/symbol_index/chrono_literals:
These operators are declared in the namespace std::literals::chrono_literals, where both literals and chrono_literals are inline namespaces. Access to these operators can be gained with using namespace std::literals, using namespace std::chrono_liter... |
63,464,085 | 63,597,651 | ColoredPrintf in recent googletest | I was using rather obsolete version of GoogleTest and have used hack for custom printing, found here: How to send custom message in Google C++ Testing Framework?
My sources contain the following code from the link above
namespace testing
{
namespace internal
{
enum GTestColor {
COLOR_DEFAULT,
COLOR_RED,... | You cannot access members in an anonymous namespace outside of the compilation unit. See also this question.
Depending on your use-case alternatives may be:
Use event listeners to replace the standard output.
Pipe the output through a script that modifies the output.
Have Google Test generate an XML or JSON report and... |
63,464,158 | 63,464,250 | What part in cppreference tells me structured binding declarations only work with compile-time known objects? | My question is
What part of the cppreference.com's page on structured binding declarations should make apparent that they cannot be used with "things" not known at compile time?
That page does not contain any explicit reference to compile or run time.
Why?
I recently bumped into this question about whether structured b... | The relevant part is std::tuple_size, which yields a compile-time size. You can't implement that for std::vector. It has a run-time variable std::vector::size.
|
63,464,334 | 63,465,526 | Getting the color of a pixel at a specific x,y coordinate, then executing a click | I very recently got into C++, and am basically learning through watching videos and reverse-engineering other people's code. Needless to say, I'm not very good at this stuff yet.
Anyway, I'm working on a program that detects if a specific color (RGB) is at a specific coordinate in another window, and if it is, the code... | I changed the fixed coordinates to follow the cursor position and your program seems to work fine. Clicks are also executed!
int main()
{
COLORREF colortosearch = RGB(0, 0, 255); // color to search
HDC hdcScreen = GetDC(NULL);
while (true)
{
POINT cursor;
GetCursorPos(&cursor);
... |
63,464,385 | 63,464,475 | std::vector Error shows up: "Cannot increment a vector past the end", while wanting to erase specific element | I have a vector of classes, the class has a string name, among other private fields.
I want to implement a void delete(string name) function, which looks for the element based on the string (each class in a vector has a unique name).
However after simple testing, it gives me an error "Cannot increment past the end".
Th... | You are invalidating it when you erase, so later uses of it are undefined, including incrementing and comparing it in the loop test.
You could
for (auto it = member_list.begin(); it != member_list.end(); )
if (it->get_name() == member_name)
it = member_list.erase(it);
else
it++
However there is... |
63,464,769 | 63,567,948 | Problem with async_write two times in a row | When I call async_write 2 times the second message isn't sent to the server. In write handler I call async_read and when I run my code, the program is stuck on read.
In connection handler:
clientSocketPtr->lowest_layer().set_option(BA::ip::tcp::no_delay(true));
clientSocketPtr->set_verify_mode(BA::ssl::verify_peer);
cl... | I've done some research and solved my problem using strand and making a message queue. First of all, it is important to push messages to the queue and then call the function which will check if queue isn't empty. If it isn't, the code will process the message and call async_write and right after this it will pop this m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.