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 |
|---|---|---|---|---|
61,855,950 | 61,855,958 | C++ array assignment gives compiler error | When i try to assign values to an array like this:
int ar[5] = {18,19,20,21,22,23};
I get a compiler error: too many initializers for 'int [5]'
But when I do it like this:
int ar[5];
ar[0] = 12, ar[1] = 13, ar[2] = 14, ar[3] = 15, ar[4] = 16, ar[5] = 17;
Everthing is fine and the program runs fine and outputs correct... | Yes, you are doing something wrong here:
ar[5] = 17;
by invoking undefined behavior. You can't index the 6th element (which is stored at the index 5) of an array containing only 5 elements.
The fact that the program runs and gives the correct output is an accident. You can't rely on this, and the program is fundamenta... |
61,856,148 | 61,856,398 | Nanosecond-level C++ program idling / throttling | I'm writing a C++ program that runs a microcontroller emulator. The thread that runs the emulator does so in a loop like this:
while(should_run) {
simulator->RunSingleClockCycle();
}
On my laptop this manages to run the emulator at around 60 MHz. Since I only need the emulator to run at 16MHz, I can slow it down usi... | On conventional hardware you're never going to get nanosecond timing. For example, on my system running this code (not taking into account the race condition):
#include <thread>
#include <chrono>
#include <future>
#include <iostream>
int main()
{
unsigned int counter = 0;
auto res = std::async(std::launch::a... |
61,856,191 | 61,856,203 | Why does printf executes faster than cout in C++?Also scanf is slower than cin,why? | I've made some programs and saw that scanf and printf are considerably faster than using cin and cout?
| By default, cin/cout waste time synchronizing themselves with the C library’s stdio buffers, so that you can freely intermix calls to scanf/printf with operations on cin/cout.
Turn this off with
std::ios_base::sync_with_stdio(false);
Also many C++ tutorials tell you to write cout << endl instead of cout << '\n'. But en... |
61,856,448 | 61,856,581 | Declare constructor of a derived class as friend of parent class | As every C++ newbie out there I am coding my own matrix class as an exercise. I am using class templates like this:
template<typename T>
class BMatrix {
public:
// Constructors
BMatrix(unsigned nrows, unsigned ncols);
BMatrix(unsigned nrows, unsigned ncols, T ival);
BMatrix(const BMatrix<T>& a);
// ... | If you need something to be accessible in the derived class then make it protected instead of private. You don't need friend in this case.
You might also add a protected constructor in BMatrix that initializes data_ with the desired number of elements that you could call (delegate) in your derived class constructor.
Fo... |
61,856,487 | 61,857,195 | Confusion about declaration and definition of static const data memebers | Scott Meyers writes in Effective Modern C++ (Item 30, at page 210) that there's
no need to define integral static const data members in classes; declarations alone suffice,
then the sample code is
class Widget {
public:
static const std::size_t MinVals = 28; // MinVals' declaration;
...
};
... ... |
no need to define integral static const data members in classes; declarations alone suffice,
Declarations alone suffice only if that object is not ODR-used, that is, if a data member is not used in a context that would require its address to exist (like binding to a reference or applying operator &). The presence of ... |
61,856,747 | 61,856,980 | alignas() effect on sizeof() - mandatory? | This program:
struct alignas(4) foo {};
int main() { return sizeof(foo); }
returns 4, with GCC 10.1 and clang 10.1, and icc 19.0.1 .
That makes me wonder - is it mandatory for alignas() to affect sizeof() this way? i.e. increase the size beyond what the structure would originally be sized at? Or - is this change just ... |
is it mandatory for alignas() to affect sizeof() this way? i.e. increase the size beyond what the structure would originally be sized at?
Yes. Size of a class is defined in terms of distance between elements of an array of that type. There is no padding between elements of an array (except for padding that is within ... |
61,856,820 | 61,857,121 | Assertion failed while using imwrite OpenCV | When running this code
int main(int argc, char *argv[])
{
vector<cv::Mat> imgs(argc - 1);
for (auto i = 1; i < argc; ++i)
{
cv::Mat img = cv::imread(argv[i]);
cv::Mat dst;
cv::GaussianBlur(img, dst, cv::Size(3, 3), 0, 0, cv::BORDER_DEFAULT);
cv::Sobel(dst, dst, -1, 1, 1);
... | vector<cv::Mat> imgs(argc - 1);
should be
vector<cv::Mat> imgs;
You don't create the vector at the required size and then use push_back.
Either create the vector at zero size and use push_back to add items to it, or create the vector at the required size and use subscripting to assign items to it.
Also as Gerardo Zin... |
61,857,306 | 61,857,367 | Safely skip an task if mutex is locked | Am struggling with bending my mind around mutexes/locks.
The situation:
There is Task A that takes a relatively long time. It is executed irregularly in one thread (but only once at a time).
There is Task B which is quick and is very regularly called from another thread.
Both tasks work on the same memory and thus sho... | Your code is correct, but for exception safety and to protect from resource leaks you should better use RAII in task B. The general rule is "Use RAII lock guards (lock_guard, unique_lock, shared_lock), never call mutex.lock and mutex.unlock directly (RAII)".
std::unique_lock<std::mutex> mlock(the_mutex, std::defer_lock... |
61,857,361 | 61,857,515 | Using syntax to expose base class alias templates and variable templates in derived class? | Consider a base template class and a derived template class in a heavy template metaprogramming context (simplified here for readability and to focus on the problem).
template <class T>
struct base {
using type = T;
static constexpr int value = 0;
template <class... Args>
constexpr void function(Args&&.... | using doesn't work this way for dependent member templates:
A using-declaration also can't be used to introduce the name of a dependent member template as a template-name (the template disambiguator for dependent names is not permitted)
I'm not sure if this will satisfy your requirements, but in order to make the ali... |
61,857,582 | 61,857,655 | Run function both as constexpr and without constexpr | i have a class that generates a pseudorandom number.
i need to run the pseudorandom number generator function both in a constexpr function (i need it to generate it at compile-time) and during run-time
it works perfectly, but i am wondering if there's some way to do the following:
i want a single function that generate... | constexpr functions can be called both at compile time, and run time. Depending on the context that the function is called in, it will be evaluated accordingly. e.g:
constexpr int f() { return 42; }
int main()
{
int a[f()]; // array bounds must be compile time, so f is called at compile time
int b = f(); // not a ... |
61,857,662 | 61,866,725 | Correct way of using fdopen | I mean to associate a file descriptor with a file pointer and use that for writing.
I put together program io.cc below:
int main() {
ssize_t nbytes;
const int fd = 3;
char c[100] = "Testing\n";
nbytes = write(fd, (void *) c, strlen(c)); // Line #1
FILE * fp = fdopen(fd, "a");
fprintf(fp, "Wr... |
Why is that?
The opened stream ("stream" is an opened FILE*) is block buffered, so nothing gets written to the destination before the file is flushed. Exiting from an application closes all open streams, which flushes the stream.
Because you close the underlying file descriptor before flushing the stream, the behavio... |
61,857,743 | 61,859,231 | Write a function that only accepts literal `0` or literal `1` as argument | Sometimes for algebraic types it is convenient to have a constructor that takes a literal value 0 to denote the neutral element, or 1 to denote the multiplicative identity element, even if the underlying type is not an integer.
The problem is that it is not obvious how to convince the compiler only to accept, 0 or 1 wi... | In C++20 you can use the consteval keyword to force compile time evaluation. With that you could create a struct, which has a consteval constructor and use that as an argument to a function. Like this:
struct S
{
private:
int x;
public:
S() = delete;
consteval S(int _x)
: x(_x)
{
if (x... |
61,858,175 | 61,859,061 | Too many arguments in a condition | I recently had problem with making a condition in my code (which is very simple btw). And I cant figure out why this code has not the output that I wanted it to have.
Basically it is a code that gets an angle and tells you in which area of circle it will be.
And the problem is how can I put all of conditions in that if... | Let's consider the lines like this
if (0 < a < 90 | -270 < a < 360) {
// ^^^^^ ^^^^^
}
Whether a is less than 0 or not, the result of 0 < a is a bool value which is then compared to 90. Given that both 0 and 1 are less than 90, (0 < a) < 90 is always true. You have to split the condition.
if ((0 < a && ... |
61,858,274 | 61,859,302 | 3D vector iterate over sphere | I have a 3D vector and want to iterate over all neighbors that have a limited distance to a certain point (i.e. over a ball). I decided to use the P1 instead of the Euclidian Distance to make it a bit cleaner.
My approach looks like the following, but unfortunately does not give me all the neighbors.
std::vector<std::v... | Version with two checks. You may simply check conditions inside. It is robust and you will be to change metrics.
for (int neighbor_x = x - radius; neighbor_x <= x + radius; ++neighbor_x) {
for (int neighbor_y = y - radius; neighbor_y <= y + radius; ++neighbor_y) {
for (int neighbor_z = z - radius; neighbor... |
61,858,302 | 61,858,427 | How to find the number of excution of this function? | I want to find the number of this function executions. The function in a cc file is:
CacheSetLRU::CacheSetLRU(
CacheBase::cache_t cache_type,
UInt32 associativity, UInt32 blocksize, CacheSetInfoLRU* set_info, UInt8 num_attempts)
: CacheSet(cache_type, associativity, blocksize)
, m_num_attempts(num_at... | You can create yourself a Recorder type that you place as an object with static lifetime in your function and have its destructor output the number of uses. For instance:
#include <iostream>
template <typename T>
struct Recorder {
T data;
~Recorder() {
std::cout << data << "\n";
}
};
struct Foo {
void bar... |
61,858,364 | 61,858,448 | What is the time complexity of log10 function in cmath? | What is the time complexity of log10 function in cmath ?
Its nowhere mentioned on the internet. Does anyone know for sure ?
Later edit:
My initial question was if the following code is faster.
int numOfDigits(int n) {
return (int)log10(n) + 1;
}
than this
int numOfDigits(int n) {
int count = 0;
while(n) {
... | The standard does not specify complexity requirement for the log10 function.
However, I would expect a reasonable implementation to have constant complexity.
|
61,858,532 | 61,862,029 | How to add a QToolBar inside a QTabWidget | I have been trying to add a QToolBar inside a QTabWidget in order to achieve something like the image below, so that everytime I add a new QTabWidget I have also a related QToolBar inside it.
Everything seems to work fine, I create a QAction to link it to the QTabWidget and according to this post it seems to be possib... | You can simply do something like this, and it really works.
QToolBar *toolbar=new QToolBar("toolbar",ui->tab);
toolbar->addAction("action1");
toolbar->addAction("action2");
enter image description here
|
61,858,676 | 61,858,924 | Class instance member that depends on class member attribute | My faculty provided me with a class that represents a Binary Tree and we have to use it for an assigment.
So I'm doing a class called cluster and the thing goes like this:
BinTree (I've only copied what I though it's the minimum necessary):
template <typename T>
class BinTree {
public:
// Constructs an empty tree. Θ(1... | From what I understood, you want to merge 2 clusters so, you can do it similary to how it is done in the BinTree class.
explicit Cluster ( Cluster& left, const Cluster& right){
_cluster = Cluster(left, right) ;
}
I don't undeestand the functionality of the cluster class, it might be easier to use BinTree directly... |
61,858,779 | 61,858,939 | What happens if we don't return 0 from std::qsort? | According to the documentation qsort is supposed to be used like:
std::qsort(a, size, sizeof *a, [](const void* a, const void* b)
{
if(*a < *b) return -1;
if(*a> *a) return 1;
return 0;
});
If the values are the same and I don't mind which comes first, or I prefer one to come before th... | According to the C11 standard (7.22.5/4),
When the same objects (consisting of size bytes, irrespective of their current positions
in the array) are passed more than once to the comparison function, the results shall be
consistent with one another. That is, for qsort they shall define a total ordering on the
arr... |
61,858,805 | 61,859,091 | Writing to one channel at a time in libsndfile | I'm trying to generate a sine wave that switches between the left and right channels of a stereo wav file at 1 second intervals, but I can't find any way to write to one channel while keeping the other one silent. Here is the code I've got to write to one channel:
for (int f = 0; f < numFrames; f++) {
double time =... | You can achieve this by just writing zero samples to the 'silent' channel, e.g. (to silence the right-hand channel):
for (int f = 0; f < numFrames; f++)
{
double time = f * duration / numFrames;
buffer[f * 2] = sin(2.0 * pi * time * freq);
buffer[f * 2 + 1] = 0;
}
This assumes that libsndfile expects chann... |
61,859,381 | 61,859,452 | How C++ understands Array as pointers point of view? | I wrote the piece of code below but when I tried to return some two-dimensional array, it throws the following error.
int (* function (int input[2][2]) ) [2][2]{
return input;
}
from trial and error, I understand that when I change the function declaration to int (* function (args) ) [2] {...} it wo... | In this function declaration
int (* function (int input[2][2]) ) [2][2];
the argument of the array type is implicitly adjusted by the compiler to pointer to the array element type. That is for example these function declarations
int (* function (int input[2][2]) ) [2][2];
int (* function (int input[100][2]) ) [2][2];... |
61,860,279 | 61,860,500 | C/C++ Common Controls detecting double-click of TVItem | Is there any way to detect if a tree view control (and specifically a TVITEM) is double clicked using Common Controls & WINAPI?
I mean in my wndproc function of a form.
If so, what are the msg, wParam & lParam in that case?
| A treeview control sends an NM_DBLCLK notification when you double-click it, with uMsg = WM_NOTIFY and lParam pointing to an NMHDR structure as per the documentation.
You can then send the treeview control a TVM_HITTEST message to determine the item under the cursor, something like:
TVHITTESTINFO tvhti = {};
GetCursor... |
61,860,397 | 61,882,995 | Visual Studio cannot find my C++ hello world file | #include <iostream>
int main()
{
std::cout << "Hello World" << endl;
return 0;
}
When I try to run this code, this message keeps popping up even though I copied and pasted straight from online. There are no build errors either.
Here's the error message
| I added the file from the new file option not directly from the source file once I created the c++ project.
|
61,860,494 | 61,862,172 | Is std::destroy a no-op for fundamental types? | I often write something like this to prevent std::destroy from looping through arrays of elements that do not need to be destroyed but I have no idea if it is actually useful in any way.
if constexpr (!std::is_fundamental_v<element_type>) {
std::destroy(container_begin(), container_end());
}
Will dropping if con... |
Will dropping if constexpr statement change anything in the behavior of this code?
It will not change the observable behaviour in any way, assuming iteration of the container has no side-effects.
The behaviour of std::destroy is to invoke location->~T() for each element. location->~T() has no effects for trivial type... |
61,860,641 | 61,904,389 | ZLib creates a damaged archive | I use zlib 1.211 as a dynamic library and VS2019.
I create a simple zip from a txt file
FILE* input = fopen("D:\\1.txt", "rb");
FILE* output = fopen("D:\\1.zip", "wb");
/* do compression if no arguments */
bool ok = compress_file(input, output);
fclose(output);
fclose(input);
Compression function is:
bool compress_fi... | zlib doesn't make zip archives. Your code makes zlib streams. Two different things.
|
61,860,680 | 66,620,061 | What is complexity of my code and how can I improve it? | This is the problem from the CSES problem set.
There are n applicants and m free apartments. Your task is to distribute the apartments so that as many applicants as possible will get an apartment.
Each applicant has a desired apartment size, and they will accept any apartment whose size is close enough to the desired s... | My solution just got accepted
Ideas:
For each applicant, calculate their respective range based on k.
Remove the applicants who will never get assigned to any one of the given apartments
Sort the applicants' ranges
Sort the apartments
Now for each apartment, find the first applicant whose range includes the size of th... |
61,860,922 | 61,860,966 | Can I create a new map on the fly and pass as a function parameter? | In C#, I could so something like the following:
public static Dictionary<string,string> ExampleFunction(Dictionary<string, string> dict)
{
return dict;
}
public static void CallingFunction()
{
ExampleFunction(new Dictionary<string, string>() { { "test", "... | You may be looking for something like this:
std::map<std::string, std::string> ExampleFunction(
const std::map<std::string, std::string>& dict) {
return dict;
}
void CallingFunction() {
ExampleFunction({ { "test", "test" } });
}
Demo
|
61,860,943 | 61,864,360 | Convert java code that returns object with template into c++ using jni | I need to call some java code from C++ using JNI.
I can't figure out how to get a value from a returned java generic with JNI. Java code that I need to call from C++ is:
encoderCapabilities.getQualityRange().getLower()
The problem is java returns the generic type Range<Integer>:
public Range<Integer> getQualityRange (... | After type erasure, Range#getLower will have declared type Comparable, regardless of what the type in the Java source was.
Try this instead:
jobject range = ...;
jclass cls_Range = env->GetObjectClass(range);
jmethodID mid_Range_getLower = env->GetMethodID(cls_Range, "getLower", "()Ljava/lang/Comparable;");
jobject lo... |
61,861,026 | 61,861,971 | How does the C++ standard library work behind the scenes? | This question has been bothering me so much for the past couple of days. I was wondering how the standard library works, in terms of functionality. I couldn't find an answer anywhere, even by checking the source code provided by the LLVM compiler which is, for a beginner like me, a really complicated piece of code.
Wha... |
Does it use the OS specific API (since the library is cross platform), or what?
At some point, the OS specific API is used. The fstream implementation does not necessarily call an OS function directly. It might use other classes, which call functions inherited from C, etc., but eventually the call chain will lead to ... |
61,861,906 | 61,905,552 | Gmock const method not called instead calling the original method | I have interface which is defined as
in .h file
namespace diagnostic{
class class1interface{
virtual int readpowerstate()const =0;
virtual int readparameters() = 0;
}
class class1 : public class1interface{
int readpowerstate()const;
int readparameters();}};
in .cc file i have the function
int diagnostic::readparameter... | Module tests are all about testing an isolated module (like an instance of a selected class) in a mocked environment, specifically, how that module communicates with other objects, and how it responds to various results of these calls. To make this possible, one uses mocks in place of that other real objects. Mock clas... |
61,861,979 | 61,863,243 | inheritance parameter setup for template | So I am trying to append new accounts with vector which in Class Bank. For new account such as Class checking and Class saving that are derived from Class bankaccount.
I could not figure out what type of parameter I have to put in void addaccount() parameter so I can use it in main function below. Is it possible way I... | In your example, there is no need for templates. You can use runtime polymorphism and you were already half way there. However, you code had a lot of errors and I fixed multiple of them. Nonetheless, I still might have missed something. Please, next time, make sure that there are no bugs in your code unrelated to your ... |
61,862,378 | 61,862,444 | Implicitly generated function overloads for rvalue argument? | I am sorry if this question was asked before or I am missing something trivial, however the following for references is not clear to me. I understand why passing a rvalue instead of lvalue is allowed when the function parameter is not a reference, however I do not understand the reason it is allowed when the function p... |
I do not understand the reason [passing a rvalue instead of lvalue] is allowed when the function parameter is a const reference
This makes copying from rvalues possible using copy constructor. There may be other reasons too, but this is quite a useful feature.
Is this a bug or a feature?
It is intentionally specifi... |
61,862,468 | 61,862,608 | equal_to usage in C++ template class | I am confused on how to use this method. I tried the following:
std::equal_to(T objA, T objB);
I get errors if I use it like this. However, I have seen countless examples that use it like this:
pairs1 = mismatch(v1.begin(), v1.end(),
v2.begin(),
equal_to<int>());
How is this met... | equal_to is not a function, you cannot call it directly like one. It's a class that has the operator() defined which means that you need to create an object and call operator() on that object.
Possible implementation:
template <class T = void>
struct equal_to {
constexpr bool operator()(const T& lhs, const T& rhs) ... |
61,863,018 | 65,978,315 | How do you install library "iberty" for MacOS? | Trying to compile backward-cpp https://github.com/bombela/backward-cpp for MacOS Mojave, and getting this:
ld: library not found for -liberty
Which is straighforward in and of itself, but I can't seem to find how to install it?
https://unix.stackexchange.com/questions/160517/configuration-error-iberty-library-not-fou... | You can use Homebrew for that. First add --enable-install-libiberty to the configure option of binutils using:
brew edit binutils
then reinstall it using:
brew reinstall -s binutils
|
61,863,300 | 61,863,446 | error: 'const char* HTTPREQUESTS::certificate' is not a static member of 'class HTTPREQUESTS' | Here's a general question I hope you can explain me. In case why you're wondering why I use cstring it's because the Arduino doesn't support for exampe std by default. However, my problem is the error
error: 'const char* HTTPREQUESTS::certificate' is not a static member
of 'class HTTPREQUESTS'
#include <cstring>
... | These class members are already declared in the class.
You probably want this:
class HTTPREQUESTS {
public:
HTTPREQUESTS(char const strAddress[64] = "defaultAddress", char const strParameters[256] = "defaultParameters", bool bSendImmediately = false, char const* cert = root_ca_sherz);
~HTTPREQUESTS();
bool send... |
61,863,546 | 61,863,608 | Is there a way to explicitly call optional arguments in c++? | When I create a function such as:
int addThree(int x=1, int y=1, int z=1)
I want to call the function such that it uses the default arguments for x and z, but not y.
Some attempts have been addThree(5,,5) and addThree(5,NULL,5), but neither work effectively.
| The default arguments must be at the last of your list, so do as follows
int addThree(int y , int x = 1, int z = 1)
{
//some stuff
return someInt;
}
, hence you can call it as
int ans = addThree(4);
|
61,863,921 | 61,864,762 | Comma Operator in alignas | This code compiled and ran fine (outputting 5) on Visual Studio 2019
#include <iostream>
int main(void) {
alignas(2,3,9,8) int x=5;
std::cout << x;
return 0;
}
in C comma expressions are explicitly disallowed in alignas. This compiled fine here. I changed the order and placed 9 or 3 at the end (whi... | alignment-specifier is required to enclose a type-id or a constant-expression ([dcl.attr]):
alignment-specifier:
alignas ( type-id ...opt )
alignas ( constant-expression ...opt )
And constant-expression is required to be a conditional-expression ([expr.const]):
constant-expression:
conditional-expression... |
61,863,942 | 61,865,790 | Open a link at a specific time with C++ | So I am trying to write a C++ console program that opens a link with a web browser at a specific time. The clock updates fine and the shell line opens the link but I just can't get these two to work together. Here's my code:
#include <Windows.h>
#include <shellapi.h>
#include <ctime>
#include <chrono>
#include <thread>... | At least to me, your code seems a little confusing. It's not clear why we'd sleep for a second at a time until we reach the target. Worse, if one of the sleep calls happens to go a little too long, we could over-shoot the mark, and never carry out the desired action. And still worse, if we do reach the desired time, th... |
61,864,365 | 61,876,147 | fscanf returning -1 when trying to return first line of text file | I am trying to simply return the first value from a text file I have called time_temp.txt. The contents of this file are:
1588567745.203
1588567745.203
1588567745.204
1588567745.204
1588567745.204
1588567745.205
1588567745.205
1588567745.205
1588567745.206
1588567745.206
All I am trying to do is return the value of th... | You probably are receiving NULL as result from fopen(3) (does the file actually exist? Have you permissions to write on that file? in the directory?)
Change your code into:
#include <iostream>
using namespace std;
string startTime;
int main()
{
FILE *fTime = fopen("time_temp.txt", "w+");
if (!fTime) {
... |
61,864,380 | 61,864,748 | C++ - non-static void* member pointing to another non-static member of different objects having same address but distinct value | This question title is not clear and a bit broken. I tried to use a void* which is a member to store the address of another member. I accidentally found a weird problem. There were three Object objects created inside a vector<T>. But when I look at the value of those three val_addr, they always point to the same addres... | Any pointers pointing object members are invalidated after the vector extended. The address you see in the object constructor is not valid after a new vector element is placed and the vector is extended. So you saw the address at the moment of an object creation, and when you look at the address of a member inside anot... |
61,864,439 | 61,874,244 | How to detect if a folder is too heavy, and if so delete part of it | i need to control if a folder defined by a path is full of folders, if those folders are too much i need to delete, for example half of them, from the older one the newest one. Practically i need to make space for future folders.
void fCID(long pThreadId)
{
ULARGE_INTEGER rFreeBytesAvailable, rTotalNumberOfBytes, rTo... | If you want to remove the oldest files in a directory structure to reclaim a certain amount of space, you could use the C++17 std::filesystem library class recursive_directory_iterator and the functions
last_write_time and
remove from the same library.
Example:
#include <cstdint>
#include <filesystem>
#include <set>
#... |
61,864,490 | 61,877,236 | What's the difference between asio::io_context and asio::thread_pool? | Whats the difference between an asio::thread_pool and an asio::io_context whose run() function is called from multiple threads? Can I replace my boost::thread_group of threads that call io_context::run() with an asio::thread_pool? Or do I need somewhere an io_context?
Update
When I use asio::thread_pool, do I still nee... | A threadpool implicit runs all the tasks posted on it (until it's stopped).
An io_service doesn't assume anything about the threads that will run it: you need to make sure you do that, and you're free to decide whether you run it on multiple threads, one thread, or even a mix (like one thread at at time, but from multi... |
61,865,007 | 61,865,152 | Runtime Polymorphism - Arrow operator accessing the wrong member? | I have the following classes in my program:
class base {
public:
int bval;
base() {
bval = 1;
}
};
class deri: public base {
int dval;
public:
deri() {
dval = 2;
}
};
And a function f that takes pointer to object of class base and size of array pointed by it:
void f(base *arr, ... | You pass the pointer as a base pointer to f(), so the pointer arithmetic does not fit your deri array.
At this point: for(int i=0; i<size; i++, arr++), only the size of base is added to arr, because arr is a base pointer.
It does not matter in this case what type of objects are really stored; they are not looked at whe... |
61,865,076 | 61,865,178 | C++ template class' inner class access | I have a class like this:
#include <iostream>
template <class T>
class LL
{
using size_t = unsigned int;
class Node
{
T m_data;
Node* m_next;
Node(const T& data) :m_data{ data }, m_next{ nullptr }{}
friend std::ostream& operator<<(std::ostream& out, const Node& node)
... | getSize(ll.head()) fails because of non-deduced context; template parameter T can't be deduced automatically.
If a template parameter is used only in non-deduced contexts and is not explicitly specified, template argument deduction fails.
1) The nested-name-specifier (everything to the left of the scope resolution op... |
61,865,131 | 61,872,683 | Building R package on win32: Unable to load shared object (.dll) | I'm updating an R package that I last released (with no problems) on R3.6. I've since updated to R 4.0.0 and Rtools 40.
The package builds and runs successfully on 64-bit R. But I see that on win builder, the package's testthat tests fail on win32 (but not win64).
To diagnose the failure, I'm building the package on ... | The problem seems to have been the existence of 64-bit dlls in the package's source folder (as insinuated by the error message), created by 'devtools'.
Once these files were deleted load_all would happily re-create them using the 32-bit compilers.
|
61,865,254 | 61,865,397 | I'm curious about c++ istream assignment | I have some question about this code :
#include <iostream>
using namespace std;
int main() {
int i;
int w[10];
cin >> i >> w[i];
cout << i << ' ' << w[i];
return 0;
}
standard inputs are :
3 10
In my PC(Win10 64bit, gcc version : g++ 6.3.0), it occurs segmentation fault.
But other environment(... | You’re running into undefined behaviour before C++17. When executing
int i;
int w[10];
cin >> i >> w[i];
i has not been initialised and reading its value is undefined. The line that reads i and w[i] attempts to read i to find out the location of w[i] before a value is put into i from the input stream due to C++’s ord... |
61,865,441 | 61,865,611 | C++ - Reading int as sequence of letters and digits | int number;
string text;
cin>>number; // Here I read "1234aaaa"
cin>>text;
cout<<number<<" "<<text; // It prints "1234 aaaa"
I understand that the stream stores aaaa from the previous reading and then it passes it to the next reading.
How can I avoid the garbage value from number to be passed to text ?... |
How can I avoid the garbage value from number to be passed to text ?
All depends on what you want exactly
If you want to flush all the rest of the line after the number you can use getline :
std::string s;
std::getline(std::cin, s);
but to save in a string is useless, so you can do also :
std::cin.ignore(std::numeri... |
61,865,629 | 61,867,733 | How do I statically assert that a static_cast is noexcept? | I have a functor to perform static casts from any type to a specific type, defined in this way:
template <typename T_Out>
struct cast_to {
template <typename T_In>
T_Out operator()(T_In&& value) const noexcept {
return static_cast<T_Out>(value);
}
};
Now, I would like to restrict the use of the fun... | It depends on how technically correct you want to go. As you have said, both options achieve the intended goal - prevent compilation. The difference is:
std::is_nothrow_constructible test will always evaluate to either true or false, making your assertion pass or fail.
noexcept test will either evaluate to true, to fa... |
61,865,684 | 61,865,960 | Can GCC optimize code size for functions with the same body? | I'm debugging a C++ program with GDB and faced that different functions turned out to be the same. Here is what I mean by that:
some.hpp
class Base{
virtual bool foo() const;
virtual bool bar() const;
}
some.cpp
bool Base::foo() const {
return false;
}
bool Base::bar() const {
return false;
}
The problem i... | If you wonder how something is compiled it is often very helpful to have a look at the compiler explorer.
Here is your code (with calls to both functions)
https://gcc.godbolt.org/z/g2hfcA
When enabling the compiler flag for "inter-procedural optimization Identical Code Folding" -fipa-icf you allow the compiler to repla... |
61,865,717 | 61,865,996 | How to link SDL2 in CMake? | I'm trying to use sdl on ubuntu. According to this instruction(https://gist.github.com/BoredBored/3187339a99f7786c25075d4d9c80fad5) i installed sdl2, sdl image and sdl mixer. Now I have to link them while building. Example how should I do it below.
g++ myProgram.cpp -o myProgram `sdl2-config --cflags --libs` -lSDL2 -lS... | To link a library (shared/static) in cmake you can use the target_link_libraries command:
target_link_libraries(<target> ... <item>... ...)
According to the documentation:
<target> must have been created by a command such as add_executable() or add_library()
So first of all we need to find the SDL library, for that ... |
61,865,874 | 61,866,000 | Addons: TypeError: addons.function() is not a function | I'm still new into addons and such. I'm trying to run a simple c++ function that prints "Hello MIKE" into node js. However, I get this following error:
TypeError: addons.greetHello is not a function
at Object.<anonymous> (F:\addons\index.js:6:46)
at Module._compile (internal/modules/cjs/loader.js:1147:30)
... | Your current invocation will assign the function to the "Function" export, you probably wanted "greetHello". For your other question, you can pass a name to Napi::Function::New:
exports.Set
(
Napi::String::New(env, "greetHello"),
Napi::Function::New(env, greetHello, "greetHello")
);
|
61,866,124 | 61,870,278 | Convert ICU Unicode string to std::wstring (or wchar_t*) | Is there an icu function to create a std::wstring from an icu UnicodeString ? I have been searching the ICU manual but haven't been able to find one.
(I know i can convert UnicodeString to UTF8 and then convert to platform dependent wchar_t* but i am looking for one function in UnicodeString which can do this conversio... | The C++ standard doesn't dictate any specific encoding for std::wstring. On Windows systems, wchar_t is 16-bit, and on Linux, macOS, and several other platforms, wchar_t is 32-bit. As far as C++'s std::wstring is concerned, it is just an arbitrary sequence of wchar_t in much the same way that std::string is just an arb... |
61,866,191 | 61,866,506 | GDB C++ How to Stop Stepping Inside Standard Libraries | this post briefly discusses the same trouble I am facing. Essentially, is there a default setting or a hack for gdb to stop stepping inside every single glib library and only step inside user files? I know I can call finish each time it steps inside one but it's some wasted keystrokes I'd rather avoid.
It's already an... | If you have GDB 7.12.1 or above you can add the following to your ~/.gdbinit file:
skip -gfi /usr/include/c++/*/*/*
skip -gfi /usr/include/c++/*/*
skip -gfi /usr/include/c++/*
Double check that these are in fact the right places for those libs. This answer comes from here.
Some options without editing gdb init
If you ... |
61,866,281 | 61,866,533 | Why did my array values get updated to random values? | I have a grid with 2 rows and 3 columns. I do an operation where I do not update any element of the grid, rather just access it. Somehow, my grid has been updated with random values
#include <iostream>
using namespace std;
int main(){
int grid[2][3]{{1,3,5},
{2,4,-10}};
int row{sizeof(sizeof(grid)/size... | Your calculation of row is incorrect:
int row{sizeof(sizeof(grid)/sizeof(grid[0]))};
this gives the value of 8 (on my machine, but in general it gives the size of an int). You have an extra sizeof in there. This means you are invoking undefined behavior in your second loop, by indexing out of bounds.
Instead do:
int r... |
61,866,306 | 61,866,402 | Structure is contained in itself. How to understand this? | I am keen on someone else's code and want to understand what is happening here.
What is stored in this structure?
Is this some kind of pattern in C?
typedef struct _P_NEXT P_NEXT;
struct _P_NEXT {P_NEXT *p_el;};
| The structure contains a pointer, not the structure itself. Pointer is essentially an address in memory. The pointer type (P_NEXT, in this case) just tell what is the interpretation of the memory block should be.
This struct looks like a list: a node which points to the next node in list (I guess there is an extra "da... |
61,866,337 | 61,866,591 | Can I draw all objects of the same type at the same time? | I am creating a 2d platformer and have created several objects in different classes.
The code below shows how I currently create objects and draw them to the window.
Is there a way I can draw all of the objects in a class (for example all of the collectible objects), without having to draw each individual object as see... | Assuming all of your objects inherit from sf::Drawable:
// Declare this field in your class
std::vector<sf::Drawable*> m_drawable_objects;
// Fill it in your Game constructor
m_drawable_objects = {
&m_picture, m_character, m_simpEnemy1, ...
};
// Use it in your draw method
for (auto * drawable : drawable_objects)... |
61,866,755 | 61,869,482 | How to swap 128-bit parts between two AVX2 vectors | Problem: I have 4 x 256-bit AVX2 vectors (A, B, C, D) and I need to perform a swaping operation of their respective 128-bit parts and between two different vectors. Here is the transformation I need to do.
Original Transformed
|| Low Lane || High Lane|| || Low Lane || High Lane... | If I understand you correctly, I think you could get away without the blend instructions for this 2x4 transpose, creating new variables that pick the lanes you want. Something like:
__m256i a; // L1 H1
__m256i b; // L2 H2
__m256i c; // L3 H3
__m256i d; // L4 H4
__m256i A = _mm256_permute2x128_si256(a, b, 0... |
61,867,093 | 61,867,162 | Swapping 2 numbers in CPP | This is the code to swap 2 numbers and it works fine. But I'm curious about the "&" in front of x1 and x2 in the swap function. My code couldn't work before I added that two. What does that "&" do?
#include<iostream>
using namespace std;
void swap(int &x1,int &x2){
int x = x1;
x1 = x2;
x2 = x;
}
int main... | In this function:
void swap(int &x1,int &x2)
the & means its a reference to the argument passed in. Changing these variables will change the arguments at the call site.
In this function:
void swap(int x1,int x2)
a copy of the arguments is made. Changing these variables will not change the arguments at the call site.
... |
61,867,302 | 61,872,810 | Problem with ellipse (rotated): incorrect position of any point is detected | When the ellipse is not rotated with this formula 1. If value = 1 - point on the ellipse, if value > 1 - outside, if value < 1 - inside. The program works correctly.
Code:
int checkPointNoAngle(int x0, int y0, int x, int y, int a, int b)
{
int value = (pow((x - x0), 2) / pow(a, 2)) + (pow((y - y0), 2) / pow(b, 2));... | The code was confusing a little bit. I tried to simplify the code corresponding to rotation and inverse rotation. The following code seems to work.
#include <iostream>
#include <vector>
#include <cmath>
struct Pt {int x, y;};
double checkPoint(int x0, int y0, int x, int y, int a, int b, int angle) {
dou... |
61,867,408 | 61,867,841 | Default argument for a class function defined in constructor | Is there a possibility to define a variable that will be used as a default argument in the constructor?
#include <iostream>
class Foo
{
public:
Foo(int x) { num = x;}
void print(int y = num)
{
std::cout << y << std::endl;
}
private:
static int num;
};
int main()
{
Foo f(5);
f.print()... | It's possible, you just have to declare/initialize the static variable outside the class:
Live demo
#include <iostream>
class Foo
{
//..
};
int Foo::num; //<-- or 'int Foo::num = 0;'
int main()
{
//...
}
|
61,867,412 | 61,867,649 | delete original array pointer after copy sets first 3 bytes to 0 | The following program works untill a buffersize of something like 135.
If the buffer gets any larger, the first 3.5 bytes get printed out as 0.
(on a MKR1000 arduino)
uint8_t* bufferOut;
size_t sizeOut;
void SendMessage()
{
fillBuffer();
sendBuffer();
}
void fillBuffer()
{
sizeOut = 12; //just an example
... |
bufferOut = tempBuffer2;
delete[] tempBuffer2;
After these operations, bufferOut is an invalid pointer because the object that it used to point to was destroyed. That in itself doesn't cause any undefined behaviour, but presumably you've simply failed to create a mcve, and the problem is actually caused by you later... |
61,867,635 | 61,869,643 | recursive application of C++20 range adaptor causes a compile time infinite loop | The ranges library in C++20 supports the expression
auto view = r | std::views::drop(n);
to remove the first n elements of a range r with the range adaptor drop.
However if I recursively drop elements from a range, the compiler enters an infinite loop.
Minimal working example: (takes infinite time to compile in GCC ... | Let's take a look at the string case (just because that type is shorter) and manually examine the call stack.
printCombinations(range2) calls printCombinations<string>. The function recursively calls itself with tail. What's the type of tail? That's drop_view<ref_view<string>>. So we call printCombinations<drop_view<re... |
61,868,111 | 61,870,416 | Extracting a C++ code snippet in a sphinx document | I am trying to extract a specific code snippet (a test) from my sources to output it in the documentation.
TEST_CASE("std::vector") {
//! [MyTest]
std::vector<int> v = {42,43};
CHECK( v.size() == 2 );
//! [MyTest]
}
In doxygen, I can refer to it via a \snippet command.
Now, I would like to display the code inside ... | Thanks to @Steve_Piercy I was able to find what I wanted: use the literalinclude directive with start-after and end-before.
TEST_CASE("std::vector") {
//! [MyTest begin]
std::vector<int> v = {42,43};
CHECK( v.size() == 2 );
//! [MyTest end]
}
Documentation file:
You can create a std::vector just like this:
.. lit... |
61,868,142 | 61,871,358 | Return reference and value inside std::tuple | Is it possible to return somehow reference and value inside std::tuple.
Consider something like this:
#include <tuple>
#include <assert.h>
struct A
{
A() = default;
A(const A&) = delete;
A& operator=(const A&) = delete;
int test = 99;
};
A a;
A& get_A() {return a;}
auto return_tuple_with_reference_a... | You can use std::make_tuple and pass a reference_wrapper
For each Ti in Types..., the corresponding type Vi in VTypes... is std::decay<Ti>::type unless application of std::decay results in std::reference_wrapper<X> for some type X, in which case the deduced type is X&.
auto return_tuple_with_reference_and_value()
{
... |
61,868,645 | 61,868,895 | can you guys help me to debug a simple c program with gcc and make it work? (student problems..) | Hello guys so my question is can you help me to debug a simple c program with gcc and make it work?
The teacher gave me this code and I should debug it and make it work, i tried but without any help I can't do It.
I compiled it with g++ -g double_free.c -o double_free
The program crashes.
this is the code:
#include <... | Here's a laundry list of complaints I have about this code:
You delete buf twice. This is really the only item I can see that needs actual debugging. The fact that the name of the exercise is double_free is a dead giveaway to experienced coders that this is the issue.
On top of that:
You should either be a C coder o... |
61,868,712 | 61,868,832 | std::function as key in associative containers | Is my understanding right that one can not use std::function as a key with neither the ordered, i.e. std::map, std::set, nor unordered associative containers, i.e. std::unordered_map, std::unordered_set?
Background is that I implement a timer driven observer, i.e. in this case the subject. I give the observers a std::f... |
Background is that I implement a timer driven observer, i.e. in this case the subject. I give the observers a std::function object in order to unsubscribe again.
Don't do that.
Instead, return an iterator to the container where you stored the function object that the subscriber can use to unsubscribe.
I should be a... |
61,868,752 | 61,869,327 | Number the nearest to the average C++ | does anybody knows what is wrong with 'else' gap and the script inside to show which number is the nearest to the average? I tried to fix it, however there was no better result. (It indicates the number, but wrongly)
#include <iostream>
#include <math.h>
using namespace std;
float average (float *a, int lib)
{
... | the problem with your code is that you increment the i two times
first int the for lop itself
and the second time after the if else statment
you for loop need to look like that:
for (int i=0;i<ile;i++)
{
if ((fabs(a-b))<=(fabs(a-number[i]))) {
b=b;
}
else if ((fabs(a-b))>(fabs(a-number[i]))) {
... |
61,869,029 | 61,869,204 | C++ - Unable to inherit from base class | Gives empty values | I guess I am doing something wrong here in the below code. I want to inherit the methods of class Person in class Employee.
#include<bits/stdc++.h>
using namespace std;
class Person{
private:
string name;
int age;
public:
Person(string name, int age){ //Base parameterized constructor
... | The issue is not with inheritance, but with the fact that Person never initializes any of its fields.
This code:
Person(string name, int age){ //Base parameterized constructor
name = name;
age = age;
}
assigns local variable name to itself and same with age, because parameters shadow cl... |
61,869,112 | 61,875,115 | Travelling Salesman problem in dynamic programming | i am trying to resolve the travelling salesman problem with dynamic programming in c++ and i find a way using a mask of bits, i got the min weight, but i dont know how to get the path that use, it would be very helpful if someone find a way. This is my code:
#include<iostream>
using namespace std;
#define INT_MAX 9999... | Let's introduce a new path function that gives the entire optimal path using the previously calculated dp array.
void path(int mask,int pos){
if(mask==VISITED_ALL) return;
int ans = INT_MAX, chosenCity;
for(int city=0;city<n;city++){
if((mask&(1<<city))==0){
int newAns = dist[pos][ci... |
61,869,223 | 61,870,365 | Implementing 3 way partitioning for quick sort | I am trying to implement 3-Way partitioning for quick sort.
I tested with a lot of custom test cases but if works fine, but it fails for some unknown cases. I am unable to figure out where am I going.
Here's the code.
Partitioning:
int* partition3(vector<long long int> &a, int l, int r) {
int* m = new int[2];
lon... | The easiest way to implement three-way partition that is provably correct is to use the method of loop invariants. For simplicity and genericity let's work with iterators. Consider the following invariants:
In the range
[first, i) all elements are less than pivot
[i, j) all elements are equal to pivot
[j, k... |
61,869,347 | 68,318,696 | Control Windows 10's "Power Mode" programmatically | Background
Hi. I have an SB2 (Surface Book 2), and I'm one of the unlucky users who are facing the infamous 0.4GHz throttling problem that is plaguing many of the SB2 machines. The problem is that the SB2 suddenly, and very frequently depending on the ambient temperature, throttles heavily from a boost of 4GHz to 0.4GH... | OK... I've been wanting command line or programmatic access to adjust the power slider for a while, and I've run across this post multiple times when looking into it. I'm surprised no one else has bothered to figure it out. I worked it out myself today, motivated by the fact that Windows 11 appears to have removed t... |
61,869,567 | 61,871,000 | C++: cannot see output in VS Code while debugging | Today I'm trying to switch from VS2019 to VS Code while keep working with MSVC. This way I will develop in a lightweight and easier environment most of the time, and when I need advanced stuff such as seeing hot paths, I would be able to open VS2019 and do the job. Below is my launch.json configuration
"name": "debug",... | You are probably looking at the wrong tab. There should be the tabs "Problems", "Output", "Debug Console" and "Terminal". Why you hit F5 you are in "Terminal". That's the shell where your launch task get's executed. Your program output from std::cout however goes into "Debug Output".
|
61,869,590 | 61,870,253 | Operator Overloading not extracting overrided value from file | So, I have hit quite a pickle. I'm trying to create 2 overloaded functions, one that inputs into a file using an insertion operator, and the other extracts the value from the file using an extraction operator.
Code Sample 1: Shows the class members.
class OUSB
{
private:
unsigned short PORTB;
publi... | You store the value you read in a new object that you immmediately throw away, and you don't modify the argument.
You should let *this do the reading and writing, and you need to store the value in the argument when you read:
void OUSB::operator<<(const unsigned short& val)
{
writePORTB(val);
}
void OUSB::oper... |
61,869,689 | 61,874,206 | no matching function for call to 'connect'(QT) | I am new to write QT code. I write a simple http client code (The Qt version is 5.9). I define a class that named my_http_client, it derived Qobject, and I using QNetworkAccessManager class to create http connection. I create 3 files, one is main.cpp, another two is my_http_client.h and my_http_client.cpp. The my_http_... | Try adding #include <QNetworkReply> in my_http_client.h, it resolved the issue for me.
Also, I would suggest replacing std logging with qDebug() and qCritical() from #include <QDebug> (debugging in Qt)
|
61,869,980 | 61,870,261 | c++ classes: different ways to write a function | what's the difference between the following 3 cases:
1) in point.h:
class point
{
int x,y;
public:
int getX();
};
int point::getX() {
return this->x;
}
2) in point.h:
class point
{
int x,y;
public:
int getX()
{
return this->x;
}
};
3) in point.h:
class point
{
int x,y;... | Avoid this first one:
struct point
{
int x,y;
int getX();
};
int point::getX() {
return this->x;
}
If multiple source files include point.h, you will get multiple definitions of point::getX, leading to a violation of the One Definition Rule (and modern linkers will give an error message).
For the second o... |
61,870,157 | 61,946,097 | Error compiling Unreal Engine 4.25 on ubuntu focal | I have been following the linux setup guide for UE4.
Everything worked out fine until the call to make (Last step of "3 - Building UE4 on Linux").
The output for the build is the following:
Performing 37 actions (10 in parallel)
[4/37] Compile Module.TraceLog.cpp
[1/37] Compile PCH.Core.h
[6/37] Compile Module.UnrealHe... | The issue is due to a bug in the FPaths::MakePathRelativeTo implementation.
It is looking at the second character in the root folder (to see if it is a ':') but my disk is mounted under a single letter path.
This can be fixed by re-mounting the disk in a folder with 2 or more characters.
Also, depending on your locale,... |
61,870,280 | 72,513,585 | Does NRVO also apply to coroutines? | In the following example, NRVO (Named Return Value Optimization) applies as per this article:
std::string f1()
{
std::string str;
return str; // NVRO applies here!
}
However, consider:
task<std::string> f2()
{
std::string str;
co_return str; // Does NVRO also apply here?
}
| NRVO as defined by the article you linked (i.e. not even creating a temporary) isn't a thing for coroutines because how co_return works is up to the user-provided coroutine promise type: the expression in the co_return statement is fed to the promise's return_value method, which can decide what to do with it.
However t... |
61,870,422 | 62,010,943 | Octree with 3d array like interface | I want to use octree to save space, because I have a bunch of 3d arrays with a lot of same data (voxel chunks where blocks just uint16). I've seen implementations of octrees for ray traversal or space partitioning but all of them contain octree center and node size, I do not need any of that, I want only compressed dat... | I made what i wanted, size can be computed from amount of splits.
https://github.com/markusgod/cubic-octree
|
61,870,562 | 61,870,720 | Program doesn't perform as expected but no compilation error | I have the following code:
`#include<iostream>
using namespace std;
struct book
{
int id;
char name[50];
int price;
};
int main()
{
book b1;
book input();
b1=input();
void display(book );
display( b1);
return 0;
}
book input()
{
book b;
cout<<"Enter the following details:";
cout<<"Book Id: ";
cin>>b.id;
cout<<"Book Nam... | Quoting from the answer in this question:
getline() does not work if used after some inputs
When cin.getline() reads from the input, there is a newline character left in the input stream, so it doesn't read your c-string. Use cin.ignore() beore calling getline().
|
61,870,828 | 61,871,073 | Accessing enum members from class | So consider this struct:
struct CType
{
enum DType
{
Int,
Char
} Type;
union Value
{
int num;
char alpha;
Value() {
this->num = 0;
this->alpha = '\0';
};
~Value() {};
} value;
};
How can I do this?
CType u3;
u3.Ty... | DType is an Unscoped Enumeration that is visible in its enclosing scope:
Unscoped Enumeration (emphasis mine) - pre-C++11:
Each enumerator becomes a named constant of the enumeration's type (that is, name), visible in the enclosing scope, and can be used whenever constants are required.
You're looking for Scoped Enum... |
61,870,983 | 61,871,653 | What exactly is this called? Ex. MyClassObject.Myfunction().x | I've seen this in UE4 C++ code and in SFML C++ code and I can't seem to find out what this is exactly. I've searched google and found nothing that seems relevant to what I'm looking for.
Ex. #1 MyClassObject.Myfunction().y
Ex. #2 instantiatedObject.getPosition().x
Ex. #3 if (spriteBee.getPosition().x < -100)
It's the .... | You can do the same thing yourself:
class MyVector2 {
public:
int x;
int y;
};
int main() {
MyVector2 myVec {5, 10};
std::cout << "x from myVec:" << myVec.x << "\n"
<< "y from myVec:" << myVec.y << "\n"
}
If you want to use functions as well, that's also possible:
class MyVector2 {
publi... |
61,871,043 | 61,871,083 | C++ defining same function twice causes error | I'm too much confused why it's an error to write the same function in two different cpp files?
what if both want to use that function? and why this should ever cause an error, the function is written in to separate files...
a.cpp:
#include "test.h"
b.cpp:
#include "test.h"
test.h
int getMin(int x,int y)
{
return ... | If you define a function twice, the linker will see 2 definitions of the same function, which is not allowed. (even though each .cpp that includes this header file sees only one definition, which is why adding header guards doesn't help here).
One option is to only write the declaration of the function in the .h file,... |
61,871,065 | 61,871,162 | Explicity clearing the source resource after std::move | Encountered this little piece of code in the wild:
class JetPlane
{
private:
int engines;
Seating *seating;
string manufacturer;
public:
JetPlane(JetPlane&& jetPlane)
:engines(jetPlane.engines),seating(jetPlane.seating),manufacturer(std::move(jetPlane.manufacturer))
{
jetPlane.seating = nullptr;
jet... | It really depends on the type of manufacturer. The standard guarantees that objects of standard library types after moved are left in an unspecified, but valid state. The exact type might need clear to be called to be reusable again. In theory, the moved from object could contain any garbage, as long as it is a valid s... |
61,871,193 | 61,871,378 | Designing class for handling multiple communication protocols handling | I am developing a C++ application which should handle multiple communication protocols (Ethernet, Serial, etc.). Each of the communication protocols is handled as a specific class.
In order to expose as little as possible information about the internal structure and organization of the said classes and protocols, I wou... |
What is the best way to create a generic API for the said
functionality, and if possible involve some design pattern?
The Strategy Pattern looks suitable in this scenario.
First, define an interface for all your distinct communication startegies, Communication:
class Communication {
public:
virtual ~Communicati... |
61,871,310 | 61,871,395 | How are constructors with default parameters called in inheritance hierarchy? | I have this simple code:
class C0
{
public:
C0(std::string i) : i_(i) {}
private:
std::string i_;
};
class C1 : public virtual C0
{
public:
constexpr static auto const e{"e"};
C1(std::string i = e) : C0(i) {}
};
class C2 : publi... | The most derived class is the one that is responsible for constructing the virtual bases. To fix this, add : C0(k) to C2.
|
61,871,695 | 61,872,155 | How to find the exact substring with regex in c++11? | I am trying to find substrings that are not surrounded by other a-zA-Z0-9 symbols.
For example: I want to find substring hello, so it won't match hello1 or hellow but will match Hello and heLLo!@#$%.
And I have such sample below.
std::string s = "1mySymbol1, /_mySymbol_ mysymbol";
const std::string sub = "mysym... | The regex [^a-zA-Z0-9]* will match 0 or more characters, so it's perfectly valid for [^a-zA-Z0-9]*mysymbol[^a-zA-Z0-9]* to match mysymbol in 1mySymbol1 (allowing for case insensitivity). As you saw, this is fixed when you use [^a-zA-Z0-9]+ (matching 1 or more characters) instead.
With your update, you see that this doe... |
61,871,719 | 61,872,984 | FFMPEG C++ Volume Filter | I seem to be having a bit of trouble using FFMPEG audio filters in C++ code. If I only have "abuffer" and "abuffersink" filters, and grab the audio frame from the filtergraph, it sounds perfect. Once I add another filter into the graph (in this case, it's a "volume" filter), there is a lot of noise introduced. I can't ... | I figured this out. It was defaulting to "float" precision, so I had to add the following if the format was fixed:
snprintf(args, sizeof(args),
"volume=%f:precision=fixed",
1.0f);
_volumeFilter = avfilter_get_by_name("volume");
ret = avfilter_graph_create_filter(&_volumeFilterCtx, _volumeFilter, "volume", args,... |
61,871,927 | 61,872,446 | Run a function with a delay in QT | I want to create a function, let's say (qDebug() << "result" ;). I want to display the result 2 secs later, the delay must be in this function implemented. In other words :
void MainWindow::my_function()
{
// Here I need something to make a delay of 2 secs
qDebug() << "result";
}
Is there a method or someth... | my suggestion is to read first why sleep are a bad idea, specially when GUIS are involved..
anyways, you can since qt5
Functions of QThread
void msleep(unsigned long msecs);
void sleep(unsigned long secs);
void usleep(unsigned long usecs);
using this in your code, you can do
void MainWindow::my_function(){
// He... |
61,872,374 | 61,872,727 | Compiling c++ from command line using nmake or another tool like batch script | I have multiple c++ files in a directory, but at a moment, I need to compile only one of them. I am using Windows 10 with mingw-w64.
Currently I am individually writing command like g++ abc.cpp -o abc plus some flags, but I need to automate this, for example, writing only some command like compile abc.cpp.
I am looking... | The best, simplest method for this is to use a Makefile. I believe mingw has make capabilities.
All you have to do is simply create a file called "Makefile" with no extensions.
In the Makefile add the following lines
CXX = g++
CXXFLAGS = PUT YOUR FLAGS HERE
abc: abc.cpp
$(CXX) $(CXXFLAGS) -o abc
Then when you wan... |
61,872,389 | 61,872,476 | Accessing Private Members of a class outside the class | I have defined two classes as follows:-
class DayStat
{
private:
double cases, deaths;
public:
DayStat();
DayStat(int _cases, int _deaths);
DayStat(const DayStat &d, double denominator);
double mortalityRate() const;
double getcases() const;
double getdeaths() const;
};
class Region
{
priv... | Like this
raw[10] = DayStat(20, 30);
|
61,872,432 | 61,872,932 | Default parameter and function pointer as function arguments C++ | I have a function which takes arguments, default arguments and finally, a pointer to another function and a void pointer.
As an example, consider the following
int foo(double arg 1, bool arg 2, int arg3=0, int arg4=2, bool (*pbar)(bool,void*), void* data=0);
It is called in several places across my codebase. I have ... | The fundamental principle behind default arguments is that they apply to the right-most arguments in the argument list.
void f(int, double = 0, void* = 0); // okay
void g(int, double = 0, void*); // error: third argument needs a default value
Similarly, when calling a function with default arguments, only the rightmos... |
61,872,537 | 61,957,205 | Complex push button with several icons and text | I need to create a button which may contain two icons and two text label to display (on screenshots - every line such as "Email" or "Connection" is a standalone button).
From what I understood - I can't override QPushButton or QAbstractButton and I have to implement my own custom widget in order to achieve such layo... | Ended up using custom widget with QStackedLayout and transparent button above all other layers, I think it is the best approach.
I created necessary labels on "low" layers of the layout and just added a button above them all with background:transparent; property in style sheets.
Also StackingMode should be set to Stack... |
61,872,816 | 61,876,925 | Eigen get array of indexes where values in vector are true (no unnecessary for loops) | I have the vector
Eigen::VectorXf test(4);
test << 1.231, 1.23, 0.41, 1.233;
I'm trying to get the indexes of where test.array() > 1. I would expect the result to be in array form (std::vector is fine) and I want to take advantage of eigens optimisations (i.e. no unnecessary for loops). The result should be {0, 1, 3}... | Based off this answer Eigen Indices of Dense Matrix meeting Condition, I got the result using visitors. This time I'm checking if the values are NaN rather then greater than 1.
template<typename Func>
struct lambda_as_visitor_wrapper : Func {
lambda_as_visitor_wrapper(const Func& f) : Func(f) {}
template<typena... |
61,872,863 | 61,873,795 | Table of constants in C++ | I'm working on a project with a software that uses C++ compiler (VisualStudio 2010 C++). The software is for making numerical model for real electric circuits. I write some codes in different sections in the software, ir's a C++ code but some variables must have some prefixes (SeqInteger instead of Integer, ptVar if Va... | If you want to declare an array, and later assign to it using an initializer list, you could do:
int i = 0;
for (int v : {1 , 2, 1 , 3})
A[i++] = v;
|
61,872,975 | 61,873,071 | How do I template a class using an instance of another templated class? | I have a gpio class which is templated:
template <gpio_types::port_t PORT, uint32_t PIN>
class gpio {};
I want create a class that takes a gpio instance as a template. The problem is in the line below.
template <uart_types::flexcomm PERIPH, int RX_BUF_LEN, gpio<gpio_types::port_t PORT, uint32_t PIN> TX_PIN>
class uart... | This
gpio<gpio_types::P1, 13> tx;
declares tx to be an object of type <gpio<gpio_types::P1, 13>>. gpio<gpio_types::P1, 13> is not a tempalte, it is a concrete type. If you want to pass that type as parameter to the uart_shared_n_block then, that would be:
template <uart_types::flexcomm PERIPH, int RX_BUF_LEN,
... |
61,873,332 | 61,873,854 | Function to check if two graphs are complements | I'm trying to write a function which will take two graphs as parameters and return true if they are complement, otherwise false. I figured graphs are complement if inverse of one matches the other that's the approach I tried using. I built my function on a class and for some reason, it just doesn't let me call it from ... | Since is_complement is a member function of class Graph, you need to call it using dot operator from object g.
cout<< g.is_complement(g,g1) << "\n"; should work.
|
61,874,070 | 61,874,146 | passing template (without a specification) to an std::thread() gives error : <unresolved overloaded function type> matching Error | So, my task is to pass both vectors char & int in the template with two threads.
Why it cannot thread to reading the two containers ? Some push will be helpful.
#include <iostream>
#include <thread>
#include <vector>
template<typename T>
void check(std::vector<T> values){
for(T& it : values){
std::cout... | check is not the name of a function, it is the name of a template. std::thread needs a function object so just using check won't work.
You can use check<int> to specify the int specialization of the check template be used, or you could use a lambda and let the compiler figure it out like
std::thread th1([](const auto ... |
61,874,115 | 61,874,326 | different types in operator ? with no-capture, same signature, lambda | According to the c++ standard, a lambda function has a unique type, hence in general two lambdas cannot be used in conjunction with the ? operator. However, as discussed in this question, a lambda with no capture can be converted to a function pointer. Hence, the following code correctly compiles:
int main()
{
bool... | You have to explicitly specify type of at least one expression in ternary operator.
This should work:
int main()
{
bool x = true;
auto a_lambda = x ? static_cast<void (*)(int)>([](auto p) { }) : [](auto p) { };
}
or simply
int main()
{
bool x = true;
auto a_lambda = x ? [](int p) { } : [](auto p) { };
... |
61,874,421 | 61,874,672 | Cannot open source file "ui_QtGuiApplication.h" in default Qt project | I installed the latest QT version and the QT tool for Visual Studio. When creating a new GUI project in Qt, the default program should create an empty window, but it seems that I'm getting an E1696 error in Visual Studio Community: "cannot open source file "ui_QtGuiApplication4.h".
The error takes place in the default ... | The ui_<YourClass>.h header file is a file that only gets generated for you when you compile your project. Qt's User Interface Compiler uic will read your .ui file(s) and create the corresponding ui_ headers before the actual C++ compiler is invoked.
So you have to give it at least one compile run to generate the file.... |
61,874,422 | 61,875,209 | Unable to delete EXE after it crashes even though process not shown in Task Manager | I have a program that I have written that crashes and I'm in the process of debugging it.
However, the issue is that when I attempt to create a new build, very frequently (but not always!) I get the message:
Cannot open file 'TheExecutable.exe'
I am then unable to delete, rename, move, or in any way modify the executa... | Your process is not being terminated all the way. Since it is not list in the task manager, you can use PSKILL to end it manually.
Open power shell or the console in administrator mode and run
pskill name_of_executable
and it should terminate it so you can re-run it.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.