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 |
|---|---|---|---|---|
67,552,939 | 67,552,996 | In fstream, why read() and write() require const char*? | I trying to write a C++ program that can make a copy of a bmp file:
unsigned char* BMP_in(const char* filename) {
ifstream f(filename, ios::binary);
if (!f.is_open())
return NULL;
f.seekg(0, ios::end); //put pointer to the end of file
int size = f.tellg();
f.seekg(0, ios::beg);
unsigne... | Because std::ifstream is std::basic_ifstream<char>.
If you wish to read unsigned chars, use
std::basic_ifstream<unsigned char> f(filename, ios::binary);
|
67,553,073 | 67,553,155 | std sort sometimes throws seqmention fault | I have written the following function for partially doing stable sort over vector of arrays. When the size of vector is small like 1G it always work, when the size of vector is large (5 or 6 Gig) sometimes it works, sometimes it throws segmentation fault, could someone help me figure out the resean for this.
template <... | std::sort requires that the comparison function be a "strict weak ordering", which requires:
it is irreflexive: for all x, r(x, x) is false;
Your comparison function does not meet this requirement, because, as Mark Ransom pointed out in the comments, you return true when t1 == t2. Your comparison is basically <= rath... |
67,553,214 | 67,554,551 | friend function cant access private memebers | i started learning about operators overloading, at first it seem to easy, but now am having a problem accessing private member when try to make a global funtion operator
player.hpp
#ifndef _PLAYER_HPP_
#define _PLAYER_HPP_
#include <iostream>
#include <string>
#include "item.h"
class player
{
friend player ope... | First things first, Error #1:
main.cpp:9:1: error: ‘::main’ must return ‘int’
9 | void main(int args, char* argv) {
| ^~~~
main.cpp:9:6: warning: second argument of ‘int main(int, char*)’ should be ‘char **’ [-Wmain]
9 | void main(int args, char* argv) {
| ^~~~
The fix is easy:
int main(int ar... |
67,553,399 | 67,555,781 | double overloaded sin() and cos() do not maintain 15-digit decimal precision | Using this link as a guide, https://www.geeksforgeeks.org/difference-float-double-c-cpp/#:~:text=double%20is%20a%2064%20bit,15%20decimal%20digits%20of%20precision. double is a 64 bit IEEE 754 double precision Floating Point Number (1 bit for the sign, 11 bits for the exponent, and 52 bits for the value), i.e. double ha... |
double overloaded sin() and cos() do not maintain 15-digit decimal precision
It is not possible for any fixed-size numerical format to “maintain” a specific precision, regardless of whether it is floating-point, integer, fixed-point, or something else.
Whenever the result of an operation performed with real-number ma... |
67,553,728 | 67,553,990 | Is it an acceptable way to use class' private methods in C++? | In my C++ program I have a class, in some methods of which there are same routines happen, such as opening streams for reading/writing to files, parsing files, determining mime types, etc. Same routines are also used in constructor. To make methods more compact and avoid typing same code multiple times I split these ro... | Not to mention that what you did is the recommended way! Whenever you have multiple different operations inside a function, the standard way is to separate the function into multiple functions. In your case, the user does not need those functions, so making them private was the best you could do! When it comes to the p... |
67,553,852 | 67,553,981 | How to convert a string to uppercase using a Queue? | #include<iostream>
#include<queue>
#include<string> // probally not needed
#include<cctype>
using namespace std;
int main()
{
queue <string> str; // i created some kind of vector queue
cout << "Please enter a string." << endl;
string temp;
cin >> temp; // grabs the string
if(temp != "") // checks if string is empty
{
... | You can do this following way.
#include<iostream>
#include<queue>
#include<string> // probally not needed
#include<cctype>
using namespace std;
int main()
{
queue <char> str; //make it char queue
cout << "Please enter a string." << endl;
string temp, result = "";
getline (cin, temp); //grabs string, in... |
67,553,908 | 67,553,998 | 2d vector modify with iterator | I have a 2d matrix using vector library. And I wanted to iterate over the Matrix more conveniently, so I created an MatrixIterator class.
Matrix.cpp
#include <vector>
template <class T>
class MatrixIterator;
template <class T>
class Matrix
{
friend class MatrixIterator<T>;
private:
public:
std::vector<std::v... | You need to store a reference in the iterator class, other than hold a copy of it (iterator is just a view of the data).
template <class T>
class MatrixIterator {
private:
Matrix<T>& matrix_;
unsigned row_;
unsigned col_;
public:
MatrixIterator<T>(Matrix<T>& m) : MatrixIterator<T>(m, 0, 0) {}
MatrixIterato... |
67,554,318 | 67,554,641 | Unrecognized command line option ‘-mwindows’ | I am trying to cross compile my hello world app on C from Ubuntu linux for Windows platform. So, to compile the app I am using this Makefile:
CC = g++
IDIR = -Iinclude
SRC = src
CFLAGS = -Wall -Wextra
LFLAGS = -mwindows
main.out: main.o
$(CC) $(CFLAGS) $(IDIR) $(LFLAGS) $^ -o $@
main.o: $(SRC)/main.c
$(CC) $... | To cross compile for windows you would need mingw-w64 or use i686-w64-mingw32-g++
sudo apt-get install mingw-w64 For more info :
https://arrayfire.com/cross-compile-to-windows-from-linux/
|
67,554,745 | 67,555,205 | How to store value of pointer in a recursive function? | Let say now I would like to write a function that search a certain node in a linked list recursively. When I successfully reached the targeted node, this function will return the ID and another information of it by reference, where its ID will be stored by struct:
struct P{
int ID;
int some_info;
P* next... | Recursive:
void search(int targeted_ID, P*& current_node) {
if(current_node && current_node->ID != targeted_ID) {
current_node = current_node->next_node;
search(targeted_ID, current_node);
}
}
But I suggest a non-recursive version to not get stack overflow when searching a long linked list:
v... |
67,554,772 | 67,554,908 | Is oneline namespaces on one line with clang-format possible? | Is there a way to get clang-format to put oneline namespaces on one line like below? I need to do some forward declarations and I prefere to put it like this.
namespace One {
namespace Two { class MyClassA; }
namespace Two { typedef std::unique_ptr<MyClassA> MyClassAUPtr; }
namespace Two { class MyClassB; ... | No, as of clang-format 13, there is no such option.
|
67,554,923 | 67,554,953 | Struggling with the CreatWindow function | I am a beginner and I am trying to code my first game. I was following a tutorial that was made some time ago. This is my code:
#include <windows.h>
//Callback function
LRESULT CALLBACK window_callback(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
in... | You should use TEXT macro to express string literals when you use Windows API without explicitly specifying ANSI version (with A suffix) or Unicode version (with W suffix).
Wrong lines:
window_class.lpszClassName = L"Game Window Class";
CreateWindow(window_class.lpszClassName, "My First Game!", WS_OVERLAPPEDWINDOW | WS... |
67,557,041 | 67,557,748 | result with/without SSE simd operation is different | i'm trying to sum all the element of array (unsigned char)
but the result of cv::Mat sum is different from SSE result(below code)
with sse, sum of array result bigger than without, but why??
ex) i got 2042115 for sse sum, but cv::mat's sum results 2041104.
__m128i srcVal;
__m128i src16bitlo;
__m128i src... | You have 2 bugs:
i < nSrcSize can be true when the final vector extends past nSrcSize. Since you're already using signed int i, you can use i < nSrcSize - 15 to find the highest i value that can load a full 16 bytes from i+0 to i+15. Or use nSrcSize & -16U if you're using size_t.
new unsigned char[16]() doesn't zero ... |
67,557,172 | 67,557,389 | Garbage value received in client server communication c++ | I was trying to write a simple client server program on windows. My Server side code looks like below .
#include <iostream>
#include <windows.h>
#include <winsock2.h>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
int main()
{
WSADATA WSAData;
SOCKET serverSock, clientSock;
SOCKADDR_IN server... | char buffer[1024];
This declares a local char array in automatic scope. The array is not initialized anything, and contains random garbage.
recv(clientSock,buffer,int(strlen(buffer)),0);
This passes buffer to strlen. However, buffer contains garbage, this is undefined behavior, with the eventual results could be, ran... |
67,557,657 | 67,557,788 | Extracting the right values from strings | int a = 10;
int b = 5;
char test[]= "bread";
a = a + test[0];
cout << a << endl;
Basically i want to use the value of the integer b. In this example the first char of the string is a 'b' so i want to use the value of b and not the ascii value.
I tried casting it like this but did not work.
a = a + (i... | Variable names don't exist at runtime. You could use a std::map (or std::unordered_map) to associate names with values. Simple example:
std::map<char, int> variables;
variables['a'] = 10;
variables['b'] = 5;
std::string test = "bread"; // In C++ prefer std::string over char[]
variables['a'] = variables['a'] + variabl... |
67,557,845 | 67,558,700 | "static_cast" with pointers and objects in C++ | I've just learnt about inheritance and started using casting. While I was messing around trying to get to know the topic I found myself facing this problem which I couldn't explain. Here's the code:
#include <iostream>
#include <string>
using namespace std;
__interface AbstractClass {
void Eat()const;
void Slee... | As it was suggested you do not need to use casts when you want to get pointer to object to base class from the pointer to object to child class.
But it seems you want to call "Info" method of base class ("Employee") inside the body of "Info" method of the child class ("Developer"). It can be done in the following way:
... |
67,557,877 | 67,558,522 | What is the point of c++20 ranges? | I struggle to understand what c++20 ranges add compared to good old fashioned iterators. Yes, I guess there is no need to use begin and end anymore, but simple overloads such as:
namespace std {
template <typename Container>
auto transform(Container&& container, auto&&... args) requires ( requires {container.be... | You have argued against your own conclusion, as evidenced here:
template <typename Container>
auto transform(Container&& container, auto&&... args)
requires ( requires {container.begin(); container.end(); }) {
So... what is this? It's a function which takes a template parameter that satisfies a constraint. Let's ign... |
67,558,052 | 67,558,127 | Why can't some types (with array notation) be used as return type in C without typedef? | While messing around with the type syntax, I noticed this is legal :
typedef int *((* T)[10]);
T fun(){
return 0;
};
int main(int argc, char * argv[]){
//int c = fun(); // (1)
return 0;
}
...And if you uncomment (1), then you get an error message of this kind (GCC / Clang) : "error: cannot initialize a variabl... | int *((*fun())[10]) {
return 0;
};
... Yup. You should probably stick to the typedef for the sake of readability :)
|
67,558,125 | 67,558,616 | Determine the 'owner' of an object | I want to determine which object 'owns' some other object.
I have a situation similar to the code below. Filling in the blanks, it compiles and seems to do what I expect - but will this work in general? Is there some idiomatic way to do this? Or is ill-advised altogether?
#include <functional>
#include <vector>
#includ... | The problem that you have is that each of the struct A through D all are composited in memory. Honestly, the real problem here is, how on earth do you come up with that pointer you are feeding to superfoo to begin with? If it came from one of your objects, then can you not tag it as such.
That's really a design probl... |
67,558,188 | 67,558,412 | reading numbers from line in a file in C++ | I have this function process_input that basically gets a line of a file and prints the numbers of the line, if it has 2 numbers it prints those numbers and 0 else it prints the 3 numbers.
My problem is that for some reason its printing the lines repeatedly with a -1 token and I get why. Is there any error in my logic o... | Problem is that once you enter numbers in a loop you are not clearing your stdin buffer. You have mix of C and C++ here.
in C++ you would do this:
while (fgets(line,6,stdin) != NULL)
{
tokens = sscanf(line, "%d %d %d", &x,&y,&w);
printf("%d %d %d - tokens: %d\n",x,y,w,tokens);
std::cin.ignore();
std:... |
67,558,190 | 67,571,548 | How do I define an exported constant? | I've been trying the new modules feature, but I'm unable to export a global constant. The exporting seems to compile fine, but when importing the compiler complains that the constant is not declared. My code:
test.cpp
export module test;
export struct my_type { int x, y; };
export constexpr int my_constant = 42;
expor... | const-qualified variables have internal linkage by default, so it might be necessary to write it as
export extern const int my_constant = 42;
According to https://en.cppreference.com/w/cpp/language/storage_duration the export definition should make the variable have external linkage, so you might have hit one of the c... |
67,558,340 | 67,559,598 | Overload operator + for custom vector class | Everyone.
I have a problem. I want to sum two vectors by overloading operator +, and assign result to third vector. But when i sum values of two vectors i save results in temporary vector, and in the end i return that vector. But when sums are done that temporary vector calls destructor and values are deallocated. How ... | Changed Code a little bit. Thanks all for answers.
template <class T> class Vector
{
private:
unsigned x; // used to store size of vector
T *vector;
public:
Vector();
Vector(unsigned x);
Vector(std::initializer_list<T> list);
Ve... |
67,558,408 | 68,271,236 | Can't switch from Local Windows Debugger to Local Machine (VS 2019) | i'm creating a C++/XAML (UWP) app. Initially, i saw as debug default "Local Machine", but now i see "Local Windows Debugger" and when i debug my application the compiler find many exceptions in the file called "base.h". So i tried to reswitch to "Local Machine", but i never saw the element in "Configuration Property" m... | What you have to do is just open your .vcxproj.user file for edit and change "WindowsLocalDebugger" value to "GamingDesktopDebugger" (it is located in the DebuggerFlavor field).
|
67,558,447 | 67,558,478 | How to delete element from list in c++ | I am currently making a singly linked list in C++
Now I'm trying to make a function showList that prints the content of the list and if it is empty, prints "Empty list". However, right now it prints the list and "Empty list" every single time. When the list is empty, it prints an empty line and in new line "Empty list"... | Assuming you mean an empty list is a list where head is nullptr, you could check it explicitly:
void showList(const Node<T>* head) {
if (head == nullptr) {
std::cout << "Empty list"<< std::endl;
return;
}
while (head != nullptr){
std::cout << head->data << " " ;
head = hea... |
67,558,538 | 67,560,479 | Vector element duplication when capacity is reached | In the program as follows:
#include <vector>
#include <memory>
#include <iostream>
int main()
{
std::vector<std::shared_ptr<int>> v{ std::make_shared<int>() };
for ( auto i = v.capacity() - v.size() + 1; i-- > 0; )
v.push_back( v.back() );
for ( auto i = v.capacity() - v.size() + 1; i-- > 0; )
... | v.insert( v.end(), --v.end(), v.end() ) exhibits undefined behavior, by way of violating prerequisites of the standard library function. Table 87 in [sequence.reqmts]/4 says, among other things:
a.insert(p,i,j)
Requires: i and j are not iterators into a.
v.push_back( v.back() ); is guaranteed to work, I believe. See... |
67,558,962 | 67,563,567 | Indirect virtual base without a default ctor stops children from having a default ctor, unless every class in between also has one | I'm sorry for the obscure title, not sure how to word it better.
Consider following inheritance hierarchy:
struct A
{
A(int) {}
};
struct B : virtual A
{
B() : A(42) {}
};
struct C : B
{
C() : A(43) {}
};
It does work. Now let's say I want to create a template that can be transparently injected in the mi... | [special]/7:
For a class, its non-static data members, its non-virtual direct base
classes, and, if the class is not abstract ([class.abstract]), its
virtual base classes are called its potentially constructed
subobjects.
[class.default.ctor]/2.7 says that a defaulted default constructor is defined as deleted if
any... |
67,559,234 | 67,559,662 | Check if a tuple dominates another tuple in C++11 | I would like a function bool dominates(const std::tuple<T...>& t1, const std::tuple<T...>& t2) which returns true iff tuple t1 dominates tuple t2, i.e. for all i, t1[i] <= t2[i], in contrast with the default <= operator which uses a lexicographic comparison.
I've tried to adapt the answer from this question, but withou... | The problem in you code is in dominates_impl()
template<typename H, typename... T>
bool& dominates_impl(bool& b, H&& h1, H&& h2, T&&... t1, T&&... t2)
you can't have two variadic argument list of argument in a function; you can have only one in last position.
But you don't need dominates_impl() at all: you can emulate... |
67,559,345 | 67,559,413 | using delcaration to inherit constructors from all base classes given by variadic template arg | If I derive from one or more classes I can inherit the constructors with the using declaration.
Example:
struct A
{
A(int){}
A(){}
};
struct B
{
B(char){}
B(){}
};
struct All: public A,public B
{
using A::A;
using B::B;
};
If I want do the same within a template class, where the base classes ... | template < typename ... P>
struct All2: public P...
{
using P::P...;
};
|
67,559,519 | 67,560,025 | Why i get a SIGSEGV error on push_back(T&&) when T=std::string custom Vector C++ | #include <algorithm>
#include <utility>
#include <new>
#include <iostream>
template <typename T>
class Vector {
public:
Vector();
~Vector();
void push_back(const T& value);
void push_back(T&& value);
void clear();
std::size_t size() const { return sz; }
std::size_t capacity() const { ret... | The error is not in the using push_back(T&&). The reason is in the data that points to an uninitialized memory.
data[sz++] = value; calls T::operator=(const T&) on an uninitialized object T.
data[sz++] = std::move(value); calls T::operator=(T&&) on an uninitialized object T.
You should fix assignments data[sz++] = in t... |
67,559,556 | 67,559,949 | How to cleanly do formatted string concatenation in clang++ | I'm using clang++ on Windows to do some very basic SDL2 stuff, but I just found out that Clang++ doesn't come with the <format>, nor "fmt" out of the box.
What I need is a more pretty way to concatenate a bunch of formatted strings, that would have been trivial elsewhere, and although I managed to get it to work I'm un... | Would something like this be acceptable?
// Old Way
std::string getInfo() {
char ver[200] = "", verInfo[200] = "";
sprintf (ver, "Compiled using SDL version : %d.%d.%d \n", compiled.major, compiled.minor, compiled.patch); strcat (verInfo, ver);
sprintf (ver, "and linked with SDL version : %d.%d.%d \n", li... |
67,560,224 | 67,560,259 | strchrnul on visual studio c++? | I recently received an old source code from a port scanner program that worked in the old Visual Studio, but this source does not work in Visual Studio 2019.
p = strchrnul(h, ',');
The strchrnul function is not inside the string.h header file.
Can any of you help replace this function ? I have no knowledge of text in ... | You can write your own strchnul() implementation easily enough:
char * strchnul(const char * s, int c)
{
while(*s)
{
if (c == *s) break;
s++;
}
return const_cast<char *>(s);
}
|
67,560,402 | 67,563,125 | Initializing tesseract API's TessBaseAPI to api pointer with C++ giving error | I am using the latest Tesseract API for C++ and I followed the last answer on this post to link what is necessary. These are my includes:
#include<iostream>
#include<Windows.h>
#include<opencv2/opencv.hpp>
#include<stdint.h>
#include<tesseract/baseapi.h>
#include<leptonica/allheaders.h>
When I try to initialize the ap... | Try compiling it with VS2019. The recent builds of Tesseract were built with VS2019.
|
67,560,508 | 67,560,547 | How can one shorten the code when reading input? | int testcases;
cin >> testcases;
Is there a way to shorten the above to one line? Or more generally, can anyone provide me a good resource where I can read about code shortage that doesn't necessarily affect the readability?
| There isn't a whole lot to shorten there; however if you were going to be writing many instances of the above, you could write a helper-function like this:
int readInt()
{
int i;
cin >> i;
return i;
}
... then your many instances could be just one line apiece:
int testcases = readInt();
|
67,560,871 | 67,560,943 | How can I create and add a unique_ptr to a vector in a method? | I am trying to use polymorphism to represent a tree of sorts (terminal and non-terminal nodes for a parser). One of the classes Node holds a vector of smart pointers to subclasses of Base. I'd like to add more nodes to this vector with a method that accepts just a Node reference without having to create the smart point... | How do you want to move const object?
It should be:
void addNode(Node &&node) {
nodes.push_back(std::make_unique<Node>(std::move(node)));
}
by move, you modify moved instance, so it should be modifable.
Demo
|
67,561,218 | 67,561,435 | Issue when comparing lpcs->lpszName with other value like "OLEChannelWnd" in a WH_CBT callback | Below is the code of my WH_CBT callback. I am trying to ignore any click of a hyperlink in Outlook. When I click a hyperlink in Outlook, I'm getting a message box:
But when I return 1 in the callback without the if condition, it works fine.
LRESULT __declspec(dllexport)__stdcall CALLBACK GetCBTProc(int nCode, WPARAM ... | Your code is missing two return statements, one on the CallNextHookEx(), and one at the end of the callback. So, the return value of the callback is indeterminate unless the input string matches your criteria. Your compiler should have warned you about the second missing return. A function with a non-void return type m... |
67,561,292 | 67,561,405 | Getting the PID of foreground window | I'm writing an app that does actions depending on the current context. My goal is to get the path for the EXE that's currently running in the foreground. For this to work, I need to get the process handle for the foreground window. The problem is, with GetForegroundWindow() I get back a window handle, and for OpenProce... | You can use GetWindowThreadProcessId:
HWND hWnd = GetForegroundWindow ();
DWORD process_id;
GetWindowThreadProcessId (hWnd, &process_id);
It's not immediately obvious how this function reports error conditions.
|
67,561,571 | 67,561,605 | If-then-else vs ternary operator when returning full or empty std::optional | (I've not found much by searching for return statement, return deduce, and similar, with tags c++optional.)
Why does this work
#include <optional>
auto const f = [](bool b) {
return b ? std::optional<int>(3) : std::nullopt;
};
while this doesn't?
#include <optional>
auto const f = [](bool b) {
if (b) {
... | Lambda return type deduction require the type of all return expressions match basically exactly.
? does a relatively complex system to find a common type of the two cases. There is only one return statement, so so long as ? can figure it out, lambda return type deduction doesn't care.
Just different rules.
auto const ... |
67,561,729 | 67,572,934 | find the minimum value entered while using infinite loop c++ | My task is to find the minimum number between n input values that the user should enter in an infinite loop until a certain number or character is entered to stop the loop.
The problem that I am facing is, I can't get the condition that tests the input to see which of the entered numbers is the smallest to work. Also, ... | the problem with the code was with the header I couldn't find a one that was working with my compiler Borland v5.02 c++ but thanks to @JerryJeremiah he leads me to it.
also, I redeclared the min =INT_MAX; because I am using this code in a loop.
the code is working with me now.
#include <iostream>
#include <conio.h>
#in... |
67,561,767 | 67,562,019 | C++ Windows - How to correctly detect if the keyboard layout is QWERTZ or AZERTY? | I have got the following keyboard layouts in system:
I created the following QWERTZ / AZERTY detection function:
bool bIsAzertyKeyboard = false;
bool bIsQwertzKeyboard = false;
bool bIsQwertyKeyboard = false;
void DetectKeyboardType() {
bIsAzertyKeyboard = false;
bIsQwertzKeyboard = false;
bIsQwertyKeyboar... | Looks like I solved it!
Replacing:
switch (PRIMARYLANGID(LOWORD(GetKeyboardLayout(0))))
to:
switch (PRIMARYLANGID(HIWORD(GetKeyboardLayout(0))))
does the trick! I was attempting to use the "SUBLANGID" instead, but that's something else.
|
67,561,876 | 67,562,708 | In Binary search tree program Codeblock is printing weird characters | I was making program which can take postfix expression and then will create a binary expression tree of that expression .My program was running perfectly .I was testing my program by copy /pasting some samples postfix expression but the problem is now it is not printing inorder, post order and preorder but infact it is... | You don't initialize leftChild and rightChild members of BTnodes you allocate. These pointers contain random garbage; they are generally not NULL.
When you traverse the tree, you eventually descend down to a leaf node and then attempt to traverse further down through these garbage pointers. Whereupon the program exhibi... |
67,562,077 | 67,567,915 | How I can safely reference to an std::vector element? | I will like to create a struct that holds a higher state for other structs.
I tried to create it like this, but I recently found that returning a pointer to an element of an std::vector is not safe, since that pointer can change.
struct Foo {
std::string &context;
std::string content;
Foo(std::string &context, s... | You can have vector of shared_ptr & return weak_ptr, this way you can make sure correct referencing
#include <iostream>
#include <vector>
#include <memory>
struct Foo {
std::string &context;
std::string content;
Foo(std::string &context, std::string content) : context(context), content(content) {}
};
str... |
67,562,187 | 67,562,401 | Qt 6.1.0 MinGW Include ERROR with “__imp__ZN13QStateMachine…” | Here I'm using Qt Creator and today when I tried to compile this code it happened to cause some errors.
code:
#include "mainwindow.h"
#include <QApplication>
#include <QPushButton>
#include <QGraphicsItem>
#include <QtStateMachine/QState>
#include <QtStateMachine/QStateMachine>
int main(int argc, char *argv[])
{
... | In Qt6 QStateMachine (and the other similar classes) belong to the QtStateMachine submodule, no longer to the QtCore submodule, so add QT += statemachine to the .pro.
|
67,562,435 | 67,562,492 | linux sockets cpp recv() - cant recv fully data via http | I'm making this socket HTTP client (very basic). When recv()'ing response data from example.com it works fine and writes it all to a buffer but when I try to revc any bigger amounts of data it stops at around 1500 bytes.
Right now all I'm trying to do is get the response written into the buffer (headers and all). Not t... | You seem to expect the server to close the connection after the response is transmitted. A typical HTTP 1.1 server doesn't do that by default; they keep the connection open for further requests, unless the client explicitly asks otherwise via Connection: close header.
So, you receive all the data, and then the next rec... |
67,562,479 | 67,591,335 | Getting C to wok with assembly | Im working on a simple OS, for the past 3 weeks ive been debugging an error that only arrises when i call c++ or c code in assembly, qemu (the emulator im using), will start flickering and wont load code. I have already tried this with other emulators.
"Bootloader.asm"
[org 0x7c00]
mov ah, 0x00
mov al, 0x03... | I found the error, i was not reading the sector that held the C code, if you are reading this with this problem, make sure you are reading all of your sectors.
|
67,562,723 | 67,562,807 | Why is the empty constructor called in this case? | I'm a beginner in C++ and I have a hard time understanding this program from an exercise book, specifically why is the empty constructor called 6 times in total:
#include <iostream>
class Allo{
public:
Allo(int x_=0)
: x(x_)
{
std::cout << "A" << x << " ";
}
Allo(const Allo& autre)
: x(autre.... | Preface: A is a regular constructor, B is a copy constructor, C is a destructor (not a constructor).
Let me break down each line:
Allo tab[3];
3 objects constructed with constructor A initalized with x = 0. These are stack allocated.
Allo a(20);
1 object constructed with A, x = 20. This is stack allocated.
Allo* b = ... |
67,563,069 | 67,563,238 | Duplicate Symbols Error - Am I doing my includes right? | I am working on a project with several modules and I'm getting a lot of duplicate symbols errors. I've tried to create a stripped-down version of my project to diagnose the error.
I have the code and dependency structure below. Every .hpp and .tpp file has header guards, but I'm getting duplicate symbols errors from My... | Both of the .cpp files include, indirectly, BaseSpec.tpp which defines:
void Base<int>::hello_base() const
That's your violation of the One Definition Rule, that results in a duplicate symbol link failure.
Removing BaseSpec.tpp, and replacing it with a .cpp file, with the same contents, should make the linkage error g... |
67,563,255 | 67,565,222 | Python failing to load boost.python dll | I'm having some problems with a trivial boost python setup.
I have seen a lot of other people have had problems, but none of them seem to be the same issue as mine, as none of their resolutions worked.
For reference, I am on windows 10, using mingw64 10.2 as part of msys2 for my c++ compiler. I built boost using that c... | I followed the tutorial here following doqtor's comment, and found that the problem was python not loading several dlls that were runtime dependencies of PythonBindings.pyd.
This was fixed by adding
import sys
import os
[os.add_dll_directory(dir) for dir in sys.path if os.path.isdir(dir)]
before import PythonBindings
... |
67,563,443 | 67,564,079 | How can i put function with different parameters into map in c++? | I need to design a map, which save all function i may use in the futures.
all the functions will have double as its return value.
and all function share a common parameters const std::vector<float>&
so i define the map as:
typedef std::function<double(const std::vector<float>&)> func;
std::unordered_map<std::string, fu... | What you're asking is essentially the same as:
How can I store both int and float in a map and use them equally?
Functions with different parameters are simply different. A map can only hold a single type. Suppose you get function "2019", how will you or the compiler ever know what kind of function it is?
There are a c... |
67,563,497 | 67,563,546 | C++ cannot use template template class with class member | I am possibly misunderstanding the template template classes and their use in C++. With the following declaration:
template <typename Parameter>
class A { Parameter p; };
template <template <typename> typename Class, typename Parameter>
class B { Class<Parameter> q; };
B<A, int> b;
b.q.p = 0;
I can declare a variabl... | The code you have written is correct and valid -- up until the assignment.
The reason that b.q.p = 0; fails is because class definitions default to private accessibility for all member definitions, so:
template <typename Parameter>
class A { Parameter p; };
template <template <typename> typename Class, typename Parame... |
67,564,304 | 67,564,539 | Friend classes across different namespaces not working and namespace is not recognized | I am having trouble with the use of friend class in C++
I am forward declaring the friend class and using the appropriate namespaces, so I don't know what is going on.
Inside class MeshNamespace::Mesh , ReferenceElementNamespace::ReferenceElement 's members are still unable to access private members of the former. Be... | What I know:
Forward declarations in (other) namespaces are supported.
Forward declarations of nested classes are not supported.
OP wrote:
class MeshNamespace::Mesh;
class OtherClass {
friend class MeshNamespace::Mesh;
};
to forward declare a class Mesh in a namespace MeshNamespace.
It could be as well a class Mesh... |
67,564,842 | 67,571,653 | Replace sizer of a wxFrame in wxWidgets | I am writing a small Minesweeper game just to get familiar with wxWidgets (Windows, wxWidgets 3.1.4). The app can handle one game well, and now I would like to add the "new game" functionality. For the layout, I am using a wxGridSizer.
My first approach was to create a new wxGridSizer with the new fields in it, and jus... | To replace the sizer, you just need to make one small change to the MyFrame::OnRefill method.
Instead of calling sizer->Layout(); simply call Layout();. I'm not entirely sure why calling Layout for the sizer doesn't work.
The full method looks like this:
void MyFrame::OnRefill(wxCommandEvent &) {
Freeze();
GetSize... |
67,565,490 | 67,565,640 | what is the matching function to call for push_back here refers to? | #include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution
{
// you only need to find one solution , thats why we used break
public:
vector<int> twoSum(vector<int>& num,int target)
{
vector<int>result;
for(auto i = num.data();i!=num.data()+num.size();++i)
... | vector<int> data() is of type int * see https://en.cppreference.com/w/cpp/container/vector/data, you used auto to declare i from that, so it is also an int *
result.push_back(i-num.data()); is doing a difference of two pointers, that is fine.
result.push_back(i); is doing something weird (trying to insert an int pointe... |
67,565,493 | 67,565,529 | Why does `(void *)&` get the address of the variable? | Could someone explain the logic behind this? Why void? For example
#include <iostream>
using namespace std;
int main()
{
char c;
cout << (void *)&c;
return 0;
}
| cout << (void *)&c;
takes the address of c, then casts it to void*, then prints pointer.
The intent here is to print the address of variable c. But when passing a char * to std::cout << it will attempt to print a null-terminated string. To avoid this (and print the actual address) you have to cast to void* first.
Mo... |
67,565,866 | 67,565,969 | What is the latest MSVC that support C++ 20, 19.28 or 16.9? | I saw that MSVC supports better than other compilers if I want to develop c++ 20 (in windows). And I found this in cppreference.com. But when I searched what is the latest Visual C++ version, I found that 16.9 is the latest version. But in cppreference.com it is saying that 19.28 is the latest version. So, what is the ... | It's slightly complicated...
The latest version of Visual Studio is 16.9.5 as of now. If you download that, you will have MSVC version 14.29 and the macro _MSC_VER will be defined as 1929. Fortunately, you don't have to keep track of these for the most part to start out. Just install Visual Studio and get started.
|
67,566,001 | 67,566,233 | How to use map as data type inside multiset in C++ | I am trying to use a map data type structure for multiset. This is my code below
#include <iostream>
#include <set>
#include <iterator>
#include <map>
#include <functional>
using namespace std;
int main()
{
map<string, int> student_marks_map;
student_marks_map["Student1"] = 100;
student_marks_map["Student2"]... | None of the two parameter insert members of multiset construct a value from the parameters, and even if they did, 1, 4 can't initialise a map<int, int>.
If you want a map with the single element 1, 4, you need to specify that
multiset_map.insert(map<int, int>{{1,4}});
|
67,566,043 | 67,566,065 | While C++ gave result different from what I expected | I am new to C++ and currently trying to learn WHILE loop.
But there is a problem I don't understand about my code that gave me a result different from what I expected. Here is it:
int i = 1;
double ans = 1.00;
while (ans > 0.1) {
ans = 1 / i;
i++;
}
cout << "ans: " << ans;
I am expecting to have: ans : 0.1, but is... | The decision on whether to do integer or floating point division depends on the type of the operands.
Unless at least one of them is of floating point type, you will have an integer division.
The type of the variable you assign the result to does not matter.
|
67,566,228 | 67,566,355 | Make iostreams more strict | Is there a way to make iostreams more strict about boolean values with some flag?
I got unexpected result using std::boolalpha
bool var;
std::istringstream is("true1");
is >> std::boolalpha >> var;
yields var == true, is.good() == 1 and is.peek() == '1', when I expect is.good() == 0.
Similar behavior when there is no ... | No, there is no way to make iostreams more strict in this way.
There is no need either. Simply use is.peek() for example to check whether the entire input was consumed or not. If not, then treat the input as bad, and retry (or whatever you wanted to do in case is.good() == 0).
|
67,566,350 | 67,566,987 | How to check that multiplication of two decimal numbers is greater than ULONG_MAX? | I need to write a function that returns true if the multiplication of two numbers is greater than ULONG_MAX limit. Otherwise returns false.
I tried the following method:
bool isGtThanULONG_MAX(double A, double B) {
double result = A * B;
if (result > ULONG_MAX)
return true;
else
{
//If t... | There is a problem if ULONG_MAX cannot be represented exactly as a double. For example if type double uses IEEE representation and long has 64 bits, ULONG_MAX be rounded to the next power of 2 when converted implicitly to double type for the comparison. Hence if this happens, the comparison should be result >= ULONG_MA... |
67,566,376 | 67,566,882 | Designing the game loop | I'm developing a simple Win game. Here is my 2 similar implementations of the game loop (in c++):
approach #1:
while (Msg.message != WM_QUIT) {
if (PeekMessage(&Msg, NULL, 0, 0, PM_REMOVE) > 0) {
TranslateMessage(&Msg);
DispatchMessage(&Msg);
}
else {
// Do u... | The answer entirely depends on the use-case.
In your first approach you handle any messages in the queue before you update your game status. That might spare you some updates provoked by older messages that got obsolete by more recent ones.
On a heavily loaded queue, though, this might result in your application being ... |
67,567,985 | 67,568,219 | Why does modulo division go wrong for mix of size_t and unsigned int in C++ | Given a program
#include <iostream>
using namespace std;
int main()
{
const size_t DoW = 7;
const unsigned int DAYS_OF_WEEK = static_cast<unsigned int> (DoW);
unsigned int dayOfFirstDay = 0;
unsigned int _firstDayOfWeek = 1;
unsigned int diff = (DAYS_OF_WEEK+ (dayOfFirstDay - _firstDayOfWeek) ... | It seems on your platform size_t is 64-bit, and unsigned int is 32-bit.
There is no integral promotion to 64-bits1. This is the danger of mixing 64-bit operands in expressions.
So a 32-bit wraparound of -1 remains as 4294967295 when converted to 64 bits.
And we get 7 + 4294967295 (performed in 64 bits) = 4294967302 (no... |
67,568,310 | 67,569,032 | What series of intrinsics will complete this paeth prediction code? | I have a Paeth Prediction function which operates on arrays:
std::array<std::uint8_t,4> birunji::paeth_prediction
(const std::array<std::uint8_t,4>& a,
const std::array<std::uint8_t,4>& b,
const std::array<std::uint8_t,4>& c)
{
std::array<std::int16_t,4> pa;
std::array<std::int16_t,4> pb;
std:... | _mm_cmpgt_epi16 can be used for the comparisons. Note that _mm_cmpgt_epi16(a, b) = !(a <= b), however _mm_cmpgt_epi16(b, a) != (a <= b), because it is not a Greater or Equal comparison but a strict Greater Than comparison. So the masks come out inverted, but that's equally useful in this case, an explicit inversion won... |
67,568,929 | 67,570,116 | Storing child object in parent object | i am dealing with a c++ school project. i want to store child card object inside parent card object in main function because i need to set card inside the library (std::vector<card> _library;) as same type.
what i need to use in main function to store child classes inside parent classes?
definition of classes and main ... | Nobody answered yet, but a common approach to this is either dynamic polymorphism. Possible implementation:
std::vector<std::unique_ptr<card>> allCards;
allCards.push_back(std::make_unique<enchantment>("foo", "bar"));
std::vector<card*> in_hand; // only has references to the existing card objects.
in_hand.push_back(al... |
67,569,057 | 67,569,998 | How to save state before application crashed in C++? | I want to manage core (crash) in my application which is writen in c++. When it crashed (or before) i want to save the state so in the next start it will not start from the beginning i wan't to continue just after where it stopped. Using file to save the state will consume alot of time as i may have alot of states upda... | You can use std::signal to run a custom function when SIGSEGV is emitted, just before the program ends. Keep your data in a globally accessible structure and save it within this custom function.
#include <csignal>
#include <iostream>
#include <vector>
struct GlobalState {
static std::vector<int> results;
... |
67,569,244 | 67,569,719 | How to link an external library with CMake project | I made a Non-Qt project, Plain C++ Application in QT creator. My current folder structure is like this:
.
├── client
│ ├── client.cpp
│ └── client.h
├── CMakeLists.txt
├── CMakeLists.txt.user
├── main.cpp
└── server
├── server.cpp
└── server.h
My CMakeLists.txt file looks like this:
cmake_minimum_required(... | Linking a library of an executable in CMake is achieved by using the target_link_libraries function. In your case,
target_link_libraries(eshraagh-project PRIVATE cpnet)
Here, cpnet could be the name of a target that you CMake project knows (otherwise, it is turned into some kind of platform specific -lcpnet linker fla... |
67,570,658 | 67,570,916 | -Wstrict-overflow doesn't produce any warnings where it clearly should | According to the g++ man-page and their website https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html , the following code should produce a warning when compiled with -O3 -Wstrict-overflow=5 :
#include <iostream>
#include <limits>
int
main() {
int x{std::numeric_limits<int>::max()};
if(x+1 > x) std::cout << ... | This is definitely a bug introduced between GCC 7.5 and 8.1. Be sure to report it. This particular example is even in the docs.
|
67,570,779 | 67,571,182 | Functions that differ only in their return type cannot be overloaded | Note: Although question is duplicate, but current answers lacks details, so I wanted to post another one.
I'm using C++Builder developed by Embarcadero.
For Windows, it compiles fine.
For Android, it shows the following error:
Checking project dependencies...
Building Project3.cbproj (Debug, Android)
bccaarm command li... | my bet is that you need to use "Preprocessor directives" in your code and indicate platforms
How do I check OS with a preprocessor directive?
https://www.cplusplus.com/doc/tutorial/preprocessor/
|
67,570,821 | 67,570,985 | How to specify a range for begin() and end() iterators to find first value of sub vector in a vector of vectors? | Hi I'm new to working with vectors and other parts of STL and I would like some help please, I have a vector of string vectors, containing a topic at the index of each sub-vector
e.g arr[1][0] = "topic1", with arr[1][1..n] containing messages related to "topic1",
To find the value of the topicID, the index of the subve... |
How can I refactor this to check only the element at arr[i][0] for the length of arr?
Simply don't loop over all of the elements (std::find being the unnecessary inner loop). Replace body of the outer loop with:
if (arr[m][0] == topic) {
return m;
}
and after the loop:
return 0;
P.S. You can replace the outer ... |
67,571,531 | 67,571,647 | Output non-null terminated char array behaviours? | char sentence[] ={'k','k','k','k','k','k','k','k'}; (8 character)
std::cout << sentence << std::endl;
Then output just "kkkkkkkk".
But if we decrement characters of array (i.e. preceding array have 8 character after less 8 character)
char sentence[] ={'k','k','k','k','k','k','k'}; ( 7 character)
std::cout << sent... | The operand sentence decays to a pointer to first element of the array. The stream insertion operator overload that accepts const char* parameter requires that the pointer is to a null terminated array. If that pre-condition is violated, then the behaviour of the program is undefined.
sentence does not contain the null... |
67,572,453 | 67,572,778 | Why is abs not in std? | #include <cmath>
int abs;
int main()
{
}
This code throws the compilation error
error: 'int abs' redeclared as different kind of symbol
note: previous declaration 'int abs(int)'
The same thing happens if I include it from cstdlib.
I read this documentation https://en.cppreference.com/w/cpp/numeric/math/abs
where it ... |
Why is abs not in std?
Your question is slightly wrong. abs is in std. Let me assume that you're asking "Why is abs also in the global namespace?".
The C++ standard allows the C standard functions to be declared in the global namespace in addition to being declared in the std namespace.
Why is this happening?
Becau... |
67,572,993 | 67,573,179 | How to make sure that a variable is not used | Question
I have a function f taking some argument a, how can I make sure that the variable a is not used inside of the body, in the best case via a compile error? E.g., the following should not compile
void f( int & a ) {
UNUSED( a ); // some magic rendering the variable a unusable
++a;
}
Story of the questio... | C++ allows you to have unnamed function parameters. It's exactly useful for situations where you do not intend on using the corresponding parameter, yet must declare it to match the signature e.g. when writing a callback to some library.
Simply redefine your function:
void f(int&) {
// code ...
}
|
67,573,069 | 67,573,144 | Modify and append extra lines in a file | I'm a bit stuck in opening a file and modify it in Qt.
I have got a file that has some contents. Now I want to open it and add a few more lines to it.
For example, here I open the file
void MainWindow::on_pushButton_readlog_clicked()
{
QString filename = "logfilename.txt";
QFile originalFile(filename);
if(... | make a new file and copy content (write) to original file + mods, delete new file or old and rename new.
https://www.cplusplus.com/reference/fstream/ofstream/
https://www.codevscolor.com/c-plus-plus-delete-a-file
https://cplusplus.com/reference/cstdio/rename/
maybe this can be of use for you ... much easier.
#include <... |
67,573,252 | 67,573,324 | Why there is a limitation that c++ 'auto' cannot stand for multiple types | I mean, why the following example is not a valid construction:
if (auto x = 2, y = "ab"; x != 0) {
// ...
}
(In my real use case there are calls to some functions instead of 2 and "ab" literals.)
or
std::vector<int> cont1;
std::vector<char> cont2;
for (auto it1 = cont1.begin(), it2 = cont2.begin(); it1 != cont1.end(... |
So here, auto stands for different types.
I wouldn't interpret it that way.
The auto stands for std::pair<int, char const*>. However, the special thing here is that the name of the pair is [a, b], where a and b refer to the inner members of the pair. I would really like if the language would allow typing the type of ... |
67,573,291 | 67,573,609 | Problem with reference variable as function parameter in c++ | I have declared a class as :
class Actuator
{
public :
enum class Action
{
/*my enum member*/
};
private:
/* my data member*/
public :
Actuator(uint8_t number);
Actuator(uint8_t number, String& relay_config_string, String&... | What you are doing here:
ac.set_state(app_cmd.get_command_parameter().substring(2), false);
ac.set_relay_config(app_cmd.get_command_parameter().substring(2));
is you are passing a pr-value of the String type returned by substring() method, see:
https://en.cppreference.com/w/cpp/language/value_category
R-value cannot b... |
67,573,305 | 67,573,947 | Why does views::reverse not work with iota_view<int64_t, int64_t> | I have the following C++ program, and for some reason I can not use int64_t as template argument.
#include <iostream>
#include <ranges>
template<typename T>
void fn() {
for (auto val : std::ranges::iota_view{T{1701}, T{8473}}
| std::views::reverse
| std::views::take(5))
{
... | This is a libstdc++ bug, submitted 100639.
iota is a surprisingly complex range. In particular, we need to pick a difference_type that is sufficiently wide for the type that we're incrementing to avoid overflow (see also P1522). As a result, we have in [range.iota]:
Let IOTA-DIFF-T(W) be defined as follows:
[...]
Ot... |
67,573,550 | 67,573,735 | Use large arrays inside c++ class | This is how my class looks. My code compiles successfully but when I run it, it crashes and stops.
class Explore{
public:
Explore(ros::NodeHandle &nh, tf2_ros::Buffer &buffer);
private:
bool is_frontier(size_t mx, size_t my);
void explore_level_three();
void go_to_c... | Most probably you are creating an object of Explore on stack which would be giving a Segmentation Fault. You should declare the object dynamically on heap
int main() {
Explore * obj = new Explore(...);
delete obj; //since obj is on the heap,
//you have to take care of delete. using smart pointe... |
67,573,557 | 67,573,704 | How to manage layout on QDockWidget? | I'm getting started with Qt and I have a project for my school. I want to make an interface that read a database of space-stuff and displays them.
Until now I can display the table in a list, and my actual goal is to show the details of the object when it is double clicked.
To do so I tried to open a second dock whenev... | If you want to add several widgets to a QDockWidget then you must use a QWidget as a container:
dock1 = new QDockWidget(tr("Caractéristiques de l'objet : "), this);
dock1->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
addDockWidget(Qt::RightDockWidgetArea, dock1);
QWidget* container = new QWidget;... |
67,573,614 | 67,573,686 | how to deduce template parameters for the end regex_token_iterator on the begin one? | How to write the following so-called mini-reproducable example in which the begin iterator may be constract either on the base of std::string_view or std::string.
So, let's say that we have the following programme:
#include <iostream>
#include <string>
#include <regex>
#include <iterator>
#include <string_view>
int ma... | You're thinking way too deeply. You don't need the template parameters; the type you're trying to test against is the same type as it. So just use that:
it != decltype(it)()
|
67,573,682 | 67,579,169 | set function with unique pointer is giving error c2280 | When I try to run the below code, I am getting this error message:
Error C2280 'std::unique_ptr<int,std::default_delete<int>>::unique_ptr(const std::unique_ptr<int,std::default_delete<int>> &)': attempting to reference a deleted function
How can I fix this error?
#include <memory>
#include <vector>
#include<iostream>... | It's easy to fix with change this line:
vecvec.push_back(std::move(vec.at(i)));
You need to move the unique_ptr but not the default the copy behavior, unique_ptr is move-only but not copyable. For shared_ptr, it's copyable and moveable, so if you change it to shared_ptr it works.
By the way, you have forgotten to add ... |
67,574,412 | 67,574,510 | How to merge char element of a vector into a string element | I have two vectors. One char vector contains elements which each element stores a character of a paragraph (including dot . The other is a string vector whose each element should store a word created from the first vector.
Here is my code:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int... | If the problem is to create a vector of words from the string source there are simpler ways.
For example if you remember that the input extraction operator >> reads "words" (space-delimited strings) then you can use it to your favor with an input stream that can read from strings, like std::istringstream.
And if you le... |
67,574,731 | 67,609,502 | Diffie Hellman key exchange between C# and C++ on Windows | I want to use the Diffie Hellman algorithm to securely exchange keys between a C++ server an a C# client which both are running on Windows. I tried using ECDiffieHellmanCng in C# to generate a public key as follows:
ECDiffieHellmanCng diffieHellman = new ECDiffieHellmanCng
{
KeyDerivationFunction = ECDiffieHellmanK... | Since I simply wanted an encrypted connection, going with OpenSSL was the way to go.
|
67,575,252 | 67,575,326 | C++ execute function without if check each time | Lets say I have a bool variable(global or local) & a function which is present. The function should execute only when the bool variable is true. Since this function is repeated many times & I need a way to execute this function without performing if the bool variable is true everytime.
function();
bool executeFun = tru... | Wrap it in another function.
auto perhaps = executeFun ? function : +[](){};
perhaps();
perhaps();
perhaps();
|
67,575,266 | 67,575,582 | Linking yaml-cpp with conan | I'm using yaml-cpp from conan center, in my conan file, yaml-cpp/0.6.3, along with other dependencies.
The rest of the libraries link properly, so there must be something missing in my CMakeLists.txt file. (Maybe some extra definition...?)
Until now, with those lines:
include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)
c... | The package is okay, but your profile is misconfigured.
undefined reference to `YAML::LoadFile(std::__cxx11::basic_string<char, std::char_traits, std::allocator > const&)'
collect2: error: ld returned 1 exit status
You have to update your libcxx setting:
conan profile update settings.compiler.libcxx=libstdc++11 defau... |
67,575,268 | 67,575,655 | Converting a vector<tensorflow::Tensor> to tensor of tensors | Let's say I have a vector of image tensors with each image tensor having the dimensions of [frames, height, width, num_channels] and I want to take that vector and convert it to one larger tensor of [num_tracks(size of vector), frames, height, width, num_channels]. What's the easiest way to do this with the tensorflow... | You can create a new Tensor with desired shape, and just fill it out by iterating for all dims in for loops (to access individual item use operator() of Eigen's TensorMap which you can get by tensor<DataType,DIMS> on Tensor):
tensorflow::Tensor concat(const std::vector<tensorflow::Tensor>& in){
int frames = in[0].d... |
67,575,534 | 67,575,642 | Is there a way how to identify class of overloaded operator[] in c++? | Let say we have a class with an operator [] as follows
class MyClass
{
//...
public:
TYPE operator[](const size_t idx) const
{
//... Implementation
}
}
Now i want to read TYPE and use it as a template argument for another class. One may use a trick
template<class T>
class OtherClass
{
//...
}
... | Yes:
using T = std::decay_t<decltype(myclass[0])>;
The expression inside decltype is not evaluated. In fact, you don't need an instance:
using T = std::decay_t<decltype(std::declval<MyClass>()[0])>;
See std::decay, decltype and std::declval
|
67,575,953 | 67,580,643 | Alternatives to Qt Signals and Slots for Inter-Object Communication | What are alternatives to using Qt-like signals and slots for communication between two objects (class instances) in both directions?
I know this can be realized by saving a reference of the other in each object. However, this gets sort of confusing when there are many different objects and all objects are supposed to i... | Qt Signal and slot mechanism is best choose in Qt programs, but if you want to know about other options, you have these:
You can develop your own Observer structure that would be like Qt signal and slot but you should invent the wheel from the beginning by yourself.
You should create an Observe class and a Subject cla... |
67,575,957 | 67,577,397 | Explicitly specify template template types | I'm learning templates. If I mix up the concepts template / template-type / template-argument, please correct me.
I'm trying to write a template function that creates an object and returns it. The type of the object comes from the template argument that has to be explicitly specified.
result = createObject<ObjectType>(... | The usual way to do decomposition like this is via partial specialization, which requires a helper class template:
namespace detail {
template<class> struct create; // undefined
template<template<class T> class C,class T>
struct create<C<T>> {
static C<T> make() {/* … */}
};
}
template<class T>
T createObject() {re... |
67,575,980 | 67,584,275 | C ++ (crypto ++) and C # encryption matching | For secure communication between client and server, I want to encrypt and decrypt data from both the client and the server, but I cannot get the same results, the data that comes from the client to the server is not decrypted, also when encrypting the same the same data from the server, I get a distinctive result from ... | The posted C++ code is fine. It returns the posted ciphertext STpu...0lWJ on my machine and the ciphertext can be decrypted with the decrypt() method.
In contrast, although the posted C# code returns the posted ciphertext tIDl...RoEM=, the ciphertext cannot be decrypted using the Decrypt() method. This has two reasons:... |
67,576,384 | 67,579,963 | what are the differences in libnotify dev versus libnotify bin | what is the difference in 2 libraries? Which one is prefered for production apps?
Why is there significantly different set of dependencies while installing?
| There is only one libnotify library. I assume you're asking about the deb packages libnotify-bin and libnotify-dev.
If so, the difference is very simple: the library packages with -dev suffix contain development files for the library, while packages with -bin suffix may contain some compiled binaries and utilities. To ... |
67,576,425 | 68,003,955 | How to run a command on powershell in vscode? | I am making a c++ program in vscode. And i want to compile the c++ program using a specific command (for example g++ file_name.cpp -o file_name.exe). But cant understand how to do it using tasks in vscode?All i want is to be able to run the above compilation command on the powershell in vscode. How can i do it??
| I recently found out how to do it.
You can download the coderunner extension in vscode.
Then go to the settings of this extension.
Then go to the executor_map.json folder.
In this folder you will see json pairs like key value pairs.
The 'key' is the language name and 'value' is the string which is directly pasted in t... |
67,577,365 | 67,577,541 | C++: confusion about accessing class data members while multithreading | I have the following minimal working example in which I create a number of markov_chain objects in a vector chains and an equal number of thread objects in a vector workers, each of which executes a markov_chain class member function sample on each of the corresponding markov_chain objects. This function takes some int... | There are 2 problems with your code:
when creating each std::thread, you are passing a copy of each object as the this parameter of sample().
Pushing multiple objects into the chains vector the way you are doing may cause the vector to re-allocate its internal array, thus invaliding any object pointers you have alrea... |
67,577,430 | 67,577,517 | How to write a deduction guide for passing anonymous std::array of variable size? | I want to be able to pass an anonymous std::array of variable size to a constructor:
using namespace std;
template <size_t N>
struct A
{
array<string, N> const value;
A (array<string, N>&& v): value {v} {}
};
Trying to pass an anonymous array like this …
A a { { "hello", "there" } };
This results in the foll... | This works for me on gcc 11 with -std=c++17:
#include <string>
#include <array>
using namespace std;
template <size_t N>
struct A
{
array<string, N> const value;
A (array<string, N>&& v): value {v} {}
};
template<typename T, size_t N>
A( T (&&) [N]) -> A<N>;
A a { { "hello", "there" } };
Live example
|
67,577,563 | 67,587,677 | Magick++ find out whether an image has transparency | I'm trying to find out whether an Image (the Magick++-class) is opaque/has transparent pixels. My current test code looks like this:
Image orig;
orig.read(inputPath.c_str());
bool hasAlpha = orig.alpha();
printf("Alpha: %s %s\n", inputPath.c_str(), hasAlpha ? "yes" : "no");
This correctly outputs "no"... | With ImageMagick-7, I believe the method you need is Magick::Image::isOpaque(); which calls the same MagickCore method to calculate '%[opaque]'.
bool hasAlpha = !orig.isOpaque();
printf("Alpha: %s %s\n", inputPath.c_str(), hasAlpha ? "yes" : "no");
|
67,577,625 | 67,588,845 | C++ Efficient interpolation of a std::vector | I need to find the value of a function given its unknown by interpolation. The problem is that the one I created is way too inefficient.
Firstly, I read a data file that contains both y=g(T) and T, but in discrete form. And I store their values in a std::vector<double>.
After this, I convert T (std::vector<double> Tgda... | Lose min_element, lose the absolute distance comparison. It's a convex transformation which can be searched efficiently, but not by any function that exists in the C++ standard library.
You don't want the two closest points anyway, you want to bracket your evaluation above and below. (The only case where "closest two... |
67,578,050 | 67,578,366 | vector::erase fails with invalid operands to binary expression (T and const T) | I have a Class called Request like this,
class Request {};
I store objects of this type in a global vector called,
std::vector<Request> requests;
I initialize the object using,
auto &request = requests.emplace_back();
Now, I attempt to delete the object using the reference provided by emplace_back like this,
request... | In
requests.erase(std::remove(requests.begin(), requests.end(), request), requests.end());
The asker has been confused by answers to problems with std::erase and classes with no compiler-generated assignment operator. The problem here is not with std::erase and assignment operators, Request is, as presented at any rat... |
67,578,150 | 67,578,316 | Exception has occurred: Trace/breakpoint trap - Debugging a C++ program in VSCode (uses dynamic memory allocation) | I am using Dynamic memory allocation in this code for deleting for nodes. Upon encountering a delete someVar I am getting an error in the VSCode debugger.
Exception has occurred
Trace/breakpoint trap
I do not understand what is the meaning of Trace/breakpoint trap. Could you explain it? Also, kindly help me detect wha... | delete should only be used with an object that has been created with new.
You create objects on the stack and set lsptr to point to them. Note that the list nodes were not created by new. You then delete lsptr, which is invalid because they were not created by new. This causes an exception. The exception is not handled... |
67,578,185 | 67,578,203 | Why does the delete[] syntax exist in C++? | Every time somebody asks a question about delete[] on here, there is always a pretty general "that's how C++ does it, use delete[]" kind of response. Coming from a vanilla C background what I don't understand is why there needs to be a different invocation at all.
With malloc()/free() your options are to get a pointer... | Objects in C++ often have destructors that need to run at the end of their lifetime. delete[] makes sure the destructors of each element of the array are called. But doing this has unspecified overhead, while delete does not. This is why there are two forms of delete expressions. One for arrays, which pays the overhead... |
67,578,313 | 67,578,387 | Overload += for a template? | I have a base class Animal and a derived class Bird : Animal. I use a template class that will store vectors of pointers to either Animal or Bird objects. I want to overload the += operator in such a way that I can insert a new animal right in the Atlas, so m_length = m_length + 1, pages.push_back(animal), just to get ... | The basic problem is that you've declared your operator+= as returning a T, but the return statement in it is return *this;, which is an Atlas2<T>.
If you change the return type to Atlas2<T> &, it should work. That's what you would normally want to return from an operator+= anyways, though with your use, it doesn't ma... |
67,578,558 | 67,578,573 | Function has parameter of type `int`, but gets passed an argument of type `int*` | I have a question about terminology. Consider a unary function. I read in this thread that the function's parameter is the 'variable' used in its declaration, and the 'argument' is the actual value of the variable one passes to the function when calling it.
However, consider this simple function:
void f(int *p){};
It ... | Your function has one parameter p of type int*. You pass it one argument w of type int*. The placement of the * causes some awkwardness at the syntactic level, but for type checking purposes you should regard it as part of the type.
|
67,578,892 | 67,587,849 | CLion - can't run a program on apple m1 | I ran clion a month ago and it worked perfectly. Now when I run a program I get:
/bin/sh: /Users/a/Library/Application Support/JetBrains/Toolbox/apps/CLion-ARM/ch-0/203.7717.62/CLion.app/Contents/bin/cmake/mac/bin/cmake: No such file or directory
make: *** [cmake_check_build_system] Error 127
Also, on clion startup, t... | Erase cmake-build-... directory manually and reload a CMake project.
|
67,579,804 | 67,586,154 | How to get rowvalue of selected combobox in Qtableview? | I have Qtableviews, I have added combobox in table2 and values in combobox getting from table1 col0, so when user select item in combo2, I need to get the row value of selected item?
How can I do using indexwidget?
After getting row value then I can compare the combobox text and perform the calculation.
As what I sha... | I found the solution
after combo2
I added
if (combo2!=NULL) {
//my previous code
}
|
67,579,849 | 67,580,406 | how to temporarily use std::cout in place of std::ofstream | if I want to create a logging class, say
class logging_class {
public:
std::ofstream error;
std::ofstream event;
logging_class() {}
logging_class(string err, string evt) {
error.open(err);
event.open(evt);
}
~logging_class() {
error.close();
event.close();
}
}... | Think of std::cout of what it actually is: an object. It is just that:
The global objects std::cout and std::wcout control output to […]
So when you say that you want to temporarily use std::cout in place of std::ofstream you're mixing apples (object std::cout) with oranges (class std::ofstream).
What you want to do,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.