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,791,312 | 63,791,796 | How do you suppress all 3rd party compile time warnings in MSVC | I'm working on a C++ project that uses OpenCV and Boost. Unfortunately when compiling, my compiler gives me hundreds of warnings from the include files of those libraries. Even with an empty main function and no other code I still get these warnings from the include statements. I've heard this is a problem with other 3... | All this is from this blog post: https://devblogs.microsoft.com/cppblog/broken-warnings-theory/.
The general tone of the introduction of the article speaks volumes about why this option wasn't there to begin with (and none of it makes much sense to me).
Basically this says you can use /external:I as a synonym to -isyst... |
63,791,447 | 63,791,516 | Why is operator< overloading necessary for STL set containing custom objects, instead of operator== | I'm working with C++11 and I want to use set to store my custom objects because I need a container, which can filter the elements with the same value.
Here is the class of my custom object:
struct Ele
{
int a, b, c;
}
As my understanding, I need to overload the function operator== because set need to filter the el... | == is not sufficient on its own to define an ordering, whereas < is. Furthermore all other relational operators can be cast in terms of operator<, so long as you are allowed to negate the result.
For example, a == b if !(a < b) and !(b < a)
< is a natural choice insofar that thinking of things being in ascending order ... |
63,791,578 | 63,791,688 | std::bind is on stack? | I want to pass c++ objcet member callback func to an "c" lib, which just have void*. Then I use std::function to register the callback handler. But there is a problem when I cast std::function<>* to void*, seems the std::function<>* is destroyed when cast to void*.
Below is the test code.
#include <iostream>
#include <... | std::bind is a function. It's not on the stack or the heap.
Its return value is a temporary object, and has the usual lifetime of temporaries. That's not the problem here; the bind return value is stored in the std::function passed to register.
In register, again the normal C++ rules are followed. std::function<void(in... |
63,792,223 | 63,792,278 | How to add an remove std::functions from a std::vector | I have a simple C++ program below which registers some callbacks/listeners which are just std::functions. And then it removes the callbacks.
Code:
#include <iostream>
#include <functional>
#include <vector>
#include <memory>
class SomeClass {
public:
typedef std::function<void(int)> ListenerType;
std::vector<L... | You can't compare std::functions (except with nullptr), so that approach is never going to work (find cannot locate the function you're looking for).
Instead, wrap the std::function into some class that also has a unique ID for each one, then compare that instead (using a custom comparator for find).
Alternatively, and... |
63,792,255 | 63,792,679 | How to include different number of objects at compile time in the initializer list? | I need to include a different number of objects depending on the provided 'define'
and with different ctor parameters
inline static std::array<A::Output, NUM_OUTPUTS> s_Outputs =
{
#if NUM_OUTPUTS > 0
A::Output{0}
#endif
#if NUM_OUTPUTS > 1
, A::Output{1}
#endif
#if NUM_OUTPUTS > 2
, A::Output{2}
#endif
};
... | Using std::make_index_sequence and a variable template you can do.
#include <utility> // std::integer_sequence
template <std::size_t... I>
constexpr auto makeArray(std::index_sequence<I...>)
{
return std::array<A::Output, sizeof...(I)>{I...};
}
template<std::size_t NUM_OUTPUTS>
constexpr static std::array<A::Outpu... |
63,792,322 | 63,792,499 | C++ how to define the operator [] to write and read an item of the circular buffer | I have created a template class that implement a circular buffer. The buffer is formed of items that have a value of type T.
I want to define the operator[ ] to write and read an element of the buffer. Even when I try to read an element already inizialized the result is: Segmentation fault: 11
This is the code for oper... | I'm guessing somewhat, because you haven't provided enough context (it's difficult to see if a small part of a class is correct without seeing the rest of the class). But it seems that _buffer is a linked list. The next pointer in the item struct gives it away
typedef struct item {
T value;
item *next;
};
But ... |
63,792,526 | 63,792,609 | Change deletion order to delete pointer before variable | I have a class with a plain variable, _apple, a pointer to a second variable, _orange, and a destructor that cleans up _orange.
Even though _orange is defined before _apple in my class, it is cleaned up as part of the explicitly defined destructor, and is thus deleted before apple, in contrast to the usual "LIFO" delet... | You change the deletion order by changing who manages the resource (= allocated memory). If you need pointer semantics, std::unique_ptr is a good candidate for this:
struct Meal
{
std::unique_ptr<Food> _orange;
Food _apple;
Meal() : _orange(std::make_unique<Food>("orange")), _apple("apple") {}
};
|
63,792,534 | 63,803,896 | Protobuf type and variant array types | I was looking at proto3 documentation and it is not clear to me if I can create an rule for my use case. The equivalent in c++ will be to have the following declaration:
using Variant = std::variant<bool, int32_t, uint32_t, int64_t, uint64_t, float, double>;
using Data = std::vector<std::vector<Variant>>;
Is it pos... | You cannot have a repeated repeated Any. Try the following code:
message SubData {
repeated google.protobuf.Any element = 1;
}
message Data {
repeated SubData sub_data = 1;
}
|
63,793,242 | 63,795,338 | Converting PCM-ALAW data to an audio file using ffmpeg | In my project, I processed the received RTP packets with the payload, and extracted all the payload to a separate buffer. This payload is - PCM ALAW (Type 8). How do I implement a class that will take as arguments - the file name and a buffer with raw data to create an audio file. Exactly what steps do I have to go thr... | That sounds way too complex. "PCM ALAW" is a bit misleading, but it's pretty clear that G.711 aLaw encoding is meant. That's a trivial "compression" which maps each 16 bits PCM sample to an 8 bits value. So a trivial lookup fixes that.
There's even a Free implementation of the aLaw encoding available. Just convert each... |
63,793,368 | 63,801,645 | Reason for boost::extension.hpp does not defining hash_value() for unordered and some other containers | From the boost documentation:
It also implements the extension proposed by Peter Dimov in issue 6.18 of the Library Extension Technical Report Issues List (page 63), this adds support for:
...
**the standard containers**
...
However, when looking at the implementation (boost version 1.71) in extension.hpp I can see... | Unordered containers will largely have irrelevant, non-repeatable hashes.
This is because hash(a,b,c) is not the same as hash(b,a,c) or hash(c, a, b) etc.
Since the ordering cannot be depended and only implicitly controlled, you will never know what it means to have "identical hash". The main rule of hashes for lookup ... |
63,793,433 | 63,795,136 | Best practices: extra methods in c++ | So, I'm doing a project where I have a class named Window, and the goal of the class is storing the state of the window (whether the window is open or closed) and having a method Toggle, which toggles the window.
class Window {
public:
explicit Window(bool is_open);
Window(const Window&) = default;
Window& oper... | You have run into "You Aren't Gonna Need It" (YAGNI).
If you need those features later, you can build them later at about the same cost as building them now. But if you build them now, you might not need them later, in which case that effort will be wasted. (Not to mention the cost of maintaining that extra code.)
Ther... |
63,794,342 | 63,794,468 | Calculating an array's number of elements... Able to refer to its index values by just stating the return type? What? How? Why? (C++) | I am learning how to calculate the size and number of elements in an array and came across a question. In a tutorial I see
we can calculate the number of elements in an array as follows ...
int array_variable [] = {1, 5, 8, 10};
int array_variable_number_of_elements = sizeof(array_variable) / sizeof (int);
I am aware... | Second approach is better and more generic, when you need to change the type of array int to char, you don't have to edit second line at all.
char array_variable [] = {'a', 'b', 'c' }; //changed this line only
int array_variable_number_of_elements = sizeof(array_variable) / sizeof
(array_variable[0]);
To a... |
63,794,805 | 63,798,180 | Simply way of getting all open named pipes | Is there a simpel way to get all open named pipes in c++, like there is in c#?
String[] listOfPipes = System.IO.Directory.GetFiles(@"\\.\pipe\");
I found this article where differen methodes where proposed to get all open named pipes, unfortunately nothing for c++ c0x.
| Much of .NET's source code is openly available on https://referencesource.microsoft.com.
If you look at the source code for the System.IO.Directory class, its GetFiles() method creates a TList<String> using an IEnumerable<String> from FileSystemEnumerableFactory.CreateFileNameIterator(), and then converts that TList<St... |
63,795,354 | 63,813,113 | Is there a way to make a constructor accept two possible types of parameters? | I have a class MyClass that looks like this currently:
class MyClass{
public:
MyClass(std::initializer_list<std::initializer_list<float>> arg){
// some code here
}
MyClass(vector<vector<float>> arg){
// identical code as above block
}
// other class me... | My solution:
#include <iostream>
#include <vector>
class MyClass
{
public:
using Vec_vec = std::vector<std::vector<float>>;
MyClass(Vec_vec arg) : vv{std::move(arg)}
{
for (const auto& ilist : vv)
{
for (const auto& x : ilist)
{
s += x;
... |
63,795,395 | 63,982,028 | C++20 "transparently replaceable" relation | In the final working draft of C++20 (and the newest publicly available draft linked below), the wording of [basic.life] has been changed regarding how objects are allowed to replace other objects, so that pointers, references and the object's name automatically refer to the new object. For this purpose the relation "tr... | [intro.object]p2 applies regardless of whether [basic.life]p8 applies, so o1 and o2 are direct subobjects of the same object. You can easily check that an object is always transparently replaceable by itself, so p1 transparently replaces p2, so o1 transparently replaces o2.
This is in line with the intent, which was to... |
63,795,397 | 63,795,721 | How can I make my c++ program to countinue? | I wrote this to find out which 10-digit numbers are prime but it stops after showing about 20 numbers at all. Would you help me figure out what's wrong? Or suggesting any other sources? It's important to me as it's my school project.
#include <iostream>
#include <string>
#include <windows.h>
using namespace std;
void t... | When n1 is 9999999983 it gets stuck inside the while loop until n2 is less or equal to 1
You should look for a more efficient way
while (n2 > 1)
{
n3 = n1 % n2;
if (n3 == 0)
{
std::cout << n1 << " not prime\n\n";
n1--;
temp();
}
else
... |
63,795,481 | 63,936,057 | FLite won't load voice from file/festvox repository | I'm still in troubles with FLite TTS. After building it into my project (c++ on Ubuntu 16.04) I can't load any voice to perform the TTS conversion. I've tried three ways to initialize the needed voice with no luck.
At first I tried "register_cmu_us_kal" from docs example but it comes with many building errors and won't... | Contrary to the nonsense by ALX23z here is a solution (maybe actually reading documentation and try to implement a solution would have been more helpfull instead):
extern "C" {
cst_voice *register_cmu_us_rms(const char *voxdir);
void unregister_cmu_us_rms(cst_voice *v);
void usenglish_init(cst_voice *v);
cst_lexicon *c... |
63,795,520 | 63,980,131 | How to implement nested loops with the depth of n? | The following code shows what I want to achieve. How can I generalize this principle for any value of n to generate nested loops of the same depth? Or is there a better solution?
For n = 2:
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
}
}
For n = 3:
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
for(k=0;k<... | The way that i answered this question is; suppose we want n nested loops that is supposed to run from 1 to 10, this is how it would look
void nLoop(int n)
{
if(n<=0)
return;
for(int i=1;i<=10;i++)
{
nLoop(n-1);
}
}
|
63,796,449 | 63,796,781 | Arduino C++: Create object from foreign class | I have an LCD display attached to my Arduino Mega 2560 using the following code:
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C myLCD(0x27, 20, 4);
void setup() {
myLCD.begin();
myLCD.backlight();
}
void loop() {
myLCD.clear();
myLCD.print("Hello");
delay(2000);
}
This works fine and the display shows "Hello"... | Inside begin() method you define a local variable with the same name as your class field
LiquidCrystal_I2C myLCD(lcd_address, columns, rows);
At the end of the begin() method this object is destroyed. myLCD object in the write() method has nothing to do with the local object myLCD in begin()
In the constructor Lcd() m... |
63,796,525 | 63,799,799 | Curl replacing \u in response to \\u in c++ | I am sending a request using libcurl in windows and the response I get has some universal characters in them that start with \u. Libcurl is not recognizing this universal character and as a result, it escapes the \ turning the universal character to \\u.
Is there any way to fix this? I have tried using str.replace but ... | Your analysis is wrong. Libcurl is not escaping anything. Load the URL in a web browser of your choosing and look at the raw data that is actually being sent. For example, this is what I see in Firefox:
The server really is sending Mu\u1e25arram, not Muḥarram like you are expecting. And this is perfectly fine, bec... |
63,796,551 | 63,800,062 | How to keep the windows aspect ratio while resizing the window in SFML 2.5? | I want to know if there is a way to keep the windows aspect ratio while resizing the window like when you scale a layer and pressing shift in photoshop.
| I finally manage to do what I wanted to do. I listen to sf::Event::Resized and calling sf::Window::setSize then I adapted the code from this post which look like that :
// set screen size
float screenWidth = 800.f;
float screenHeight = 600.f;
// get the resized size
sf::Vector2u size = _window.getSize();
// setup my wa... |
63,796,938 | 63,813,442 | Can’t compile WebView2 project. Need own Callback class template | I am using Visual Studio 2015, version 14.0.23107.0. Project’s target platform is 10.0.17763.0.
I have read this article, and did first steps. I downloaded webview2 solution from GitHub and opened it in Visual Studio. Then, via git NuGet I successfully added Windows Implementation Library package (version 1.0.200902.2)... | Seems hard nights do their work.
I included only WRL:
#include <wrl.h>
And then used:
Microsoft::WRL::Callback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler>(...
For each appearance and it compiled.
But it again was a blank window
This answer helped me, and now I finally got working solution I need.
|
63,797,119 | 63,797,219 | Does std::bitset<64> work on 32 bit machines for uint64_t? | The output of code below on a 32 bit Linux (RHEL6) machine with Intel compiler with enabled -std=c++11 is like below - why?
uint64_t a = UINT64_MAX;
std::cout << std::bitset<64>(a) << std::endl;
Output on 32 bit machine:
0000000000000000000000000000000011111111111111111111111111111111
Output on 64 bit machine:
111111... |
Does std::bitset<64> work on 32 bit machines for uint64_t?
Yes, since C++11.
Prior to C++11, the constructor accepted a unsigned long which is only guaranteed to be 32 bits or larger. When the size of the bitset exceeds the number of bits in long (prior to C++11) or long long (since C++11), the overflowing bits are i... |
63,797,185 | 63,800,017 | The first DFS path using a itertaive DFS rather than a recursive one | I am trying to implement a simple Dfs path finding for a problem in which I have to print the very first path I encountered and nothing if no path is found.
I was able to do it with Recursion but i am having trouble with the iterative version.
here is my code :
#include <iostream>
#include <stack>
#include <map>
using ... | Basically, you get a code that solves your testcase example, by removing the following code lines from your inner for loop:
if( !parentMap.count(i) )
and
visited[i] = 1;
In your code, the parentMap registers the first occurrence of a path from the currently processed element to its children. In order to mimic the rec... |
63,797,216 | 63,798,429 | How to seamless build with CMake? | When I clone a project with a configure or even a Makefile I know that I can do ./configure && make or just simply make all && sudo make install. But everytime I have a CMakelists.txt it makes my journey harder...
Usually I have to start by creating a new directory, then go into this directory, then launch cmake with a... | Firstly, don't call the build system directly. Instead, use it through cmake so that it will work regardless of which build system was configured:
# not this
#make
# do this
cmake --build .
I forgot perhaps -G or -g.. Then Makefiles or LinuxMakefiles or maybe Linux Makefile
If you compile on Linux, then Unix Makefil... |
63,797,259 | 63,797,441 | Unable to initialize vector from initializer list in delegating constructor | I have a class MyClass as follows:
class MyClass {
public:
MyClass(vector<vector<float>> arg) {
// some code here
}
MyClass(std::initializer_list<std::initializer_list<float>> arg)
: MyClass(vector<vector<float>>(arg)) {
}
// other class members
};
I'm trying to use a delegating cons... | The initializer_list constructor for std::vector looks like:
vector(std::initializer_list<value_type>)
Where value_type is the first template argument to std::vector. In this case, std::vector<std::vector<float>> has value_type = std::vector<float> -- which means that it can only be constructed from a std::initializer... |
63,797,383 | 63,797,830 | Does destroying delete still require destructor being accessible? | C++20 introduces the concept of a "destroying operator delete", as described below:
delete-expressions does not execute the destructor for *p before placing a call to operator delete
So, given the following struct S:
struct S {
void operator delete(S* p, std::destroying_delete_t);
private:
~S();
};
I'd expe... | gcc is correct: ~S() need not be accessible.
From [expr.delete]/6:
If the value of the operand of the delete-expression is not a null pointer value and the selected deallocation function (see below) is not a destroying operator delete, the delete-expression will invoke the destructor (if any) for the object or the ele... |
63,797,386 | 63,797,554 | Does reinterpret_cast with uint8_t break the Strict Aliasing Rule? | Is the following code legal in terms of the Strict Aliasing Rule (and in general)?
const int size = 1024;
uint8_t* buffer = allocateBuffer(size);
float* float_pointer = reinterpret_cast<float*>(buffer);
std::fill(float_pointer, float_pointer + size / sizeof(float), 1.5f);
As far as I understand, generally speaking SAR... |
However, in the above code we use a pointer of a non-character type (float*) to read or write data of (probably) a character type (uint8_t), which I think is illegal.
Am I correct?
Yes.
Is the following code legal in terms of the Strict Aliasing Rule (and in general)?
No.
Besides pointer aliasing, another consider... |
63,797,522 | 63,803,367 | MongoDB bsoncxx crash parsing a json document with int64_t value | I'm generating a json document in C# using the Bson library function ToJson(). The document starts with:
{ "Key" : NumberLong("2053249000001086"), ...
I'm parsing this document in a C++ DLL using the bsoncxx drivers.
An exception is thrown by this line:
'''bsoncxx::from_json(TheJsonDocument).view()'''
with What = "Got ... | The extended json you produced is invalid. The correct spelling is
{"$numberLong": <64-bit signed integer as a string>}
See https://github.com/mongodb/specifications/blob/master/source/extended-json.rst#conversion-table.
You need to fix the producing side to produce correct extended json.
|
63,797,818 | 63,797,920 | What is the syntax for make_unique for a pointer of base type to a derived object? | Consider the following base and derived classes.
class base
{
public:
int i{9};
virtual void func()
{
cout << "base" << endl;
}
virtual ~base()
{
}
};
class derived : public base
{
public:
int i{4};
void func()
{
cout << "derived" << endl;
}
};
I would lik... | When you do
auto ptr = std::make_unique<base>(derived{});
make_unique<base> is going to create a unique_ptr<base> which means it is only going to create a base object. Since derived is derived from base it is legal to pass that to base's copy constructor so the code compiles, but you have a base, not a derived.
What ... |
63,798,013 | 63,798,346 | runtime error: reference binding to null pointer of type 'std::vector<int, std::allocator<int> >' (stl_vector.h) | This is leetcode 210
There are a total of n courses you have to take labelled from 0 to n - 1.
Some courses may have prerequisites, for example, if prerequisites[i] = [ai, bi] this means you must take the course bi before the course ai.
Given the total number of courses numCourses and a list of the prerequisite pairs, ... |
You only have a small typo here: return vect to return myvect.
Another small bug is here: int m = n ? prerequisites[0].size() : 0;
After fixing these bugs, the algorithm partially works fine, does not work for all test cases though, not sure how to fix that. ( ˆ_ˆ )
class Solution {
public:
vector<int>... |
63,798,543 | 63,806,207 | CMake illogic path parsing? | I'm trying to include this project into my cmake code base.
I cloned the repo to my include/ dir and added this line to my CMakeLists.txtx:
add_subdirectory(${DIVISIBLE_INSTALL_INCLUDE_DIR}/cc.ublox.commsdsl)
include_directories(${DIVISIBLE_INSTALL_INCLUDE_DIR})
link_directories(${DIVISIBLE_INSTALL_INCLUDE_DIR})
But w... | Found the problem for the double path problem.
I added the project as subdir from my main project by adding this line:
add_subdirectory(${DIVISIBLE_INSTALL_INCLUDE_DIR}/cc.ublox.commsdsl)
The problem is that DIVISIBLE_INSTALL_INCLUDE_DIR is a absolute path and thus is added to the cmake source dir of the subdir.
This ... |
63,798,645 | 63,798,758 | How does C++ know how many bytes to copy when retuning an object from a function? | This question popped into my head when I saw the following warning.
struct Wrapper{
char somechar[10];
};
auto returnFoo() {
char somechar[10];
return somechar; // Warning: address of stack memory returned!
}
auto returnFoo() {
Wrapper wpr;
return wpr; // OK
}
I understand the ... | Functions cannot return arrays in C++. This is simply how the language is specified. This is the same in C.
In the first example, the array name decays to a pointer to first element of the array, and the deduced return type is pointer to char. Pointers can be returned, but the pointer will be invalid because the automa... |
63,798,992 | 63,799,430 | Why do references passed as arguments work for modifying variables via a function? | As I got stuck between whether shortening the question or clarifying it, I do not think I can be understood with the question sentence. I tried to explain myself with examples here:
Let's see a non-working void function for decreasing a variable by 1 :
#include <iostream>
using namespace std;
void decrease (int a)
{
... | Lets make this simple:
The meaning of "reference" is to refer to a specific variable.
You tell the compiler: "I want to work with this variable under another name, not make a copy".
How the compiler accomplishes this, is up to whoever writes the compiler (that is what the question you linked tries to explain).
But the ... |
63,798,996 | 63,799,138 | naming a member of a struct with a string array | in a Project of mine i need to call a member/property (dont know the right term) of a struct by a string which is inside an array.
The fat part in the line with the comment //???? is the Problem users[i].members[j] is nonsense and i know that but i just cant figure out what would be right there.
Thanks for your help in... | Create a map of strings to member pointers.
#include <map>
#include <string>
#include <iostream>
struct person { // Eigenschaften des Eintrags
std::string name; //nachname
std::string vorname; //vorname
std::string telefon; // telfonnummer
};
// map names of variables to person membe... |
63,799,028 | 63,799,376 | Invalid operands to binary expression when using unordered_map? | I'm trying to find if my character hash table contains the first character of a string:
string minWindow(string s, string t) {
unordered_map<char, int> charFinder;
for (int i = 0; i < t.length(); ++i) {
charFinder[t[i]] = 0;
}
cout << charFinder.find(s[0]) == charFinder.end() << endl;
return... | Per Operator Precedence, operator<< has a higher precedence than operator==, so your cout expression:
cout << charFinder.find(s[0]) == charFinder.end() << endl;
Is being evaluated as if you had written it like this:
(cout << charFinder.find(s[0])) == (charFinder.end() << endl);
The compiler error is complaining about... |
63,799,073 | 63,799,136 | sqrt function in C++ issue | #include <iostream>
#include <cmath>
using namespace std;
int main(){
int n;
cin >> n;
int i = sqrt(1 + 2 * n * (n + 1)) - 1;
cout << i;
}
I have written a simple program which utilizes the sqrt() function in C++. The above program prints out a negative value on the console for n = 327... | Change int n to double n. Your calculation 1 + 2 * n * (n + 1) overflows the range of int which for 32bits is -2,147,483,648 to 2,147,483,647.
Side note: int may not be 32bit, it depends on the platform (however, usually most of the time it is 32bit)
|
63,799,127 | 63,799,310 | Massive time loss in simple for loop | I have an extremely simple program to measure how much time a function is taking.
#include <iostream>
#include <vector>
#include <chrono>
struct Foo
{
void addSample(uint64_t s)
{
}
};
void test(const std::vector<uint64_t>& samples)
{
uint32_t onlyCallTime = 0;
uint32_t loopOnlyTime = 0;
Foo st... | 1 000 000 iterations took roughly 50 000 microseconds. That is well under 1μs per iteration on average and std::chrono::duration_cast<std::chrono::microseconds> will round any time less than 1μs to 0. Meaning your loop only counts the iterations that took way longer than average for some reason (scheduling, page faults... |
63,799,653 | 63,799,885 | how can a c++ concept combine concepts? | I have inherited the following:
template <typename T>
concept IsAwaiter = requires {
typename T::await_ready;
typename T::await_suspend;
typename T::await_resume;
};
template <typename ...AWAITABLES>
concept IsAwaitables = typename std::conjunction<IsAwaiter<AWAITABLES>...>::type;
Building this with clang 10.0.... | std::conjunction is for type traits. std::conjunction<IsAwaiter<AWAITABLES>...> is a type with a member static bool value = (IsAwaiter<AWAITABLES>::value && ...), where each IsAwaiter<AWAITABLES> is itself expected to be a type trait with its own static bool member value. This is nonsensical when IsAwaiter<AWAITABLES> ... |
63,799,977 | 63,800,421 | ERROR: Thread 1: EXC_BAD_ACCESS (code=1, address=0x68) FIX: PLACE THE IN AND OUT FILES IN THE WORKING DIRECTORY OF THE PROJECT | I get this error:
Thread 1: EXC_BAD_ACCESS (code=1, address=0x68)
on the following line:
while(fscanf(f,"%d", &a[x])==1)
1st time trying to do my class homework in Xcode, used code blocks before and managed to run this same code on it, any help is much appreciated!
#include <cstdio>
int a[1001];
int main()
{
int... | The problem was that I placed 1.in and 1.out outside the working directory, to fix this had to go to Product>Scheme>Edit Scheme>Run>Options and set a custom "Working Directory" where I placed the 1.in and 1.out files. Thanks for the help guys.
|
63,800,200 | 63,801,267 | How to check if mouse button is pressed anywhere on screen , even outside of my mainwindow? | Is it possible to detect mouse buttons pressed inside and outside of my application window in Qt, i guess there is a way to detect mouse clicks inside my application window , but what about detecting clicks inside+outside of main window ?
|
Is it possible to detect mouse buttons pressed inside and outside of my application window in Qt
I don't know if Qt itself provides such functionality, but the underlying OS likely does. For instance, on Windows, you can use a mouse hook via SetWindowsHookEx() or RegisterRawInputDevices() to monitor mouse activity g... |
63,800,876 | 63,801,299 | c++17 structured bindings and move semantics | im reading this https://leanpub.com/cppmove (C++17 - The Complete Guide First Edition Nicolai M. Josuttisand) and regarding c++17 structured bindings and move semantics it gives the following example, where the moved from object ms is left intact:
MyStruct ms = { 42, "Jim" }; // struct has fields {int i, std::string ... |
would not auto&& e = std::move(ms) cause ms to immediately have its contents "moved"/"stolen"/"invalidated"?
std::move() only prepares ms to be moved, it doesn't outright move from it. That's why e is a reference to a MyStruct, not an actual MyStruct object.
|
63,801,290 | 63,801,370 | "virtual memory exhausted: Cannot allocate memory" only when compiling with debug flag | I get the error with following code (error.cpp):
#include <map>
#include <functional>
#include <vector>
int main()
{
std::map<
int, std::map< std::string,
std::map<std::string, std::map<std::string, std::map<std::string,
std::map<std::string, std::map<std::string, std::map<std::string,
... | You have 8+7+6 strings in that definition, right? So, I'd say what you have on your hands is a relation of arity 21. Why not try:
constexpr const std::size_t my_arity = 21;
std::unordered_set<std::array<std::string, my_arity>> oups;
instead?
|
63,801,429 | 63,845,165 | OpenCV python is not displaying python wrapped Cuda SIFT Keypoints converted to OpenCV keypoint format | We wrote a small python wrapper using pybind11 around the ExtractSift function which seems to work fine.
Here's what it looks like :
std::vector<SiftPoint> extractSIFT(char* filename)
{
int devNum = 0, imgSet = 0;
cv::Mat img;
cv::imread(filename, 0).convertTo(img, CV_32FC1);
unsigned int w = img.cols;
... | I found the solution, had to put kp = cv.keypoint() inside the for loop:
def extract_sift_keypoints(impath, kpts):
im = cv.imread(impath, cv.IMREAD_COLOR)
kp1 = []
desc1 = (np.array([k.getdata() for k in kpts], dtype=np.float32))
for k in kpts :
kp = cv.KeyPoint()
kp.pt = (k.xpos, ... |
63,801,580 | 63,802,343 | Template specialization and references | In Functional programming in C++, chapter 11 deals with some basic template meta programming.
In this context, the author shows this implementation of remove_reference/remove_reference_t, which are essentially the same as those described on cppreference.
template<typename T> struct remove_reference { using type = ... |
only the general (or primary? What is the correcto word here?) template
The technical term used by the C++ Standard is "primary class template". It will also be the most general class template, compared to its partial specializations and explicit specializations. So that could also be a reasonable thing to call it, g... |
63,801,827 | 63,801,871 | how to did the value of k become -5 after implementation of 1st expression in this code? | Can somebody please help me understand this piece of code. I'm not able to understand how did k become -5 after the execution of statement k=(j>=5)?(i<5)?(i-j-i):(k-j):(i);
int main () {
int i=8,j=5,k=0;
k=(j>=5)?(i<5)?(i-j-i):(k-j):(i);
i+=(k)?(i)?(k):(i):(k);
cout<<i<<k;
return 0;
}
Output: 3 -5... | Just spreading out the nested ternary expressions, and adding a redundant parentheses might make it easier to understand:
k = (j>=5) ?
( (i<5) ?
(i-j-i)
: (k-j)
)
: (i);
Now j >= 5 is true, which means i < 5 is evaluated, which is false, whi... |
63,801,894 | 63,801,977 | I am trying to create an array with an already specificed maximum size using a class but the array does not seem to be created | I am trying to create an array in my UnsortedList class. I specified to create an array in the header file, and I also specified the MAX_SIZE, which is equal to 10. However, whenever I create my object of the class, the default constructor does not create that array with the MAX_SIZE. I am unsure what I am doing wrong.... | I recommend you use std::array or std::vector, but if you must use C arrays, then your definition in the header needs correcting:
class UnsortedList {
// ...
const static int MAX_ITEMS = 10;
int numbers[MAX_ITEMS];
};
You can remove the corresponding line in the constructor. The file reading method also needs ... |
63,802,391 | 63,804,302 | Why does CreateWICTextureFromFile require ShowWindow? | I'm writing some D3D11 apps and am using DirectXTK's CreateWICTextureFromFile to load a texture file into SRV. I wanted to show my rendering window only when I start to draw the scene (after initializing models, textures, shaders, constant buffers, etc.) so I've created the window early on but I omit the ShowWindow unt... | Before you call WICTextureLoader (which uses the Windows Imaging Component) you need to initialize COM as noted in the documentation.
In your main entry-point, add:
if (FAILED(CoInitializeEx(nullptr, COINIT_MULTITHREADED)))
// error
The fact that ShowWindow happens to initalize COM is an interesting side-effect, ... |
63,802,477 | 63,961,616 | mongo-cxx driver cannot find polyfill for unique_ptr | I'm trying to build mongo-cxx-driver on Windows; I'm following the instructions, but am getting errors:
C1189 #error: "Cannot find a valid polyfill for make_unique"
Here's what I did:
Building mongo-c-driver
I cloned mongo-c-driver using the specified minimum release (1.15):
git clone https://github.com/mongodb/mon... | The answer seems to be in the installation guide, I missed a step:
For building with Visual Studio 2017 (without a C++17 polyfill), it is
necessary to configure with an additional option, /Zc:__cplusplus to
opt into the correct definition of __cplusplus (problem described
here):
'C:\Program Files (x86)\CMake\bin\cmake... |
63,802,972 | 63,803,030 | c++: how to constrain template type to copy-assignable types? | template<typename T>
class A {}
How can I restrict types T to only those that are copy-assignable?
I know about std::is_copy_assignable<T>::value but how can I use that to restrict the type T for class A?
| You can also use static_assert for this, which lets you generate a nicer error message:
template<typename T>
class A
{
static_assert (std::is_copy_assignable_v<T>, "T must be copy-assignable");
};
Live demo
|
63,803,093 | 66,423,083 | Do boost accumulators support the calculation of minimum difference between adjacent values? | Assumption here is that I am receiving many values and I do not want to store them in the vector.
So I would like to use something like boost accumulators. But in docs I can not find something like the logic I want.
Is there a way for me to have accumulator so that when called with
5, 10 , 12 , 15 , 27 it will output 2... | Not with the accumulators that are part of Boost, but you can write your own.
The accumulator itself will look something like this. Note that this version only handles an increasing sequence of values correctly, but does not required an initial sample. If you have different requirements you can tune this.
namespace boo... |
63,803,277 | 63,803,340 | How do I process two functions in parallel each running at a specific frequency? | I would like to run two functions in parallel, each having a different execution frequency.
I used CppTime::Timer, but I realized, that the functions are actually executed behind each other. Is that because CppTime executes the threads behind each other, or is there something wrong with my code?
Here the script:
CppTim... | When adding the timer callbacks, the statements longProcess() and shortProcess() will try to call those functions, and then pass the return values to add(). So the 1st timer.add() wouldn't even be executed until after longProcess() finishes its work and exits. And the same with the 2nd timer.add() and shortProcess().... |
63,803,770 | 63,804,035 | Why debugging and running outputs are different in C++? | I want to read ".text" file and convert string as double. In debug mode i can read text as 99,03 but in running mode i can read only 99. I can't understand how it would be? My converting code is below
double a = std::stod(text)
| std::stod is affected by locale.
#include <iostream>
#include <string>
#include <clocale>
int main(void){
std::setlocale(LC_ALL, "C");
std::string s{"99.03"};
double d = std::stod( s );
std::cout<< d << "\n";
std::setlocale(LC_ALL, "de_DE.UTF-8"); // A locale installed on your machine.
std::s... |
63,803,854 | 63,805,213 | No argument specified with option "/MAPINFO" , why? | I try to fix my previous company project on visual studio 2013, but when i try to build i have error like this
error LNK1146: no argument specified with option "/MAPINFO"
when i see on linker -> Command Line -> additional options, i see this command:
/MAPINFO:EXPORTS /MAPINFO /MAPINFO:LINES
if i delete that comma... | As far as I know, /MAPINFO:LINES is no longer supported since VS2005. You could delete it.
If you need to use it, you may have a try to find a replacement of it. You can refer to the link below and consider using dbghelp library to do this.
|
63,804,434 | 63,804,466 | Best way to find code and data sections in COFF object files? | I want to find the CODE and Initialized DATA sections in COFF Object files.
The sections that I want to find are called .text$mn and .data in output generated from two versions of Microsoft "c" compilers.
I have no idea how consistent this is across different compiler vendors, compiler versions from one vendor or diffe... | Table 7. Section Header Flags
STYP_TEXT 00000020h Section contains executable code
STYP_DATA 00000040h Section contains initialized data
Common Object File Format
Does narrow down the options, yet derived two different data sections.
On the Microsoft platform searching for these section names in the Symbol_Table seems... |
63,804,482 | 63,804,764 | C++ Reading from a file - First line of file being skipped, and last line being repeated twice | I have been tasked with a C++ program in which I need to read integers from an input file, calculate their roots, and then print them to an output (either the screen or a specified output file). I have been able to achieve this, but my problem is that my code is skipping the first line of the input.txt and then repeati... | The first line is not being skipped. It's being read into line_str in the line
getline(input_file, line_str);
The last line is not being read twice. It is failing but you are not checking whether extraction from the file was successul. You should always check that before using the variables you are reading into.
Inste... |
63,804,632 | 63,804,989 | function that covers boost::trim and accepts std::vector<std::string> | void trimMyStrings(std::vector<std::string> &dataVectors) {
for(auto &dataVector : dataVectors) {
boost::algorithm::trim(dataVector);
}
}
int main() {
std::string firstWord = " blaasldlasasdasd ";
std::string secondWord = " asdasdasd ";
std::vector<std::string> combineWord{firstWor... | you need a reference to the original strings that you place into your vector.
std::vector<std::string*> combineWord{&firstWord, &secondWord};
Then for trimMyStrings you need to update its parameter like:
void trimMyStrings(std::vector<std::string*> &dataVectors)
Then use trim with something like:
boost::algorithm::tr... |
63,804,666 | 63,807,472 | How can a clang 10 C++20 concept specify compound requirements for class methods? | I have some code which tries to use a concept to specify requirements on the member functions of a class:
#include <type_traits>
template <typename A>
concept MyConcept = requires(A a, bool b) {
{ a.one() } -> bool;
a.two();
a.three(b);
};
Unfortunately, clang 10.0.0 using -std=c++20 on https://godbolt.org p... | The concepts proposal changed and now it requires using std::same_as.
This compiles fine with Clang 10 (although you may need to provide std::same_as yourself if you don't have a stdlib with it):
template <typename A>
concept MyConcept = requires(A a, bool b) {
{ a.one() } -> std::same_as<bool>;
a.two();
a.three(... |
63,804,937 | 63,805,035 | delete[] keyword after declaring array using new causing error | I have the below code snippet.
int main()
{
wchar_t *wTemp = new wchar_t[ArrSize];
std::vector<char> SourceVector;
std::vector<std::wstring> DestinationVector;
for (int i = 0; i < ArrSize; i++)
{
SourceVector.push_back(i);
}
int k = 0;
for (size_t i = 0; i < SourceVector.size... | You always write at most ArraySize characters no matter where in the array you start via wTemp + k, that will lead to buffer overrun.
k += swprintf(wTemp + k, ArrSize-k, L"%u", SourceVector[i]);
Is the correct call, but this will only reveal the true source of the error. swprintf appends \0 (and actually writes only ... |
63,805,370 | 63,806,176 | Which one is faster for obtaining substring of a given string in C++? The string constructor or the substr() function? | Whenever i need to obtain a substring of a given string, I've always had a dilemma over which method would be faster.
Method 1 - using std::string::string (const string& str, size_t pos, size_t len = npos) - the string constructor
string str = "abcdefgf";
string sub(str, 2, 4); //sub = "cdef"
Method 2 - using s... | std::string owns its data, so with either API the cost is dominated by allocating and copying data for the substring. What you may want is std::string_view, which avoids all this by "viewing" the underlying data without copying.
|
63,807,171 | 63,813,608 | Moving std::string into capture | Consider the following example that takes a msg and posts it asynchronously.
void sendMessage(std::string msg) {
runAsync<void>([msg = std::move(msg)] {
onPostMessage(cookie, msg.c_str());
});
};
Would the following be faster?
void sendMessage(std::string&& msg) {
What would be the... | I would use the following solution:
void sendMessage(std::string&& msg) {
runAsync<void>([msg = std::move(msg)] {
onPostMessage(cookie, msg.c_str());
});
};
and at the calling site:
auto msg = ...
sendMessage(std::exchange(msg, {}));
|
63,807,277 | 63,824,781 | Electron app won't open after compiling for Win32 x64 | I have an issue. I was creating an app with electron and when I compiled it to an .exe file it built, but haven't started/created a window on my laptop. I tried turning off my Windows Defender but that didn't help. Whenever I try to run it with my npm script npm start or electron . it works. Is there anything that I'm ... | Your build command seems wrong.
See the docs of electron-packager for the command's signature:
electron-packager <sourcedir> <appname> --platform=<platform> --arch=<arch> [optional flags...]
What you do in mkdir build && electron-packager build ISS-Live-Locator --platform=win32 --arch=x64 is basically trying to use th... |
63,807,309 | 63,807,643 | Compiling cpp Project with command line But debugging in Vscode | I compile my code with the command line. here is an example of how I compile a program named "out" with 2 libraries a and b
g++ -c -O3 -I../../include/boost_1_61_0 -std=c++14 -MMD -MP -MF "a.o.d" -o a.o ../../my_Library/lib_a.cpp
g++ -c -O3 -I../../include/boost_1_61_0 -std=c++14 -MMD -MP -MF "b.o.d" -o b.o .... | Here is example of configuration:
{
"name": "(gdb) Launch my super program with 3 args",
"type": "cppdbg",
"request": "launch",
"program": "/home/user/build/my_program.o",
"args": ["arg1", "--arg-2", "arg_3"],
"stopAtEntry": false,
"cwd": "/home/user/build/workspace",
"environment": [],
... |
63,807,846 | 63,808,023 | values unable to assign to struct | I am unable to assign values to struct, d.
It is always 0.
I can't find the bug.
My print statement always prints x is: 0, y is 0
disc dArr[30];
struct disc *d ;
for (int i = 0; i < numDiscs; i++)
{
d = &(dArr[numDiscs]);
x_offset = d->pos[0];
y_offset = d->pos[1];
printf("The x is: %f\n", x_offset);
... | disc dArr[30];
struct disc *d ;
for (int i = 0; i < numDiscs; i++)
{
d = &(dArr[numDiscs]);
...
}
Assuming that numDiscs == sizeof(dArr) / sizeof(*dArr), attempting to access the object at address &(dArr[numDiscs]) yields undefined behavior.
What you probably want is &(dArr[i]).
|
63,808,234 | 63,811,511 | Switch button couple in Qt | I'm building a simple switch from two QPushButton. At the beginning, only one is enabled (let's say button 1) and when you click on it, it's disabled while button 2 is enabled. If you click on button 2, it's disabled and button 1 is enabled.
This is the .cpp code:
#include "SwitchButton.h"
#include "ui_SwitchButton.h"
... | I was able to reproduce the behaviour: Clicking the button, while the mouse stays hovered over the button sometimes leads to the animation that comes with the hovering not being finished properly.
Updating the disabled button some time after it was disabled clears the wrong animation. Adding the following line in the f... |
63,808,539 | 63,808,625 | trim for both std::string and std::wstring | I have a trim function for std::string,
static string trim(const string &s)
{
int ibegin = s.find_first_not_of(" \t\r\n");
if (ibegin == string::npos)
{
return "";
}
int iend = s.find_last_not_of(" \t\r\n");
return s.substr(ibegin, iend - ibegin);
... | TCHAR is the template argument, not a preprocessor token. Use if constexpr instead.
template<typename TCHAR>
std::basic_string<TCHAR> trim(const std::basic_string<TCHAR>& s)
{
int ibegin;
if constexpr(sizeof(TCHAR) == 1) {
ibegin = s.find_first_not_of(" \t\r\n");
}
else {
ibegin = s.fin... |
63,808,746 | 63,847,197 | How to deallocate array of class instances in C++? | I am making a little game, I store the map in an array, for a reason I think is needless to inform you about my map is not just a char array, I have made a class:
enum Marks { N, Ex3, Ex2, Ex1, Pl, En, Pb, Eb};
class MC /*Map Component*/{
public:
Marks Marked = Marks::N;
char ch = '\0';
};
and my array is an ... | Well, I am terribly sorry, bcs it turns out that I am a total idiot, my stupidness knows no bounds. The reason I am saying this: as the game runs certain type of objects get created, deleted and recreated all the time and bcs of that I was allocating them to the heap, but I forgot to make my program delete them in case... |
63,809,034 | 63,809,112 | Save the new value of a variable whenever it changes | I'm using C++ on Visual Studio 2015. I want to check if the status variable changes during these lines. if everything is OK status always returns 0 else -1.
My problem here is that I'm checking only on the last status variable.
How can I know if any of status got -1 ?
int function1(ATF *cm33) {
int status;
uint32_t va... | If you want to preserve the value of -1 to signify that any of the statuses were non-zero then use
int status = 0;
followed by
status |= cm33->readData32(SAU_CTRL_Mv8, &val);
status |= cm33->writeData32(SAU_CTRL_Mv8, 0x3);
status |= cm33->readData32(SAU_CTRL_Mv8, &val);
This has the advantage of only returning 0 if e... |
63,809,206 | 63,810,806 | C++ How to place data in vector of base class | Here is my base class:
#include <string>
#include "DataStruct.h"
#include <vector>
#include <mysqlx/xdevapi.h>
#include <iostream>
#include <memory>
namespace Vibranium {
using namespace mysqlx;
class MySQLTable {
public:
MySQLTable();
virtual ~MySQLTable() = default;
int Index;
... | I would drop the type DataStruct, and make MySqlTable a template.
#include <string>
#include <vector>
#include <mysqlx/xdevapi.h>
#include <memory>
namespace Vibranium {
using mysqlx::Table;
using mysqlx::RowResult;
using mysqlx::Session;
class MySQLTableBase {
public:
MySQLTableBase();
... |
63,809,236 | 63,809,337 | Is it undefined behavior to iterate over an std::array initialized in the for-loop? | // This snippet
for (const float t : std::array{ 0.0f, 0.33f, 0.66f, 1.0f }) {
std::cout << "t = " << t << "\n";
}
// Yields the following (incorrect) values:
t = -3.91649e-28
t = 4.59037e-41
t = 2.66247e-44
t = 0
// Whereas this snippet ...
auto vals = std::array{ 0.0f, 0.33f, 0.66f, 1.0f };
for (const float t : va... | No, it is not UB since range-for loop does extend lifetime of temporary range.
https://en.cppreference.com/w/cpp/language/range-for
If range_expression returns a temporary, its lifetime is extended until the end of the loop, as indicated by binding to the forwarding reference __range, but beware that the lifetime of a... |
63,809,336 | 63,809,458 | How can i check if all charterers in a word are existing into the other one? | I'm trying to make a code that takes tow words from user and store them as arrays and check if the first word's all characters are already exists in the second word , if Yes then just output Yes , if NO then output a NO .
Example :
input :
ENTER THE FIRST WORD :
fos
ENTER THE SECOND WORD :
stackoverflow
output :
... | I tried it with simple search and 1 boolean variable to track if it is found or not.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1 = "fosq";
string s2 = "stackoverflow";
bool isfound;
for(int i=0;i<s1.length();i++)
{
isfound=false;
for(int j=0;j<s2.length();j++)
... |
63,810,157 | 63,810,216 | Pointer re-assignment, heap use after free | I'm trying to write a simple function that swaps the nodes of a linked list (in which the values cannot be changed, just the nodes). Running into memory usage after free errors, and I can't pin it. I'm fairly certain the answer is quite straightforward and easy, I just can't see it right now.
void swapNodes(ListNode* a... | With
auto newA = std::make_shared<ListNode>(ListNode(b1->val, a2));
you create a new shared pointer object. This object is local inside the swapNodes function. Its life-time ends when the swapNodes function returns, and the object is destructed.
This destruction will lead to the memory allocated will be deleted, unles... |
63,810,298 | 63,812,360 | What is the difference between load/store relaxed atomic and normal variable? | As I see from a test-case: https://godbolt.org/z/K477q1
The generated assembly load/store atomic relaxed is the same as the normal variable: ldr and str
So, is there any difference between relaxed atomic and normal variable?
| The difference is that a normal load/store is not guaranteed to be tear-free, whereas a relaxed atomic read/write is. Also, the atomic guarantees that the compiler doesn't rearrange or optimise-out memory accesses in a similar fashion to what volatile guarantees.
(Pre-C++11, volatile was an essential part of rolling y... |
63,810,979 | 63,816,108 | Send POST data via HttpOpenRequestA | I'm trying to send my PC Name to my local server and save it in a file.
There is my code:
#include <stdio.h>
#include <windows.h>
#include <iostream>
#include <fstream>
#include <string>
#include <string.h>
#include <cstring>
#include <Lmcons.h>
#include <unistd.h>
#include <stdlib.h>
#include <WinInet.h>
#include <bit... | You can't concatenate char[] arrays like you are trying to do. Allocate a separate buffer of sufficient size and copy the input strings into it, eg:
#include <windows.h>
#include <Lmcons.h>
#include <WinInet.h>
#include <cstring>
//#include <cstdio>
using namespace std;
#pragma comment( lib, "Wininet.lib")
int main(... |
63,812,552 | 63,812,905 | How can I use different rules in Makefile for two groups of files? | I have one Makefile to build an executable and a library. Executable consists of a lot of source files and library consists of one .cpp file. The difference between compilation of executable and library is -fPIC option.
There is a compilation rule:
%.o : %.cpp
$(CXX) -c $(CXXFLAGS) $< -o $@
all: $(TARGET) $(TA... | If you just run make without a target, the first target gets built. So just put all back at the top and it should work fine.
|
63,812,657 | 63,813,464 | Unexpected result of std::is_invocable over a template type | I have an if constexpr checking that a type is equality-comparable with itself. I use std::is_invocable_v<std::equal_to<>, T, T>.
However, when T is a vector of incomparable structs, the snippet falsely returns True. Is there a deep reason for it or is it a compiler bug?
Minimal example follows.
#include <type_traits>
... | I think, this is correct behavior.
In the first std::is_invokable_v checks for the presence of the operator== in the TNonComparable type. It is not present - so the result is 0.
In the second case std::is_invokable_v checks for the equality operator of the std::vector, which is present and may be invoked. But if do try... |
63,812,727 | 63,813,012 | delete on pointer (*&) to base class with virtual destructor c++ | So, I have a game-server running on a very old system (2006-2007) that creates a player object when a players logs in, a monster object when a monster is created and a npc object when npcs appear. All these classes derive from the creature class and all of them have virtual destructors. So, when I create these objects ... | if (!cr)
continue;
will not work like you intend it to. deleteing a pointer doesn't reset it to nullptr. In your first call to ProcessAllCreatures() everything may work fine, when you call it a second time you will delete already deleted pointers, because you will never continuewhen looking at a already deleted po... |
63,812,803 | 63,813,582 | Do map::erase(iterator) functions require valid key contents? | Consider the following:
struct ExternalBuffer {
ExternalBuffer(const char *s) : s(s){}
const char *s;
bool operator<(const ExternalBuffer& other) const {
return strcmp(s, other.s) < 0;
}
};
char *some_cstr = strdup("hello");
std::map<ExternalBuffer, Value> m;
m.insert(std::make_pair(ExternalBuffer(some_cst... | Keys in a map are const objects, and they need to stay valid as long as they are in the map. Any change to their state that can change the behavior of the comparison function results in Undefined Behavior.
Because free(some_cstr); will break this comparison (since it will invoke Undefined Behavior by dereferencing a fr... |
63,812,908 | 63,824,393 | Unbox numerical value in c++/winrt with conversion | Is there a way to unbox numerical value regardless of type? For ex. boxing int and then unboxing double or long long (if the conversion is possible). The point is to be able to unbox from some unknown type to known type if the conversion is possible.
Now it behaves like this:
winrt::Windows::Foundation::IInspectable bo... | If you don't know (or don't care) which type of value has been boxed, IReference<T> won't be fun to use. Chaining a bunch of unbox_value/unbox_value_or calls will incur a series of QueryInterface calls, which is a very inefficient way to do this. Better, would be to use IPropertyValue. It already performs scalar conver... |
63,813,522 | 63,814,712 | Create a heap-based 2D array without using double pointer syntax? | I need to declare a 2D array as the member variable of a class. I can't use STL (so, no vector), and I've been asked to avoid double/triple pointers. I want to be able to reference elements in this 2D array using subscripting notation, e.g. arr[0][0]. The array also must be declared on the heap due to its size.
Due to ... | Of course you can do this without double/triple pointers. You can even do this without use of any pointers in the class declaration. But first lets look at the more common approach. A 2D array is a simple extension of a 1D array.
Starting off with the standard way this is done for a 1D array of 1000 ints w/o using vect... |
63,813,682 | 63,815,167 | Include QNetwork module | First, I've seen this thread : How to use/include the QtNetwork Module.
I've followed every step.
these are my includes :
#include <QTcpServer>
#include <QTcpSocket>
My additionnal include directory path
C:\Qt\5.15.1\msvc2019_64\include\QtNetwork
My additional library path
C:\Qt\5.15.1\msvc2019_64\lib;
Right now it ... | Ok I've found the problem, it stems from the fact the lib file is currently named "Qt5Networkd.lib" and not "QtNetworkd.lib" as i had seen on the web. Leaving the answer here in case someone goes across the same trouble.
|
63,813,775 | 63,823,504 | C++ calling Python how to deal with SystemExit exception | I have a C++ code which executes Python script using the PyRun_SimpleFileEx C API.
The py file looks like this
import time
time.sleep(2)
raise SystemExit("Sorry, it is time to exit.")
SystemExit is what is also raised by calling python stuff like either quit() or abort()
Since SystemExit inherits from BaseException i... | You can create a wrapper.py and run the code from it.
class ExceptionWrapper(Exception):
def __init__(self, exc):
self.exc = exc
def run_code(filename):
try:
exec(open(filename).read(), globals=globals(), locals=locals())
except BaseException as ex:
raise ExceptionWrapper(ex)
Using... |
63,814,223 | 63,814,383 | Unexpected behavior of arrow operator "->" in c++ | The code I have provided is simple BST with insert & inorder traversal only.
struct Node{
int data;
Node* left;
Node* right;
};
Node* create(int data){
Node* node = new Node;
node -> data = data;
node->left=node->right=NULL;
return node;
}
Node* insert(Node* ptr,int item);
void inorder(No... | ptr->left=insert(ptr->left, item);
Will change the content of the ptr object. It does the insert and stores it.
However, when you do:
ptr = ptr->left;
ptr = insert(ptr, item)
you first get a pointer to what ptr->left was pointing, you insert in the same way. But the return value doesn't get stored in your original pt... |
63,814,242 | 63,814,307 | How to initialize members of class/struct type in another class/struct type | Assume that I have a struct foo and a wrapper struct wrapper for foo defined below
struct foo
{
int n;
foo(const int s) {n = s};
};
struct wrapper
{
foo f;
wrapper(const int s);
};
Is there a way to use the constructor of wrapper to initialize the member of type foo in wrapper through callin... | This should do what you want, here foo is initialized with the same const int that was given to wrapper constructor.
struct foo
{
int n;
foo(const int s) {n = s;} // <- corrected your typo here
};
struct wrapper
{
foo f;
int u;
wrapper(const int s) : f (s), u(0){ //<- foo initialization here
}
}... |
63,814,346 | 63,814,829 | How can i erase duplicated elements from a multimap<int, std::pair<int, bool>>? | I have a multimap with duplicates. When I finished the collection of the elements i would like to erase the dups.
Here is the container:
std::multimap<int, std::pair<int, bool>> container;
This following code is inside an iteration.(it is a simpler version of the original)
container.emplace(LeafId, std::make_pair(Node... |
Is it good solution?
Unless you keep internal pair sorted inside multimap, no it is not a good solution as it would miss duplicates. If you can change data type then you can use:
std::map<int, std::vector<std::pair<int, bool>>>
instead of std::multimap and then for each element sort vector and remove duplicates usin... |
63,814,461 | 63,817,295 | Qt app undefined reference to `gst_app_src_push_buffer' | I'm creating a Qt application which will show a video which is more or less based on the following code:
https://gist.github.com/floe/e35100f091315b86a5bf
When I'm running it as it is at C file it's working, but when I try to move it to my Qt app, I get undefined reference to `gst_app_src_push_buffer' (and 'collect2:er... | gstapp probably does not exists with that name. Use pkg-config for that as well:
PKGCONFIG += gstreamer-1.0 gstreamer-app-1.0 glib-2.0 gobject-2.0
|
63,814,984 | 63,815,525 | A redis command ERR:wrong number of arguments hiredis | when I am executing the "script load" command through hiredis adapter I am getting the error wrong no of argument. The same command through Redis client is running fine.
reply_r= (redisReply *)redisCommand(con_r,"script","load", "return 1");
string stemp="";
if(reply_r->len>0)
{
string stt... | reply_r= (redisReply *)redisCommand(con_r,"scrips load %s", "return 1");
string stemp="";
if(reply_r->len>0 && reply_r!=NULL)
{
stemp=string(reply_r->str);
}
freeReplyObject(reply_r);// should free the object after reading the data
return stem... |
63,815,157 | 63,815,313 | Cpp expression does not get executed | I have created a simple function that gets a string called code and reads it line by line (The line seperator is defined as TERMINATOR, and currently is '\n'). So I wrote this mess:
uint16_t* compile(string code){
for(int i = 0; i < code.length(); i++){
string line;
while(code[i] != TERMINA... | Supposing that your string is std::string and your printf is the C standard library's printf, there is no automatic conversion applied to the variadic arguments of printf(), so your printf("%s\n", line) produces undefined behavior on account of the second argument not being correctly type matched to a %s directive. Yo... |
63,815,405 | 63,815,458 | Overriding a template argument in grandchild class in C++? | I have the following hierarchy
template<class SettingsType>
class TemplatedBase;
class A : public TemplatedBase<SettingsTypeA>;
class B : public A;
class SettingsTypeA;
class SettingsTypeB : public SettingsTypeA;
Is there a way to override the template specialization in B so it inherits from A while having the... | A simple change would be to template A while giving it a default:
template<typename T = SettingsTypeA>
class A : public TemplatedBase<T> {};
and then you can use the needed type when B inherits from A:
class B : public A<SettingsTypeB> {};
|
63,815,871 | 63,816,394 | How can I change the parameters of a default constructor? | I have a class called Date that controls the date.
I have a constructor Date(). If this constructor is uninitialized, a default date will be put in its place by a private, static data member called default_.
I have initialized default_ in Date.cpp as follows:
Date Date::default_{1, Month::January, 1900};
Where the fir... | Let's step through your main line by line:
auto date_1 = Date{};
What will this do? It will call Date::Date, which will read all of the values from default_ into date_1. At this point default_ is 1/1/1900 and date_1 now is the same. Then
date_1.setDefaultDate(29, Month::September, 2020);
will change default_ and defa... |
63,815,912 | 63,825,308 | Doubts on classes when implementing binary search trees | I am studying generic binary search trees (BST) and AVL trees (AVL) on some notes that contain implementation pseudocodes. I am a bit puzzled about some details of their implementation.
The BST is based on the struct Node below
struct Node{
int key;
Node* parent;
Node* left;
Node* right;
//constructors
}
//... | You could use CRTP here. This would allow you to create the left right and parent nodes in the baseclass. For example consider something like this:
template<typename T>
struct BaseNode{
int key;
T* parent;
T* left;
T* right;
};
struct AVLNode : public BaseNode<AVLNode>{
int height;
int size;
AVLNode(cons... |
63,816,571 | 63,816,811 | How would I put two words from a file into one index in an array? | I want to put first and last names into an array, but I don't want to use a 2d array because the names will always be used together for my project. I have tried something like this:
ifstream in("filename");
string* names = new string[num];
for (int i = 0; i < num; i++)
{
in >> names[i] >> names[i];
}
But tha... | operator>> assigns to names[i] it does not concatenate strings. You could write an overload for >> that can concatenate strings. Would be fun but not quite appropriate here I think. Simple solution is to first read the strings, then concatenate them (I am scared of pointers, hence no pointers in my example):
std::ifstr... |
63,817,005 | 63,817,779 | Populate char* array using loop | I have a legacy function that has an input parameter of type const char* array
myfunc(const char* names[]);
I have a set std::set<std::string> mynames;. The set has already been populated.
I have to pass mynames to myfunc
Using range based loop, I have
const char* names[];
int i = 0;
for (const auto &name : mynames)
{... | You are not allocating any memory for the names[] array. You need to do something more like this:
const char** names = new const char*[mynames.size()]; // +1 if needed
size_t i = 0;
for (const auto &name : mynames)
{
names[i++] = name.c_str();
}
/* if needed:
names[i] = nullptr;
*/
/* alternatively
std::transfor... |
63,817,007 | 63,833,011 | How to create a constexpr std::vector<std::string> or something similar? | So I've been looking around and trying different things but I can't wrap my head around how I would go about creating some collection of strings with constexpr.
What I'm trying to do is basically the following, which obviously doesn't compile:
constexpr std::vector<std::string> fizzbuzz(){
size_t N = 100;
std:... | std::vector/std::string doesn't have constexpr constructor before C++20...
and even in C++20, the constexpr allocation should not escape from constexpr evaluation, so cannot be used in runtime (for printing).
I don't see a standard constexpr way to transform an integer to a char sequence representation.
std::to_string,... |
63,817,332 | 63,817,660 | Accessing windows 10 task manager process list | When it comes to the Windows 7 task manager, I was easily able to get the process count, etc because the processes were stored in a traditional listview control that I could access using SendMessage functions. For explorer/win10 task mgr/etc however the list control that the processes are stored in does not seem to be ... | Don't do that. Task Manager isn't doing any magic. It uses Windows APIs to get the list of processes, enumerate it, and obtain details. What you're doing is actually harder to get right than simply replicating what Task Manager is doing internally. A good starting point would be the Process Status API (psapi), and ther... |
63,817,819 | 63,817,933 | libstc++-6.dll was not found | Language: C++
IDE: Code::blocks
Compiler: GNU GCC
OS: WIndows
I am trying to create an executable. When I go to the executable file, and I attempt to open it, it says " the code execution cannot proceed because libstc++-6.dll was not found. Reinstalling this program might fix this problem." The problem is that the cod... | Based on libstdc++-6.dll not found, it looks like the problem is that your executable isn't in the same directory as the dll, so either copy the dll file to the directory with your executable, or better: use the static options to link the libraries without needing to copy the dll for each executable.
|
63,818,232 | 63,818,399 | Why using SFINAE to find if a method exists fails with std::vector::begin | I'm looking for a way to detect if a template class has the methods begin, end and resize.
I tried a modified version of this answer:
#include <iostream>
#include <vector>
// SFINAE test
template <typename T>
class has_method
{
typedef char one;
struct two { char x[2]; };
template <typename C> static one ... | std::vector has an oveloaded begin: one overload is const and the other one is not.
The compiler doesn't know which overload to use when you write &C::begin, so it treats this ambiguity as an error, which gets detected by SFINAE.
Instead of forming a pointer to begin, just call it:
// ...
template <typename C> static o... |
63,818,500 | 63,818,549 | Why does this simple custom-comparator of tuples crash even with strict-weak ordering? | This simple custom-comparator for type tuple<int, int, int> crashes for the example test below. I checked with the cout statements in the cmp comparator that each call to cmp gets a return value, so it's not like the values in the tuples t1 and t2 are junk.
Any idea why this is crashing? Is there anything wrong with th... | Your cmp operator() does not have a strict weak ordering. e.g. you need to check if d1 == d2 before comparing w1 < w2 and so on. This violates the requirements of std::sort which invokes undefined behavior. This could lead to a crash.
A simple implementation that is correct would be:
bool operator() (std::tuple<int, in... |
63,818,501 | 63,818,666 | runtime error while merging 2 binary trees | I'm trying to solve merging binary trees problem from leetcode. Here is my c++ code
class Solution {
public:
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
TreeNode *t;
if(t1==nullptr){return t2;}
if(t2==nullptr){return t1;}
t->val=t1->val+t2->val;
t->left=mergeTrees(... | In this code
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
TreeNode *t;
if(t1==nullptr){return t2;}
if(t2==nullptr){return t1;}
t->val=t1->val+t2->val;
t is an uninitialised pointer, and therefore t->val is an error.
Presumably you meant something like this
TreeNode* mergeTrees(TreeNode* t1, TreeN... |
63,818,871 | 63,838,050 | Why does tag_invoke pattern need the Niebloid std::tag_invoke at all? | This question assumes familiarity with the customization point management technique tag_invoke, introduced in P1895R0.
A customization point object can be defined according to P1895R0 as:
inline constexpr struct foo_cpo {
// simplified original by omitting noexcept forward and using auto arg
auto operator()(aut... | I don't think it's strictly necessary for tag_invoke itself to be a function object. But defining it as an object gives us a handy place to put a poison-pill overload should we decide that's necessary. And it's generally nice to have functions as first-class citizens that can be passed to higher-order functions. That's... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.