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 |
|---|---|---|---|---|
72,822,279 | 72,822,289 | Move an object containing a unique_ptr to vector | Just wondering if there is a way to move an object holding a unique_ptr into a vector of those objects? Example:
class A
{
public:
std::unique_ptr<someData> ptr;
};
std::vector<A> objects;
A myObject;
//move myObject to objects???
Now, is there a way I could move myObject into objects and avoiding unique_ptr erro... | You'll need to do std::move:
std::vector<A> objects;
A myObject;
objects.push_back(std::move(myObject));
|
72,823,028 | 72,823,422 | How to test a protected member from multiple inheritance in GoogleTest? | Imagine I have a Foo class which contains a protected member. Foo is my template base class.
Then I have a Bar class, which inherits from Foo.
The protected member will be private within Bar.
I need to make a test which I need to access the protected member from my Foo base class as seen below.
#include <gtest/gtest.h>... |
why can't I access my mMember method?
It is not my mMember, it is bar's member.
GoogleTest manual:
When you need to test the private or protected members of a class,
use the FRIEND_TEST macro to declare your tests as friends of the class.
template <typename T>
class Foo
{
public:
void set() { mMember=1; }
p... |
72,823,620 | 72,874,932 | Use SDK (libraries, header files, etc) during creating a C++ ROS package | I am working with Teledyne Lumenera USB Camera. I installed lucam-sdk_2.4.3.94 for Linux on my Ubuntu 18.04. It includes these files:
The api folder contains this files:
One of the folders is example which contains several examples for working with Teledyne Lumenera USB Camera. Each example in example folder, shows o... | I solved the problem. Working with CMakeList and ROS was confusing.
Go to this repository, and read instalation part, then look at CMakeList.txt:
https://github.com/farhad-dalirani/lumenera_camera_package
|
72,823,670 | 72,823,829 | How does conversion constructor work in this case? | How does conversion constructor work?
Does the compiler creates a temporary object of myClass and uses the constructor myClass(int i) initialize the temporary object first and then pass the object to function output?
OR
Does the compiler directly initializes the output() parameter rhs using the
myClass(int i) construct... | The parameter is a reference. A reference is not an object. It must be bound to some object instead and the type of the object must be compatible with the type of the reference.
So yes, a temporary object to which the reference can bind must be created. This temporary object is initialized by a call to the myClass(int ... |
72,823,777 | 72,824,146 | Can initializing an object with a prvalue function result call the move constructor? | I started with this piece of code to show the effects of NRVO:
struct test_nrvo {
bool b;
long x[100]; // Too large to return in register
};
test_nrvo tester(test_nrvo* p) {
test_nrvo result{ p == &result };
return result;
}
bool does_nrvo() {
test_nrvo result(tester(&result));
return result.... | Per [class.temporary]/3 RVO on the return value of a function has an exception.
If the type has at least one eligible copy or move constructor, all of them trivial, and if it has a trivial or deleted destructor, then the compiler is allowed not to apply RVO and create a temporary in which the function return value is h... |
72,824,003 | 72,824,136 | Overload pattern as a storage | I am trying to use overload pattern as a storage, but I am having trouble appending a new element.
Is it actually possible?
There is an example - https://godbolt.org/z/ohvY4sx9q
PS stackoverflow doesn't allow to paste that much code
template<typename... Ts>
struct Container : Ts...
{
template <typename H>
auto ... | godbolt
Is this what you want?
#include <iostream>
#include <typeinfo>
template<typename... Ts>
struct Container : Ts...
{
void operator()(auto&&... args)
{
( [&]() {
std::cout << "type => " << typeid(Ts).name() << std::endl;
Ts::operator()(std::forward<decltype(args)>(args)...);
... |
72,824,256 | 72,824,494 | OpenMP: Assign threads one iteration at a time | Say you have a loop containing a varying number of iterations and 4 cores
I understand that
#pragma omp parallel for
will basically divide the iterations in like this with chunks of size/4 length
| T1 | T2 | T3 | T4 |
However, in my particular situation, this behavior would be more advantag... | What you are describing -- assuming that your heuristic is size/total threads -- is a round-robin scheduling (i.e., static scheduling) with chunk_size = 1. For that you simply need :
#pragma omp parallel for schedule(static,1)
In this case, it makes no difference if the number of iterations is known (or not) at runtim... |
72,824,276 | 72,824,308 | Not getting expected answer using this approach? | I am solving a question on LeetCode , Here is the Link
I got the solution but I wanted to know what wrong I am doing here , There are some testCases below or you can visit the link . A helping attempt is always appreciated from my side.
class Solution {
public:
static bool comparator(vector<int>&a,vector<int>&b){... | You need to add a break in the else statement. If truckSize <= boxTypes[i][0], we just load truckSize boxes and it will no longer accept any boxes (which means we need to break the for loop and return the result). Otherwise, it will continue the for loop, and try to load the following boxes.
|
72,824,401 | 72,824,424 | Mounting memory buffer as a file without writing to disk | I have a server and needs to feed data from clients to a library; however, that library only supports reading files (it uses open to access the file).
Since the data can get pretty big, I rather not write it out to a temporary file, read it in with the library then delete it afterwards. Instead I would like to do somet... | Use /dev/fd. Get the file descriptor of the socket, and append that to /dev/fd/ to get the filename.
If the data is in a memory buffer, you could create a thread that writes to a pipe. Use the file descriptor of the read end of the pipe with /dev/fd.
|
72,825,008 | 72,825,047 | Why does my UniquePtr implementation double free? | When I run this program I get a double free for my implementation of unique ptr. Any idea why this happens?
#include <iostream>
#include <memory>
using namespace std;
template <class T>
class UniquePtr
{
public:
UniquePtr(T* t = nullptr) : t_(t) {}
UniquePtr(const UniquePtr&) = delete;
UniquePt... | t_ is uninitialised in your move constructor so the moved from pointer ends up pointing to an uninitialised pointer and has undefined behaviour (this will cause problems when the moved from object destructs and deletes the uninitialised pointer). You need:
UniquePtr(UniquePtr&& oth)
: t_(nullptr)
{
std::swap(t_, ot... |
72,825,894 | 72,826,111 | Get all combinations of changing characters in a sring (C++) | Okay, I've been tearing my hair out for the past 5 hours on this.
I'm still new to C++, so bear with me if this is a stupid question.
I would like to get all possible character combinations, and put them in a string, in C++.
void changeCharInString(std::string &str, int index, char ch)
{
str[index] = ch... | You tagged your question as "recursion", so here is an answer that uses recursion:
void generate(int idx, string& test) {
if (idx == test.size()) {
// do something with test
} else {
for (char c : globals::validChars) {
test[idx] = c;
generate(idx+1, test);
}
... |
72,826,399 | 72,832,684 | float pointer in ctypes python and pass structure pointer | I'm trying to pass a structure pointer to the API wrapper, Where the struct is containing float pointer member. I'm not sure that how we can pass float pointer value to the structure.
/Structure/
class input_struct (ctypes.Structure):
_fields_ = [
('number1', ctypes.POINTER(ctypes.c_float)),
('numbe... | You can either create a c_float instance and initialize with a pointer to that instance, or create a c_float array and pass it, which in ctypes imitates a decay to a pointer to its first element.
Note that ctypes.pointer() creates pointers to existing instances of ctypes objects while ctypes.POINTER() creates pointer t... |
72,826,538 | 72,831,701 | binding reference of type const node*& to node*const | I am trying to implement a generic tree and in the function getSizeRecursive line 1why cannot i use const node* &root. Similarly, i am getting the same mistake in line 2.The compiler is giving an error which i am not able to comprehend.
graph.cpp: In function 'int getSizeRecursive(const node*&)':
graph.cpp:56:40: error... | Let's see the reason for getting each of the error on case by case basis. Moreover, i'll try to explain things in steps.
Case 1
Here we consider the 1st error due to the statement:
for(const node* &child : root->children)
Now to understand why we get error due to the above statement, let's understand the meaning of ea... |
72,826,704 | 72,826,957 | From boiler plate code to template implementation | I am implementing a finite state machine where all possible states are stored within a std::tuple.
This is a minimum compiling example of the problem I am facing and its godbolt link https://godbolt.org/z/7ToKc3T3W:
#include <tuple>
#include <stdio.h>
struct state1 {};
struct state2 {};
struct state3 {};
struct state4... | If you only want to avoid adding another line like
if (index == 4) return transit_to<4>();
when you add a new state, e.g. struct state5, you may implement transit_to(std::size_t) like this:
// Helper function: Change state if I == idx.
// Return true, if the state was changed.
template <std::size_t I>
bool transit_if_... |
72,827,366 | 72,829,177 | C++ output producing random long integers | I recently coded a question, and I have debugged and figured out where the problem is but cannot quite place a finger on it. My program aims to merge groups of sectors if they overlap or are next to each other, but the last section is scrambling the output.
#include <cstdio>
using namespace std;
int main() {
freopen("... | Pointing out some issues with the code above, many of which you can get reported by using compiler options:
umbrellas[u][2] and groups[u][2]: these are variable length arrays; they're not standard C++.
n, k, and x are declared, read from, but never used later on.
groups is 1) not initialized, 2) filled only for groups... |
72,827,398 | 72,828,942 | MPI send and receive large data to self | I try to send and receive a large array to self-rank using MPI. The code works well for small arrays (array size <10000) when I further increase the array size to 100000, it will deadlock. Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
int main(int argc, char *argv[])
{
MPI_Init(&argc, &argv... | That's the definition of send and receive: they are blocking. The statement after the send will not execute until the send has been successfully completed.
The safe way to solve this is using MPI_Isend and MPI_Irecv.
The case for a small messages which don't block is an optimization that is system dependent and you ca... |
72,827,565 | 72,830,084 | How to get 2 dimensional array from file (C++) | I'd like to input 2 dimensional array from text file. But my code doesn't work..
#pragma disable (warnning:c4996)
#include<cstdio>
#include<cstring>
#include<iostream>
#include<fstream>
#include<conio.h>
int main()
{
std::ifstream arrival; std::ifstream departure;
arrival.open("arrival.txt"); departure.open("de... | This is what you can do with the 4 'basic' libraries vector, string, fstream and iostream. It is an example for "arrivals.txt" only:
#include<vector>
#include<string>
#include<fstream>
#include<iostream>
int main() {
std::ifstream arrivals; // open the file
arrivals.open("arrivals.txt");
std::ve... |
72,827,569 | 72,828,326 | How can I read message by message with recv in an AF_UNIX socket with C/C++? | I am trying to write a client for my AF_UNIX server. The server occasionally does a
write(fd, buffer, bufferSize);
where the message always ends in a newline.
Now, I want a C client to read it, message by message.
With bash, it's possible to do something like this:
socat - UNIX-CONNECT:/tmp/myepicsocket.sock | while r... | recv(socketfd, buffer, 1024, NULL);
With stream sockets, like AF_UNIX sockets, recv() is equivalent to read(). That's what makes them "stream" sockets. So, for all practical matters, this is:
read(socketfd, buffer, 1024);
And just like with a regular file you have no guarantees whatsoever that this reads only up unti... |
72,827,759 | 72,834,067 | Is using ranges in c++ advisable at all? | I find the traditional syntax of most c++ stl algorithms annoying; that using them is lengthy to write is only a small issue, but that they always need to operate on existing objects limits their composability considerably.
I was happy to see the advent of ranges in the stl; however, as of C++20, there are severe shor... |
Is using ranges in c++ advisable at all?
Yes.
and many things present in range-v3 did not make it into C++20, such
as (to my great surprise), converting a view into a vector
Yes. But std::ranges::to has been adopted by C++23, which is more powerful and works well with C++23's range version constructor of stl contai... |
72,827,897 | 72,828,002 | Why doesn't std::istream_iterator< std::string_view > compile? | Why can't GCC and Clang compile the code snippet below (link)? I want to return a vector of std::string_views but apparently there is no way of extracting string_views from the stringstream.
#include <iostream>
#include <sstream>
#include <string>
#include <string_view>
#include <vector>
#include <iterator>
#include <a... | Because there is no operator >> on std::stringstream and std::string_view (and std::istream_iterator requires this operator).
As @tkausl points out in the comments, it's not possible for >> to work on std::string_view because it's not clear who would own the memory pointed to by the std::string_view.
In the case of you... |
72,828,750 | 72,829,850 | Can the else clause be simplified in this if\else ladder? | I have thiselse clause:
else if (iItemIndex == 1 || iItemIndex == 3 || iItemIndex== 5 || iItemIndex == 7 ||
iItemIndex == 10 || iItemIndex == 12 || iItemIndex == 14 || iItemIndex == 16 ||
iItemIndex == 19 || iItemIndex == 21 || iItemIndex == 23 || iItemIndex == 25)
Can it be simplified in some way? Nothing wro... | You can write
const bool rng=i>=0 && i<27;
if(const auto r=i%9; rng && !r) …
else if(rng && (r&1)) …
else …
This can of course be much simplified if the value may be assumed to be in the relevant range:
if(const auto r=i%9; !r) …
else if(r&1) …
else …
|
72,828,925 | 73,251,112 | How to reset/delete Qcustomplot's axis ticker setting? | I have a QcustomPlot widget that I want to reuse it for plotting all kinds of plot. But there is a case that I need to set the xAxis ticker to DateTime.So I did this:
QSharedPointer<QCPAxisTickerDateTime> dateTicker(new QCPAxisTickerDateTime);
dateTicker->setDateTimeFormat("yyyy-MM-dd");
customplot->xAxis->setTicker(da... | ui->customPlot->xAxis->setTicker(QSharedPointer(new QCPAxisTicker)); - this will return them to their standard state
|
72,828,926 | 72,829,942 | QTableWidgetItem displays three dots instead of full text | I'm using a QTableWidget with four column witch i programaticaly fill with QTableWidgetItem in a loop. it's working but the full text is not displaying, it show three dots instead like there isn't enough space:
if i double click on a row it will display the whole text:
How to set QTableWidgetItem programatically to f... | My original string contain return lines, removing them like:
QString s = lines.at(i).libelle;
s.replace('\n',' ');
ui->operationTableWidget->setItem(i,1,s);
is working.
As @Scheff'sCat pointed out in the comment of my original post, using the accepted solution at How to prevent too aggressive text elide in QTableview?... |
72,829,395 | 72,830,012 | How function templates can accept functions as parameters even thought functions are not types? | This obvious question might be asked somewhere which i couldn't found, the nearest answer is this .
I come from a C background and if you want to pass a function as argument in C You ought to use a pointer to function . but this :
void increment ( int & n ) { n += 1; }
template <typename T, typename F>
void iterat... | Functions have a type. There is nothing fundamentally different from passing increment to the function template compared to passing arr. Their types get deduced and then replaced as the template arguments.
Perhaps it get clearer without argument deduction:
iterator<int, void()(int&)>(arr, 5, increment);
or letting dec... |
72,829,821 | 72,829,898 | c++: Generate random numbers with seed | I am new to c++. I am trying to generate 4 random unique numbers from 0 to 9. Here is my code:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<int> vect;
int randNums = 4;
int countSameNums = 0;
int randNumber;
srand(time(0))... | It can take long before you get 4 different numbers. There is a simpler and more efficient way to get 4 unique numbers. Take a vector containung number from 0 till 9, shuffle it, take the first 4.
Anyhow the issue in your code is that once countSameNum is not 0 you will never reset it to 0. You only reset it when it is... |
72,831,013 | 72,831,488 | How to track source of rules (functions) in bazel? Is there any order of initialisation or query to discover it? | How to find places where the rule is defined and which definition bazel uses in this specific package?
Say, I have gRPC installed and looking at grpc/examples/cpp/helloword/BUILD file. I can see a common rule for cpp builds: cc_binary. But this rule is not in grpc WORKSPACE file. Nor it in BUILD file. I do grep -rnw -e... | In general, query --output=build will emit a comment indicating where a target's rule class is defined:
$ bazel query --output build //src/proto/grpc/core:stats_py_pb2
py_proto_library(
name = "stats_py_pb2",
deps = ["//src/proto/grpc/core:stats_descriptor"],
)
# Rule stats_py_pb2 instantiated at (most recent call ... |
72,831,564 | 72,831,787 | Is it possible to pass one of the standard function templates as an argument without using a lambda? | For example, std::get<N>.
Can I do the following without using a lambda somehow?
#include <iostream>
#include <tuple>
#include <algorithm>
#include <vector>
#include <iostream>
using str_and_int = std::tuple<std::string, int>;
std::vector<std::string> just_strings(const std::vector<str_and_int>& tuples) {
std::ve... | You don't have to use a lambda. You could provide an instance of your own type if you'd like:
struct transformer {
auto operator()(const auto& tup) const { // auto C++20
return std::get<0>(tup);
}
};
std::vector<std::string> just_strings(const std::vector<str_and_int>& tuples) {
std::vector<std::st... |
72,832,331 | 72,833,793 | How do you display the array responses back to the user after establishing & validating their input? c++ | newer at this but im drawing a blank on how to simply display the user's responses back. any feedback is so appreciated!
currently what i have:
int array[5] = {};
int i;
int numbers;
for(int i = 0; i < 5; i++)
{
std::cout << "Please enter a number: ";
std::cin >> numbers;
... | what you really want is the printing of the array that is filled by the user inputs if i am not wrong.I want to bring to your consideration that the thing you have done is not even storing the inputs to the array.
On going further assuming that you have the array concept. Now the problem you are facing is the access to... |
72,832,433 | 72,832,665 | Preserving constness upon a cast | I want a way of preserving if the type is a pointer, const, etc upon a cast. See the following.
template<typename type>
void test(type t) {
std::cout << "t const? = " << std::is_const<decltype(t)>() << std::endl;
int x = (int) t;
std::cout << "x const? = " << std::is_const<decltype(x)>() << std::endl;
};
i... | Your example isnt the best to illustrate the actual issue to cast a void*, possibly const, to some T* with same constness, because you can simply replace the line with type x = t; to get desired output.
However, you can use a type trait:
#include <iostream>
#include <type_traits>
template <typename From,typename To>
s... |
72,832,521 | 72,832,768 | is it safe to use std::move_iterator in std algorithm with lambda as pred | std::vector<std::string> foo{"a","b","c"};
std::set<std::string> check{"a"};
std::vector<std::string> bar{"something_here"};
typedef std::vector<std::string>::iterator Iter;
std::copy_if(std::move_iterator<Iter>(foo.begin()), std::move_iterator<Iter>(foo.end()), std::back_inserter(bar),
[&check](std::string && s)->boo... |
Is it because although string is passed into lambda as rvalue, it was not used to construct another string, so effectively the input string was not "moved", i.e., ownership of that string resource is unchanged?
Yes. Simply forming an rvalue reference does not modify an object. The object doesn't even know it happen... |
72,832,782 | 72,833,491 | How to make my ifstream "input" look the same in program like it does in file | I am new to programming, and currently I am learning C++. I am making this kind of project that I learn on, in which there already exists some "premade items", and items that you can create yourself and then be shown. For this, I am currently learning and using fstream.
The text in my file looks like this:
But this is... | The lines of text in the file are delimited by line breaks. operator>> skips leading whitespace before reading data (unless std::noskipws is used), and then stops reading when it encounters whitespace. Spaces, tabs, and line breaks are all considered whitespace by operator>>.
So, in your case, you end up reading indi... |
72,832,953 | 72,833,655 | How to get process name in an injected dll? | I have this basic internal dll:
#include "pch.h"
DWORD WINAPI HackThread(HMODULE hModule)
{
uintptr_t moduleBase = (uintptr_t)GetModuleHandle(L"Mainmodule123.exe");
AllocConsole();
FILE* f;
freopen_s(&f, "CONOUT$", "w", stdout);
std::cout << "Injected" << std::endl;
while (!GetAsyncKeyState(V... | You can pass NULL for the lpModuleName parameter into GetModuleHandle:
If this parameter is NULL, GetModuleHandle returns a handle to the file used to create the calling process (.exe file).
|
72,833,079 | 72,848,497 | c++11 - list-initialization of an aggregate from an aggrrgate | On this page of the cppreference.com I read the following:
If T is an aggregate class and the braced-init-list has a single
element of the same or derived type (possibly cv-qualified), the
object is initialized from that element (by copy-initialization for
copy-list-initialization, or by direct-initialization for
dire... |
of the same or derived type
That means that default copy-constructor will be used. That's why there is no contradiction between these two rules
|
72,833,113 | 72,833,153 | How can a static void class function be initialized in the header of a C++ program? | I am supposed to initialize a static string, which is a private member of the class, with a setter which is a public member of the same class, from outside of the class, and in the same namespace.
Here is the code template I was given. Changing the College class is not allowed.
#include <iostream>
using namespace std;... | string College::setPrincipalName("John"); is not legal or correct. You need to define the actual College::principal_name variable instead, eg:
string College::principal_name = "John";
Even then, don't define it in the header file itself. Every file that includes the header will try to re-define the variable, leading... |
72,833,444 | 72,833,523 | How to Return struct in a class when gthe struct is declared outside the class? | I am trying to get the structure of strings "Johna" "Smith" to return by calling a class. I am very new and confused on OOP and pointers and I wanted to know if Im on the right track and what I can do to get rid of the following errors:
"cannot convert ‘name’ to ‘const char*’" on line 46... This line
printf(s1.get_na... | Your code is totally fine, you're just confused about the printf function of C++.
Maybe you have experience with python, javascript, or other scripting languages that the print function accepts anything and prints it out nicely. That is not the case with a strong typed language like C++.
You should read the docs on pr... |
72,833,914 | 72,834,126 | Does this count as an Insertion-Sort? And why does a random number show at the end? | I've been asked to create an insertion sort for an array. My program ended differently from the teacher's, but it sorts the array. However, I'm curious if it truly counts as a proper insertion sort. Also, at the end of the sorting, some random numbers appear. I would appreciate some help with this.
#include <iostream>
... | For starters there is a typo in this statement
v[i+1] = v[I];
^^^^
It seems you mean
v[i+1] = v[i];
^^^^
The while loop
while(v[i+1] < v[i]){
temp = v[i+1];
v[i+1] = v[I];
v[i] = temp;
printArr(v);
i = 0;
}
can invoke undefined behavior due to acc... |
72,833,916 | 72,835,160 | c++11 - zero-initi of members insted of default-init | In the below code, I expect members of a being inited with gargabe as they are not mentioned in the members-init-list of the called constructor (with two int parameters). Instead, I'm constantly getting 0 in both i and j of a, b and c and I am failing to see why. Could anybody please point me in the right direction?
#i... | The i and j fields that you are accessing are, indeed, uninitialized. However, you are smearing the wrong part of the stack. It just so happens that on most OSes, the stack is initially all zeros. It even used to be common in C (long ago) to assume that automatic variables in main were zero-initialized.
To see that ... |
72,834,348 | 72,834,516 | Make generic Lambda with exactly N arguments | I want to dynamically create math expressions with lambdas, as reviewed here.
using Func = std::function<double(double)>;
Func operator+(Func const& lhs, Func const& rhs){
return [lhs, rhs](double x){
return lhs(x) + rhs(x);
};
}
My next goal is to generalize this.
Thanks to this answer I managed to i... | Not sure the standard allows you to manage argument count restriction like that, but you can definitely have an assert if the arg count is in mismatch. E.g.:
#include <functional>
template <std::size_t, typename T> using alwaysT = T;
template <typename FLOAT, typename Seq> struct func_struct;
template <typen... |
72,834,444 | 72,834,546 | How to concat string and float | I have a simple variable:
float t = 30.2f;
How do I add it to a string?
char* g = "Temperature is " + h?
Any guaranteed way (I don't have Boost for instance, and unsure of what version of c++ I have) I can get this to work on a microcontroller?
| For simple cases, you can just use the std::string class and the std::to_string function, which have both been part of C++ for a long time.
#include <string>
#include <iostream>
int main()
{
float t = 30.2;
std::string r = "Temperature is " + std::to_string(t);
std::cout << r;
}
However, std::to_string doesn't ... |
72,834,496 | 72,834,604 | Explicit template instantiation of templated friend of templated class in C++ | I have a main class MainClass whose private member variables should be visible to a friend class FriendClass.
Both are templated by an int called dim, and they both have their respective header and source files (and are thus in different translation units).
Since MainClass doesn't really depend on FriendClass (and to a... | You have declared two different class templates both named FriendClass. Probably unintentionally.
One is the global FriendClass and the other is MainClass::FriendClass.
You can fix this by forward declaring your class template in the namespace it exists in.
// MainClass.hpp
#ifndef MAIN_CLASS_HPP
#define MAIN_CLASS_HP... |
72,834,725 | 72,834,877 | How to obtain iterator type from template parameter, if template parameter is a reference type | The question title may not be super clear, but hopefully the below explains what is my problem.
Let's say I have the following (simplified) class template:
template <typename T, typename Container = std::vector<T>>
class MyVector {
using iterator = typename Container::iterator;
Container data{};
public:
MyV... | The std::remove_reference will work here. Or you need std::remove_reference_t version of it
using iterator = std::remove_reference_t<Container>::iterator;
// ^^^^^^^^^^^^
That is mean, if you do not have access to the c++14, provide a type alias for this
template< class T >
using remove_ref... |
72,834,729 | 72,899,394 | Thrust inplace copy_if operation | I wanted to know if you can use copy_if as an in-place operation?
i.e.
void copy(thrust::device_vector<int> & input){
auto end = thrust::copy_if(input.begin(), input.end(), input.begin(), thrust::placeholder.1_ < 10);
input.erase(end, input.end());
}
is equivalent to:
void copy(thrust::device_vector<int> &... | According to the documentation:
Preconditions: The ranges [first, last) and [result, result + (last - first)) shall not overlap.
So no, one is not allowed to use thrust::copy_f in-place. The reason is probably that the algorithm would need to create an internal copy (especially costly due to the potential allocation)... |
72,834,775 | 72,835,147 | ZLib: DeflatePrime number of bits of Z_PARTIAL_FLUSH | In the ZLIB Manual it is stated that Z_PARTIAL_FLUSH always flush an extra 10 bits. So that we correct for that using deflatePrime when we want to append later.
But why then is gzlog.c containing logic to find dynamically the bit count if *buf . According to the specs this is not needed and only the else is needed to ... | Because most of the time not all of the ten bits are written. Only in the case where the last byte is a zero are all ten bits written, because by chance (a one-in-eight chance) there were six bits pending to be written before the ten-bit empty static block.
|
72,835,323 | 72,835,392 | C++ class object default constructor bug | I am trying to create a class object s2 with some customized attributes and some attributes from default constructor however my output is the wrong output for the get_year function. It should be outputing 0 which is the key for FRESHMAN but it is out putting 2 instead. The rest of the code is outputting as expected:
#i... | Student lacks a constructor, so all its members are default initialized, and the default initialization of year Year and int idNumber is "no initialization", so reading from them is undefined behavior. Reading them might find 0, 2, a random value each time, or crash.
I see that your class contains a void set_year(year ... |
72,835,462 | 72,835,502 | Comparator for lower_bound for vector of pairs | I wanna make lower_bound for vector of pairs but I wanna use it only for first elements of pairs. I tried to make my own comparator like this:
bool find(const std::string& key) const {
auto finder = std::lower_bound(words_.begin(), words_.end(), key,
[](const std::string& ... | Your lambda is the wrong signature and comparison for lower_bound(). It is expected to compare a container element against the provided value. Which means it does not accept an iterator as input at all.
The 1st parameter of the lambda needs to accept the container element, and the 2nd parameter needs to accept the inpu... |
72,835,571 | 72,835,611 | constexpr C++ error: destructor used before its definition | I'm experiencing an error using g++-12 which does not occur in clang++-13. In particular, this code:
struct A {
constexpr virtual ~A() = default;
constexpr A() = default;
};
struct B : public A {
constexpr ~B() = default;
constexpr B() = default;
};
constexpr int demo(){
B *b = new B();
delet... | It is a GCC bug, see this report.
Virtual defaulted destructors don't seem to work at all in constant evaluation with current GCC. As also mentioned in the bug report, simply
struct A{
constexpr virtual ~A() = default;
};
constexpr A a;
also fails.
As a workaround you can provide definitions for the destructors m... |
72,835,703 | 72,837,755 | Sort 2d C++ array by first element in subarray | I am trying to sort a c++ subarray by first element.
My code is currently set up like this:
int umbrellas[3][2] = {{5, 6}, {2, 7}, {9, 20}};
int n = sizeof(umbrellas) / sizeof(umbrellas[0]);
sort(umbrellas, umbrellas + n, greater<int>());
The sort function doesn't seem to be functioning properly and when I run the c... | Use a std::vector of std::vector as your container and the sort becomes much easier to do with. Not only is std::vector the preferred container for C++ but using STL functions on it is way simpler and direct , without any substantiable overhead.
Define your data as
std::vector<std::vector<int>> umbrellas{
{5, 6},
... |
72,835,974 | 72,836,053 | Return Expression Check Condition in C++ | Still getting used to the formatting when writing C++ code, come from a Lua background.
How do I correctly format a if/conditional expressions as my example highlights below.
This will correctly run, but with warnings which is unideal:
return (boolean == true) and init() or 0;
Highlighted Warning:
expected a ';'C/C++ ... | and and or are keywords are considered a bit archaic. They are technically valid C++ keywords in modern C++ (since C++98 it seems). You must be using a very old C++ compiler that was written before they were added to C++. They, and their usage, never took off. Classical && and || operators continue to rule the roost an... |
72,836,070 | 72,838,182 | Speeding up boost::iostreams::filtering_streambuf | I am new to the C++ concept of streams and want to ask for some general advice to speed up my code in image processing. I use a stream buffer boost::iostreams::filtering_streambuf to load and decompress the image from a file, as suggested in this post and another post. The performance is not satisfactory.
The relavent ... | You can use blockwise IO
char buf[4096];
inflated.read(buf, sizeof(buf));
std::for_each(buf, buf + inflated.gcount(), _fill_);
However, I also think considerable time might be wasted in _fill_ where some dimensions are reshaped. That feels arbitrary.
Note that several libraries have the features to transparently re-in... |
72,836,346 | 72,836,441 | How do I can I get notified of an object collision and object trigger in Box2D? | Unity3D has the OnCollisionEnter2D, OnCollisionExit2D, OnTriggerEnter2D etc. However, I am using Box2D and am looking for a way to implement something similar or the same in my C++ project, but I do not know how. I saw something about implementing a listener but I believe it was for the whole world. I am looking to rep... | Enabling an event listener is necessary for collision events in Box2D, as explained in this video. Alternatively, you could implement your own collision logic. For rectangular hitboxes, that would look something like this: (Please note: this only works for rectangles with no rotation relative to the screen.)
if (rect1.... |
72,836,555 | 72,836,752 | How can I delink an element from a c++ std::list without deallocating it? | Suppose I have a c++ std::list object containing a few elements and an iterator it to one of the elements. How can I remove this element from the list but still be able to access it? In other words, I want it delinked from the list, but not deallocated.
Curiously, using list::erase does seem to achieve this:
#include <... | This can be done provided you don't mind using a second list to receive the erased item
auto it = (--a.end());
std::list<int> b;
b.splice(b.end(), a, it);
cout << *it << endl; /// outputs '3'
splice removes the it element from list a and adds it to the end of list b. It's a constant time operation and does not inval... |
72,836,628 | 72,836,662 | How good is the Visual Studio compiler at branch-prediction for simple if-statements? | Here is some c++ pseudo-code as an example:
bool importantFlag = false;
for (SomeObject obj : arr) {
if (obj.someBool) {
importantFlag = true;
}
obj.doSomethingUnrelated();
}
Obviously, once the if-statement evaluates as true and runs the code inside, there is no reason to even perform the check ag... | Branch-prediction is a run-time thing, done by the CPU not the compiler.
The relevant optimization here would be if-conversion to a very cheap branchless flag |= obj.someBool;.
Ahead-of-time C++ compilers make machine code for the CPU to run; they aren't interpreters. See also Matt Godbolt's CppCon2017 talk “What Has... |
72,837,193 | 72,837,214 | C++ Socket libraries are not being identified by the compiler | I am trying to to learn how to stream image frames via UDP in C++ and I was following this tutorial for the server part to receive my frames, this tutorial clearly uses code from question stackoverflow question. However, after following up both sources, whenever I attempt to load my libraries in geany/c++:
#include <st... | You are using SOCKET or SOCKADDR_IN which is Microsoft dedicated but I see Linux headers.
You need to select what you want to do:
You need code only for Windows.
You need code only for Linux.
You need a cross-platform code.
Your approach somehow differs based on what you want to do.
If your code is supposed to work o... |
72,837,408 | 72,837,533 | Passing a templated function as argument without instantiation? | I've been doing some exercises in C++ and stumbled upon one, it was about creating a simple a templated function iterator that takes an array of any type and another templated function to do some processing in each element in the array, i've completed the exerisce to look like the following:
template <typename T >
void... | Yes, you are correct. A function template cannot be passed as a template argument because it does not have a type yet.
What you can pass is a functor, either custom one with overloaded operator() or just a lambda. Are you sure the wording does not talk about functors?
The following code works:
auto print = [](const aut... |
72,837,598 | 72,837,674 | Class template argument deduction for class with additional non-type arguments | Is it possible to make CTAD work for T in this case?
enum class boundary_type:int{inclusive, exclusive};
template<class T, boundary_type left, boundary_type right>
struct interval
{
using value_type = T;
T begin;
T end;
};
I tried to add the decuction guide
template<boundary_type left, boundary_type rig... | CTAD cannot work with the partially explicitly specified template parameter. But you can do this using normal template function
template<boundary_type left, boundary_type right, class T>
auto make_interval(T begin, T end) {
return interval<T, left, right>{begin, end};
}
int main() {
auto intval = make_interval<bou... |
72,837,730 | 72,837,731 | How does the setw stream manipulator work? | How does the setw stream manipulator (space count) work? When there is one \t, for example, I want to print a with four spaces, so I use \t and I compare \t with setw.
The code that I wrote:
# include <iostream>
# include <iomanip>
int main()
{
std::cout<<"\t"<<"a\n";
std::cout<<std::setw(9)<<"a\n";
return... | That's because you need to add a \n at the setw(18). And this applies to any setw.
Sample code:
# include <iostream>
# include <iomanip>
int main()
{
std::cout<<"\t\t"<<"a\n";
std::cout<<std::setw(18)<<"a\n"; // And you add the \n here
return 0;
}
Output:
a
a
And another solution is:
# include <iostre... |
72,837,932 | 72,837,987 | Is " const wchar_t* " a pointer? | Normally when we write:
int a = 10;
int* ptr = &a;
std::cout << *ptr;
Code output is:
> 10
But when I write this:
const wchar_t* str = L"This is a simple text!";
std::wcout << str << std::endl;
std::wcout << &str << std::endl;
Code output is:
> This is a simple text!
> 012FFC0C
So this makes me confused.
Doesn't t... | L"This is a simple text!" is an array of type const wchar_t[23] containing all the string characters plus a terminating 0 char. Arrays can decay in which case they turn into a pointer to the first element in the array which is what happens in
const wchar_t* str = L"This is a simple text!";
std::wout can be used with a... |
72,838,017 | 72,839,302 | multiple shared_ptr that point to the same object | Just for studying purpose I'm coding binary search tree rotation now.
I normally use std::unique_ptr but I used std::shared_ptr this time
This works correctly:
// Node implementation
template <Containable T = int> struct Node {
T key_ = T{};
bool black_ = false; // red-black tree
std::shared_ptr<Node> left_;
st... | void left_rotate(Node *xp, Node* x) {
...
std::shared_ptr<Node> x_ptr(x);
...
When you create the shared_ptr it takes over ownership of x. The problem here is that it is not yours to give. Someone else, another shared_ptr, already has ownership of the pointer. So some of the operations you do before y->lef... |
72,838,038 | 72,838,111 | (C++) Using multiple operator overloads with const reference parameters | I have been working on a matrix class and I have recently learnt about passing const references to operator overloads so that I can have multiple of them on the same line. The problem I encountered is when defining a function for an operator overload, which takes a parameter by const reference, and then tries using ano... | For starters matrix1 is a pointer but you need to apply the subscript operator for an object of the type Matrix.
matrix2 is a constant object but the subscript operator is not a constant member function.
You need to overload the operator [] as a constant member function
Column& operator[](int i) //Operator overload to ... |
72,838,235 | 72,838,443 | C++ How to choose file size as array size | I can't use file size as array size, because it should be a constant. But I made it constant.
ifstream getsize(dump, ios::ate);
const int fsize = getsize.tellg(); // gets file size in constant variable
getsize.close();
byte dumpArr[fsize] // not correct
array<byte, fsize> dumpArr // also not correct
byte *dumpArr = ne... | You need a compile-time constant to declare arrays so you have two options:
Give up the idea to create an array and use a std::vector instead:
std::ifstream file("the_file");
std::vector<std::uint8_t> content(std::istreambuf_iterator<char>(file),
std::istreambuf_iterator<char>{});
I... |
72,838,522 | 72,841,372 | C++ how to make a series of statements atomic? | I have a program which have multiple threads running. Inside the main thread, a class variable maybe changed by operations from different threads. So I will like to make sure that within a series of steps involving the variable, no other threads may change the variable midway through that series of steps. E.g.
this->a ... | From the comments, it seems your view of a mutex is that it serves to protect a single block of code, so that no two threads can execute it simultaneously. But that is too narrow a view.
What a mutex really does is ensure that no two threads can have it locked simultaneously. So you can have multiple blocks of code "... |
72,838,658 | 72,838,677 | How can I deal with pointer assignment compile error (error: no viable overloaded "=") in C++ | I'm a rookie, and when I was doing Leetcode 21. Merge Two Sorted Lists
I submitted this code:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNo... | Very common error
ListNode* p1, p2;
should be
ListNode *p1, *p2;
You need to use * on both variables to make both of them pointers.
Since this is confusing, and easily forgotten, most style guides recommend splitting the declaration.
ListNode* p1;
ListNode* p2;
|
72,838,717 | 72,838,751 | Assignment and retrieval along with Post increment in single line in c++ | This is the code which I ran.
int minimumCardPickup(vector<int>& cards) {
int N = cards.size();
int l = 0, r = 0, res = INT_MAX;
unordered_map<int, int> pos;
while (r < N) {
if (pos.find(cards[r]) != pos.end()) {
l = pos[cards[r]];
res... | As you correctly identified, the problem is here:
pos[cards[r]] = r++; //Here
In earlier standards:
If you post-increment or post-decrement a variable, you should not read the value of it again before a sequence point (in this case, ;). This is because post-increment might occur any time during the statement (as long ... |
72,838,808 | 72,839,485 | C++ How to copy a part of vector into array? | I was making a copy from a large dynamic array to a small fixed size array.
for (int i = 0; i <= dumpVec.size() - 16; i++)
{
copy(dumpArr + i, dumpArr + i + 16, temp); // to copy 16 bytes from dynamic array
}
But I should use a vector instead of dynamic array. How to copy 16 bytes from vector into array?
for (int ... | copy(dumpArr + i, dumpArr + i + 16, temp); // to copy 16 bytes from dynamic array
can be written as
copy(&dumpArr[i], &dumpArr[i + 16], &temp[0]); // to copy 16 bytes from dynamic array
and now the same code works for vector and array too.
You can also use
copy_n(&dumpArr[i], 16, &temp[0]);
|
72,839,048 | 72,839,119 | XCode project's choice of C++ standard is not being respected | I'm playing around with XCode and C++, and I noticed that I change the C++ standard (i.e. C++98, C++11, GNU17, etc.) by clicking my project in the left sidebar. See screenshot at bottom of this post.
However, when I change to C++98, the C++ statement auto x = 6; still compiles and runs with no complaints. This is bad b... | There's another possibility you overlooked:
auto x = 6;
This happens to be a perfectly valid declaration in prehistoric times. auto meant something else entirely, and traces its lineage to C. Nobody was using it, so the keyword was re-purposed in C++11. But, this just happens to be valid code. You might want to try so... |
72,839,318 | 72,839,678 | How to use vector<MyObject> with ImGui::ListBox? | I'm trying to display a vector of objects in a listbox that will be rendered dynamically in every frame.
This is my class and I want to display every attribute later in the listbox:
class Waypoint {
public:
int x, y, z;
char action;
};
What I'm trying now as I don't really know is this:
Waypoint wp1;
wp1.actio... | ImGui::ListBox takes a char* as a displayed text, so you could not use a single char. You should re-design your class like this:
class Waypoint {
public:
int x, y, z;
std::string action;
};
Then use this function:
bool ImGui::ListBox(const char* label, int* current_item, bool (*items_getter)(void*, int, const ... |
72,839,746 | 72,839,804 | c++ problem | i want to NOT open the console while an program running | Ya know the console opens everytime when u execute an c++ script in any way i am making currently an GDI effect and this Console shows in the background up Here is the script but i dont think the script affects everything :/enter image description here
| You should use /SUBSYSTEM:WINDOWS with WinMain.
Alternatively, you could hide the console.
ShowWindow(GetConsoleWindow(), SW_HIDE);
|
72,839,766 | 72,839,794 | Resizing makes the window's content become thinner on each loop | I was trying to fix an issue where the window stretched out the content, and I finished fixing that. But after trying it out, it works halfway through only.
Here are some images and below is the explanation of the problem:
Image A: (when the app starts)
Image B: (after resizing once in any direction)
When I start the... | gluOrtho2D not only sets the projection matrix, but defines an orthographic projection matrix and multiplies the current matrix by the new matrix. You need to load the Identity matrix with glLoadIdentity before gluOrtho2D:
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
const GLfloat aspectRatio = (GLfloat)w / (GLfloat)... |
72,839,908 | 72,840,004 | Pointer to an object | I have a problem. I am developing a small chess-like game.
I am creating a class that manages the round, dividing them into 3 phases.
In the first step, check if the mouse has clicked on a Token.
In the second check select a location
And in the third he moves the selected Token.
I had thought in the first phase (after ... | You've redeclared your A pointer hiding the version you meant to assign to. See the comments
class TurnSystem{
...
Token* A; // class member A
...
};
void TurnSystem::Update(sf::Vector2i &mousePos) {
if (...){
if (...) {
if(...){
Token* A = soldier; // this is a loca... |
72,840,405 | 72,864,396 | How to create something like a sniffer? | I want to create an app to monitor and save the received data (for test my program!).
The device I'm working with have an API itself, and I want to create an app to get data from the device using CyPress CyAPI (FX3). For that the device should open and start streaming data.
My code is something like this for now:
#incl... | After sometimes, figuring out that I should read two endpoint asynchronously not synchronously.
std::tuple<std::vector<uint8_t>, std::vector<uint8_t>> USB::getData()
{
OVERLAPPED ov1, ov2;
ov1.hEvent = CreateEvent(NULL, false, false, L"CYUSB_IN");
ov2.hEvent = CreateEvent(NULL, false, false, L"CYUSB_IN");
UCHA... |
72,840,675 | 72,840,945 | How to create a vertical group of buttons in ImGui? | I have this ImGui menu:
I want to move the "Del" button to the red selected area in the previous image.
This is that part of the menu snippet:
class Waypoint {
public:
int x, y, z;
std::string action;
std::string display;
Waypoint(std::string action, int x, int y, int z) {
this->action = action... | I normally use ImGui::SetCursorPos() for this, as suggested by @thedemons. But there is also ImGui::BeginGroup();.
Remove the last ImGui::SameLine(); and wrap the two buttons in Begin/EndGroup. Here's a simplified example:
ImGui::Begin("Window");
ImGui::Button("x", ImVec2(200,100));
ImGui::SameLine();
ImGui::BeginGroup... |
72,841,415 | 72,841,514 | Is something wrong with my tasks.json settings? | I've been trying to use VSCode's tasks.json settings to automate the compiling process of my code. When I run the task I get an infinite loading loop, no errors are shown just the loading symbol and nothing happens.
{
"version": "2.0.0",
"tasks": [
{
"label": "MSVC Build",
"t... | "executable": "C:/Program Files/Microsoft Visual Studio/2022/Community/Common7/Tools/LaunchDevCmd.bat"
This above launches cmd.exe in the terminal of Visual Studio Code. Since LaunchDevCmd.bat never finishes, the queued command cl {$file} user32.lib && del *.obj does not run, until you enter exit in the running cmd.ex... |
72,841,438 | 72,841,469 | How to store array data as map key or increment frequency if array already in map? | My code:
map<array<byte, aes>, int> possible;
array<byte,aes> temp;
if (!possible.count(temp)) // if not found
possible.insert(pair<array<byte,aes>,int>(temp,1)); // insert
else
possible[temp]++; // if found increment frequency
I need to use an array with its data as a map key. An integer indicates the freque... | In C++ this code will work fine
possible[temp]++;
If temp exists then it's frequency will be incremented. If it does not exist then it will be inserted with a frequency of 0, which will then be incremented. This gives you exactly the same result as your code.
Looking at the documentation for QMap, it seems the above c... |
72,841,621 | 72,841,670 | finding all the values with given key for multimap | I am searching for all pairs for a particular key in a multimap using the code below.
int main() {
multimap<int,int> mp;
mp.insert({1,2});
mp.insert({11,22});
mp.insert({12,42});
mp.insert({1,2});
mp.insert({1,2});
for (auto itr = mp.find(1); itr != mp.end(); itr++)
cout << itr->fir... | You're calling find only a single time in your code. It's perfectly acceptable for this call to return the same value as mp.begin() resulting in you iterating though all the entries in the map before reaching mp.end().
You can use the equal_range member function to get iterators for the start and end of the elements wi... |
72,841,913 | 72,841,956 | Why doesn't RVO happen with structured bindings when returning a pair from a function using std::make_pair? | Consider this code, which defines a simple struct Test (with a default constructor and copy constructor) and returns a std::pair <Test, Test> from a function.
#include <iostream>
#include <utility>
using namespace std;
struct Test {
Test() {}
Test(const Test &other) {cout << "Test copy constructor called\n";}... | std::make_pair is a function that takes the arguments by reference. Therefore temporaries are created from the two Test() arguments and std::make_pair constructs a std::pair from these, which requires copy-constructing the pair elements from the arguments. (Move-constructing is impossible since your manual definition o... |
72,841,986 | 72,842,271 | why does C++ allow a declaration with no space between the type and a parenthesized variable name? | A previous C++ question asked why int (x) = 0; is allowed. However, I noticed that even int(x) = 0; is allowed, i.e. without a space before the (x). I find the latter quite strange, because it causes things like this:
using Oit = std::ostream_iterator<int>;
Oit bar(std::cout);
*bar = 6; // * is optional
*Oit(bar) = 7;... | One requirement when defining the syntax of a language is that elements of the language can be separated. According to the C++ syntax rules, a space separates things. But also according to the C++ syntax rules, parentheses also separate things.
When C++ is compiled, the first step is the parsing. And one of the first s... |
72,842,307 | 72,842,940 | Measuring packet per second for connected clients IP addresses | How can we determine the packet rate of clients connected to our server in case of multi client server using Winsock. The idea I came up with is keeping a frequency map for IP addresses of all the clients and storing the packets count for some arbitrary amount k seconds. Now after k seconds we traverse the map and see ... | Per comments:
If someone is sending too fast, I'd like to block him permanently rather than receiving his messages less frequently. Something like this is what I'm trying to achieve
If this was UDP, I'd 100% be onboard with what you are trying to do and give the code I have. But this is TCP and your assumptions are ... |
72,842,442 | 72,846,416 | How to draw a line along the Z axis in openGL | I'm stuck drawing a line along the Z-axis. I have checked the related topic that OpenGL Can't draw z axis but even if I change my camera position, I still can't see my line; meanwhile, I can see a square draw in XZ-plane.
here is my code:
int main()
{
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
... | Assuming that you want to draw a 3D line, the size argument of glVertexAttribPointer is wrong. By setting it to two, you tell OpenGL to read only two values and add 0 for z.
Set the size to 3 as in
glVertexAttribPointer(0, // attribute 0 matches aPos in Vertex Shader
3, // size
... |
72,842,534 | 72,842,628 | Manually validate date/time comes before another | I have to manually verify a time/date format of the type day_hh:mm:ss so 1_09:00:01 comes before another and return a boolean.
Ive come with this but there are still some tests that are not validated correctly. Any ideas where I could refactor?
bool DateHour::operator<(const DateHour& date_hour) const{
if(days <= d... | Attempting to squish days/hours/minutes/seconds together into one combined chunk of logic, in the shown code, leads to many hard to understand logical flaws. The easiest way to solve a complicated problem is break it up into smaller problems, and solve them individually.
if(days < dh.days)
return true;
if(days > d... |
72,842,789 | 72,850,198 | What are all the requirements of a QObject derived class? | I'm working on my first non-trivial project using the Qt Framework and to help maintain consistency across documents and to ensure I don't forget some small requirement I've decided to make a template document demonstrating the member functions, macros, etc. needed to subclass QObject. I also want to be able to fully u... | As Jeremy Friesner suggested, the requirements are not that strict. The situation is more like this:
If your class uses signals and/or slots, it must both have the Q_OBJECT macro and be derived from QObject,
If it only uses other meta-object functionality, such as Q_PROPERTY declarations, it can use the Q_GADGET macro... |
72,843,016 | 72,843,033 | "if" statement syntax differences between C and C++ | if (1) int a = 2;
This line of code is valid C++ code (it compiles at the very least) yet invalid C code (doesn't compile). I know there are differences between the languages but this one was unexpected.
I always thought the grammar was
if (expr) statement
but this would make it valid in both.
My questions are:
Why ... | This is a subtle and important difference between C and C++. In C++ any statement may be a declaration-statement. In C, there is no such thing as a declaration-statement; instead, a declaration can appear instead of a statement within any compound-statement.
From the C grammar (C17 spec):
compound-statement: "{" blo... |
72,843,254 | 72,843,314 | VSCode compile C++ with external classes - undefined reference to `MyClass::MyClass()' | Error when compiling my main file & external Class file using VScode.
file structure:
project/
--main.cpp
--MyClass.cpp
--MyClass.h
MyClass.h
#ifndef MY_CLASS_H
#define MY_CLASS_H
class MyClass
{
public:
MyClass();
};
#endif
MyClass.cpp
#include "MyClass.h"
#include <iostream>
#include <string>
MyClass::MyC... | Change main.cpp's includes to:
#include <iostream>
#include <string>
#include "MyClass.cpp"
By including MyClass.cpp in main.cpp and compiling like this:
g++ -o main main.cpp
you end up including MyClass.h by virtue of it being included in MyClass.cpp. By including MyClass.cpp, you can successfully compile.
If you wa... |
72,843,313 | 72,843,487 | Happens Before relationship in the same thread | I am reading the book "C++ Concurrency in Action" section 5.3 on Memory Model of C++ and listing 5.5 below confuses me:
std::atomic<bool> x,y;
std::atomic<int> z;
void write_x_then_y()
{
// Is there a Happens-Before relationship for statement (1) and (2) below?
x.store(true,std::memory_order_relaxed); // --> (1)
... | An evaluation which is sequenced-before another evaluation also happens-before it.
Sequenced-before is a relation between evaluations in the same thread and independent of synchronization mechanism like e.g. atomic load/stores with non-relaxed memory orders.
Happens-before just extends the sequenced-before relation for... |
72,843,628 | 72,845,893 | Getting buffer overflow even though I have included the condition that avoids buffer flow (Question 74. Search a 2D Matrix) from leetcode | I was solving Q 74. Search a 2D Matrix from leetcode and I am getting heap buffer overflow error for my solution even though I have included the statements which should avoid buffer overflow which are:
row = (t1 + (t2 - t1) / 2)
col = (t1 + (t2 - t1) / 2)
Here is my code:
bool searchMatrix(vector<vector<int>>& matrix,... | t2 = matrix[0].size(); is out-of-bounds.
Did you mean
t2 = cols - 1;
|
72,843,678 | 72,844,511 | Cant make comparison between two values as total 1 is corrupted and become total 2 value | i have a problem. my total1 and total2 cant make comparison. my program will show that player 2 wins even player 1 score higher. so when i cout total1 and total2, it shows that total 1 value is corrupted and become total2 value and thats why they can compare. is it because if that turn for player 2 has came to calculat... | So essentially your code is this
for (int i = 1 ; i <= count; ++i)
{
...
float total1 = 0, total2 = 0;
total1 = ...;
total2 = ...;
if (i == 1 || i == 3 || i == 5 || i == 7 || i == 9)
cout << endl << "Your mark for this round is " << total1;
if (i == 2 || i == 4 || i == 6 || i == 8 || i =... |
72,844,051 | 72,844,087 | using RtlCompareString to compare user data crashes OS | I have the following code which is responsible to receive and send data between my mini-filter driver and user-mode:
NTSTATUS MiniSendRecv(PVOID portcookie, PVOID InputBuffer, ULONG InputBufferLength, PVOID OutputBuffer, ULONG OutputBufferLength, PULONG RetLength) {
PCHAR msg = "Hi User";
PCHAR userData = (PCHA... | RtlCompareString compares counted strings. What you have are null terminated strings. Just use the regular strcmp function, or since you seem to be trying to do a case insensitive string comparison you could try the non-standard _stricmp function.
|
72,844,097 | 72,844,480 | how to make cin only accept a single character and int accept only numbers? | How can I make cin accept only a single letter in char datatypes and numbers only in double/int datatypes.
#include <iostream>
using namespace std;
int main (){
char opt;
int num1, num2, sum;
cout << "A. Addition" << endl << "B. Subtraction" << endl;
cout << "Enter option: "; cin >> opt;
//if I put... | By definition, operator>> reading into a char will read in exactly 1 character, leaving any remaining input in the buffer for subsequent reading. You have to validate the read is successful and the character is what you are expecting before using it.
And likewise, operator>> reading into an int will read in only number... |
72,844,799 | 72,844,859 | insertion in unordered map in c++ | #include<iostream>
#include<unordered_map>
#include<list>
#include<cstring>
using namespace std;
class Graph {
unordered_map<string, list<pair<string, int>>>l;
public:
void addedge(string x, string y, bool bidir, int wt) {
l[x].push_back(make_pair(y, wt));
if (bidir) {
l[y].push_bac... | When you use the subscript operator on l, like in l[x], it returns a reference to the value mapped to the key x (or inserts a default constructed value and returns a reference to that).
In this case, the type of the value is a std::list<std::pair<std::string, int>> and that type has a push_back member function.
It's th... |
72,844,949 | 72,847,501 | Scalability Qt 5.15 Android | Since it is incredibly difficult to find a developer of android applications for qt, I will ask a question here, suddenly someone was doing this.
How to solve the scalability problem on different devices? Ideally, the application should look the same on all screens, from m/hdmi to xhdpi, if there were only 6 types of s... | In our case, we did not want to fill entire Pad and/or TV screen, and our appraoch for handling responsive-size was to:
Make size-preset: find our prefered screen-size-preset, on which we base all view constants (sizes).
We did pick 320x548, which is smallest iPhone safe-area.
Fit-to-screen: hard-code said size-pre... |
72,845,811 | 72,848,384 | Does localtime return a heap allocated tm* | As you know the <time.h> standard header defines the struct tm and a function called localtime.
Does localtime make a heap allocation?
Or is it allocated in the stack?
It returns a pointer but this could be just a pointer to the stack value, right?
| The relevant part of the C Standard (C18) has this language:
7.27.3 Time conversion functions
Except for the strftime function, these functions each return a pointer to one of two types of static objects: a broken-down time structure or an array of char. Execution of any of the functions that return a pointer to one o... |
72,846,005 | 72,846,040 | Return Base class shared pointer using derived class C++ | I have a an interface:
/*base.hpp */
class Base {
protected:
Base() = default;
public:
Base(Base const &) = delete;
Base &operator=(Base const &) = delete;
Base(Base &&) = delete;
Base &operator=(Base &&) = delete;
virtual ~Base() = default;
virtual void Function1() = 0;
};
Als... | This should do:
std::shared_ptr<Derived> d = std::make_shared<Derived>();
std::shared_ptr<Base> getBase() { return d; }
|
72,846,231 | 72,848,984 | Aggregation between two derived classes | Can there be an aggregation relationship type between two derived classes of one base class (for example, one class contains vector of another)?
Can it be implemented in C++ and if so, is it considered a good practice and does not violate logic or not?
Example in picture:
| Short answer is yes, and your class diagram shows an example of when you'd do this. Except buttons are actual, "physical" items on screen, and have unique identity, you can't just copy them in a data structure, you would probably use pointers to these buttons, in C++ like this using smart pointer:
std::vector <std::uni... |
72,847,056 | 72,847,508 | Busy/wait or spinning pattern in multithreaded environment | https://www.linkedin.com/pulse/how-do-i-design-high-frequency-trading-systems-its-part-silahian-2/
avoiding cache misses and CPU’s context switching
how does busy/wait and spinning pattern avoids context switches if it runs two threads in one core ?
It will still have context switches between these two threads(produ... |
how does busy/wait and spinning pattern avoids context switches if it runs two threads in one core ?
When a thread perform a lock and the lock is taken by another thread, it make s system call so the OS can know that the thread is waiting for a lock and this should be worthless to let it continue its execution. This ... |
72,847,398 | 72,847,823 | Find key in std::unordered_map won't find an existing key | I'm trying to make a simple ResourceManager which uses an ordered_map to find how to import files using the extension :
#include <iostream>
#include <unordered_map>
#include <string>
class ResourceManager;
typedef void (*ImporterFn)(const std::string& path);
// manage files and what's in the assets/ folder
class Res... | Problem is that your container is using const char* as a key. Note that std::unorderd_map uses standard operator == for type provided as key. In case of const char * this equal operator compares only a pointers.
So only case where you will find item is when you use same pointer. Pointed contest doesn't meter.
Now when ... |
72,847,606 | 72,847,759 | about c++ templates and parameter pack | template<class... Cs>
void func(Cs... cs){
};
template<class T, class... Cs>
void func1(T s){
func<Cs...>(/* the problem */);
};
int main(){
char s[]="HI THERE!";
func1<char*,char,char,char>(s);
return 0;
}
so the func1() call the func(), the two functions are specialized by the same template parame... | If I understand it correctly, you want to use the parameter pack and expand those number of elements in s:
#include <cstddef>
#include <utility>
template<class... Cs>
void func(Cs&&... cs){ // 'H', 'I', ' '
};
template<class T, std::size_t... I>
void func1_helper(T s, std::index_sequence<I...>) {
func(s[I]...);
}... |
72,848,060 | 72,848,083 | Operator overload for ostream not working with user defined class | I have this simple program and when i try to cout << 75.0_stC ; i have multiple errors and i don't know why.This things only happen when i pass my temperature object via reference.
class temperature
{
public:
long double degrees;
temperature(long double c): degrees{c}{}
long double show()con... | You likely need to take a const reference to the argument you'd like to print:
ostream & operator<<(ostream &ekran, const temperature &t)
Temporary won't bind to the non-const reference argument.
|
72,848,431 | 72,848,490 | Constexpr methods for nonconstexpr class | Is there any reason to add constexpr to class's methods if class hasn't any constexpr constructor? Maybe compiler can do some optimizations in this case?
| Yes, one obvious case is when the class is an aggregate class. Aggregate initialization doesn't call any constructor, but can still be used in constant expression evaluation.
Even if the class is not an aggregate class, you can still call a constexpr member function in constant expression evaluation if the member funct... |
72,848,537 | 72,848,768 | Is this possible in c++11? A class with same name but one with template. Ex: Result and Result<T> | Is this possible in c++11? Two class with same name but one with template.
Ex:
A class with name Result and another with name Result<T> to use like
return Result("Message");
or
Result<Date>("Message", date);
For example, I tried this without success:
template<>
class response
{
public:
bool sucess;
... | A couple C++11 options:
Provide a default template argument of void and specialize on that.
template<class T = void>
class response
{
public:
bool success;
std::string message;
int code;
T data;
};
template<>
class response<void>
{
public:
bool success;
std::string message;
int code;
};
Th... |
72,848,743 | 72,851,033 | Forking a process with threads containing sockets in C++ | I have the following C++ - scenario under CentOS.
Process P1 contains:
passive listening socket with descriptor D1.
1 incoming connection (socket with D2).
1 outgoing connection (socket with D3).
thread T1 with 1 outgoing connection (socket with D4).
Incoming socket connections are created with:
socket( AF_INET,SOCK... |
I close D1 in P2 directly, because I don't want to listen in different
processes at the same port, although this would be possible. Correct?
Yes.
Because all FD's were copied (Ref-Counted?), I can safely close D2 and
D3 in P2 without endangering the communication in P1, right?
Yes.
And if you are not going interact... |
72,848,816 | 72,849,041 | Does compound assignment of two unsigned integers of the same type always operate as if using that type's modular arithmetic? | Here is a conjecture:
For expression a op b where a and b are of the same unsigned integral type U, and op is one of the compound assignment operators (+=,-=,*=,/=,%=,&=,|=,^=,<<=,>>=), the result is computed directly in the value domain of U using modular arithmetic, as if no integral promotions or usual arithmetic co... | Counter example:
int has width 31 plus one bit for sign, unsigned short has width 16. With a and b of type unsigned short, after integral promotions, the operation is performed in int.
If a and b have value 2^16 - 1, then the mathematical exact result of a * b in the natural numbers would be 2^32 - 2^17 + 1. This is la... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.