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 |
|---|---|---|---|---|
73,090,536 | 73,090,845 | ~__nat() deleted error in ThreadPool implementation | I am trying to implement a ThreadPool,but the clang compiler is giving me an error, which I do not know how to fix. My ThreadPool consists of 1 thread for planning and adding tasks to the queue (Scheduler), 1 thread for taking the tasks out of the queue and assigning separate threads to them(Executor), and child thread... | The issue that cur_task is a std::optional<Task> and you pass this std::optional<Task> directly to executeChild(). But executeChild() expects not a std::optional<Task> but a Task. Since you check if the optional is nullopt before creating the thread, you probably want to use
std::thread child_thread {&Executor::execute... |
73,091,092 | 73,091,330 | How does the time function know the current time of the PC? Does it use the Internet to sync with a time server as the computers do? | How does the time function know the current time of the PC? I know how computers know the time. But how does the C++ time function implemented? Does it use the Internet to sync with a time server as the computers do? Or does it use the internal clock of the computer?
| The function returns the current calendar time, which the program got by asking the computer what the current time is.
The function doesn't require internet, just your computer's internal clock :)
If you want to learn more on this topic, I highly recommend reading
Programiz's C-Time.
|
73,091,534 | 73,091,605 | How do I split a record of text into text file in C++ | So I'm working on a simple file manipulating project where I need to append a new text on a single line, so, to visualize that suppose I have a text file called main.txt and in that file it contains a row of text that looks like this:
[AB]
1
2
Now that lets say I want to add another text: [CB] & 4,5, then I want the u... | #include <iostream>
#include <fstream>
using namespace std;
int main()
{
// we have only 1 column in this example and also we have only 2 rows of data
int columnCount = 1, dataRows = 2;
string newColumnName;
int data1, data2;
cout << "enter the column name: ";
cin >> newColumnName;
// getti... |
73,091,752 | 73,091,984 | How can I get the return of a function called from a vector std::vector that contains std::function | I have a structure that in its constructor receives an initialization list std::initializer_list<P...> of type parameter pack. That constructor is filled with lambda functions, and they are saved in a std::vector<P...>.
How can I get the return of those functions when traversing the vector calling each function?
Here i... | You should be using std::tuple, if you want to store arbitrary callable objects.
You can combine std::index_sequence with a fold expression for calling the functions:
#include <iostream>
#include <string>
#include <tuple>
#include <utility>
using std::string;
struct my_type {
my_type(){}
my_type(string _value... |
73,091,807 | 73,092,305 | How can I write field value to a json file with boost? | I have some json file:
{
....
....
"frequency_ask": 900
}
and need to change field frequency_ask to 1200 for example.
I called my function
void setFieldToJson(std::string json, std::string field, int value)
{
boost::property_tree::ptree pt;
pt.put(field, value);
std::ostringstream json;
bo... | Your problem is most likely that you're using Property Tree, which is NOT a JSON library.
Alternatively, it could be that your input is not valid JSON.
Here's my take using Boost JSON:
Live On Coliru
#include <boost/json/src.hpp> // for header-only
#include <fstream>
void setFieldToJson(std::string const& filename, st... |
73,091,911 | 73,092,044 | Compilation error on diamond problem(inheritance) | Why does the code below throw the following compilation error on msvc ?
No default constructor exists for class 'Person'
If I don't create a default constructor in the class Person, then should I delete the constructor of Employee and Student that takes only one argument and call Employee(name,age,grade) and Student(... | The cause of the problem:
Both Employee and Student have constructors that do not call the only available constructor of the base class Person (requireing name and age parameters). Therefore the compiler will attempt to use a default constuctor fo the base class which is not available.
You can handle it the following w... |
73,091,965 | 73,092,716 | Can somebody help me with EventHandling on WXWidgets | while trying to make some first progress with WXWidgets in C++ I´ve got on a problem.
As youre able to see in the Code below, I´m trying to Handle an Button-Click-Event from an WXWidget-Application.
The main Problem is that the dedicated Method TopPanel::OnClick() doesnt run. (Nothing is print to console)
Possible Erro... | First things first, your given example successfully calls the OnClick method. So your claim that OnClick is not called is not correct.
Now that being said, with newer(modern) wxWidgets you can also use dynamic event table using Bind instead of static event table as shown below. The changes made are highlighted as comme... |
73,092,727 | 73,097,122 | Is there a way to reference/index/pointer an item in a std::stack? | As the title says, using std::stack is there a way to reference any item by reference/index/pointer without popping? If not how could I achieve this?
My use case is, I am making a vm for learning and I want to reference the stack items in the std::stack so I can push and access my local stack variables. I originally wa... | Yes, there is an easy way to access the data through its underlying container.
Normally, all this is not necessary because you always can use the underlying container in the first place.
But if you want to do that for exceptional purposes, then simply take the address of the top(). This will be the last element in the ... |
73,092,753 | 73,156,771 | Problem building C++ binary using vcpkg and cmake in Github action macos-12 | Works fine building on Linux and Windows.
But in macos I get:
/usr/local/bin/g++-11 -isysroot /Applications/Xcode_13.4.1.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.3.sdk -Wl,-search_paths_first -Wl,-headerpad_max_install_names CMakeFiles/Calculator_Test.dir/src/speedtest.cpp.o CMakeFiles/... | Solved the problem by setting the environmental variables to the correct compiler before setting up vcpkg.
In the github actions yml file:
- name: Set C++/C compiler on macOs
shell: bash
run: echo "CC=gcc-11" >> $GITHUB_ENV; echo "CXX=g++-11" >> $GITHUB_ENV; cat "$GITHUB_ENV"
if: runner.os... |
73,093,306 | 73,109,037 | MariaDB C++ Connector errors when attempting connections from multiple threads | Using the MariaDB C++ Connector on ubuntu 20.04, and gcc compiler. During load test of a webserver application it was discovered that anytime there was more than a single concurrent connection the server would crash. This was narrowed down to the connect member of the mariadb driver. The errors that were being reported... | It is a bug in Connector/C++.
To track progress, please check https://jira.mariadb.org/browse/CONCPP-105
|
73,093,514 | 73,094,498 | Is it possible to create variables based on the amount of arguments in a function? | For example, I have a thread class with a template constructor which can take in an undefined amount of arguments:
template<typename _FunctionType, typename ... _ArgType>
thread(const _FunctionType* function, _ArgType ... arguments)
{
_FunctionType Function1; // Creates variable for function
_ArgType Argument1;... | You could write template specialization for functions with 0, 1, 2, 3, 4, 5, ... arguments but that defeats the purpose of having a template.
You can't really give each argument a unique name but you can put them into a std::tuple.
#include <tuple>
template<typename _FunctionType, typename ... _ArgType>
void thread(co... |
73,093,575 | 73,093,701 | Call overloaded, derived function from C++ class on base object does not call the overloaded function | Here is a simplified example (OnlineGDB):
#include <iostream>
using namespace std;
class Base {
public:
virtual ~Base() {}
virtual int test(Base* parent) = 0;
};
class Test : public Base {
public:
~Test() {}
int test(Base* parent) { return 10; }
int test(Test* parent) { return 20; }
};
int main(... | When you cast a class, the most specific information is related to the type in the hierarchy you are casting it to.
Base vtable doesn't have that overload so there's no way the compiler can know at compile time that another overload exists.
If you think about how the dynamic dispatch is implemented it's rather trivial ... |
73,094,049 | 73,094,124 | How to get unique elements from vector using stl? | I have a vector of strings. For now take:
std::vector<std::string>{
"one","two","three","two","ten","six","ten".......
}
Now I want to filter out only unique strings in the vector, and in the same order as they are.
Is there a standard library function for this?
EDIT: I need to discard the repeated values.
| If you want to remove the duplicate while keeping the order of the elements, you can do it (inplace) in O(n log(n)) like this:
std::vector<std::string> v{"one", "two", "three", "two", "ten", "six", "ten"};
// Occurrence count
std::map<std::string, int> m;
auto it = std::copy_if(v.cbegin(), v.cend(), v.begin(),
... |
73,094,942 | 73,095,300 | assignment of read-only location - Boost Geometry Register Point 2D | I am currently trying to implement a motion-planning algorithm and have been using Boost's RTree to do so. Up until now, the RTree has stored std::pair<boost::geometry::model::point<double, 2, bg::cs::cartesian>, unsigned int> and has worked just fine in answering nearest neighbor queries.
Externally, I make use of a c... | What version of boost is that? BOOST_GEOMETRY_REGISTER_POINT_2D_GET_SET takes 7 parameters, not 5, and it has done so ever since the source file appeared in January 2010, which means Boost 1.47.0.
Looking at the docs, it looks like the () are not supposed to be included on the member functions anyways.
Finally, you hav... |
73,095,016 | 73,095,040 | list.remove_if() crashing the program | I'm working on a game and I'm trying to add collectables. I'm trying to remove the object from the list after the player has collided with it, but it ends up crashing and says:
Unhandled exception thrown: read access violation.
__that was 0xDDDDDDE9.
It says this on the for loop statement, but I think it has to do wit... | I don't understand your approach, you loop the rects, then when you find the one you want to remove, you search for it again through list<T>::remove_if.
I think that you forgot about the fact that you can use iterators in addition to a range-based loop:
for (auto it = brainFrag.begin(); it != brainFrag.end(); /* do not... |
73,095,031 | 73,095,047 | braced-initialization allows creation of temporary of a *private* struct | I just read the following article from Raymond Chen's excellent 'The Old New Thing':
https://devblogs.microsoft.com/oldnewthing/20210719-00/?p=105454
I have a question about this, best described in the following code snippet. Why is the initialization of 'x3' allowed at all? I don't see any semantic difference betwee... | Accessibility restricts only which names may be written out explicitly. It does in no way prevent usage of a type.
It is always possible to e.g. use decltype on a function returning the private type and then give it a new name and access it fully through that name or to use template argument deduction to give inaccessi... |
73,095,189 | 73,097,589 | rust libclang, why am I parsing only c functions from a cpp file? | I am trying to write a rust script that parses a C++ file, finds all extern C declared functions and prints them out.
To that effect I have this first attempt:
use clang::*;
use clap::{Arg, App};
fn main()
{
let matches = App::new("Shared C++ API parser")
.version("0.0.1")
.author("Makogan")
... | UnexposedDecl is actually not the function definition, but the extern 'C' itself.
If you print all items recursively, you will see what the tree actually looks like:
fn print_rec(entity: Entity, depth: usize) {
for _ in 0..depth {
print!(" ");
}
println!("{:?}", entity);
for child in entity.ge... |
73,095,254 | 73,095,312 | How is vector<vector<int>> "heavier" than vector<pair<int,int>>? | During a recent interview, I suggested using vector<pair<int,int>> over vector<vector<int>> since we only wanted to store two values for every entry in the vector. I said something to the tune of "we should use vector<pair<int,int>> over vector<vector<int>> since the latter is heavier than the former".
After the codin... | Each vector is a single contiguous area of memory, dynamically allocated.
Let's say that you have 1000 values you'll be working with.
std::vector<std::pair<int, int>>
This gets you a single, contiguous block of memory, for 2000 integers.
std::vector<std::vector<int>>
This gets you a single contiguous block of memory ... |
73,095,639 | 73,095,654 | C or C++ : How to keep just "one block in memory" at the time? | In "Introduction to Algorithms" there is the following exercise:
Consider implementing a stack in a computer that has a relatively small amount of fast primary memory and a relatively large amount of slower disk storage. The operations PUSH and POP work on single-word values. The stack we wish to support can grow to b... | You DON'T.
You write the code with the mmapped stack and count the number of times you change page in simulation and let the OS cache as much as it wants. The best way to track page changes is in the push() and pop() functions. Cast the pointer to an integer, use a mask to get rid of the low bits and compare to previou... |
73,095,647 | 73,095,753 | why regular expression match result is empty | this is code
#include <iostream>
#include <regex>
using namespace std;
static void search_by_regex(const char *regex_s,
const string &s)
{ // ①
regex reg_ex(regex_s);
smatch match_result; // ②
cout.width(14); // ③
if (regex_search(s, match_result, reg_ex))
{ ... | In short
With your current setup, you will return after your first match, as you did not set the global flag (/.../g). Consider the following tokens: ? or *. They will return a null match ("") if nothing matches immediately. Your regex, having such tokens, will return a null match if the first character does not match ... |
73,095,700 | 73,095,855 | Segmentation fault on vector class implementation | As for many coding tests STL is not allowed so I am trying to implement vector class. To represent the graph I am using an adjacency list. It's giving me segmentation fault at new_allocation method. Also sometimes I get correct output when I run code but when I debug I get SegFault.
Following is my code.
#include <iost... |
please initialize the arr in the default ctor:
vector() {
s = c = 0;
arr = nullptr; // (1)
}
As pm100 mentioned, please pick up the right array to delete[].
void new_allocation() {
T *temp = new T[s + 10]; // SEGMENTATION FAULT HERE
c = s + 10;
for (int i = 0; i ... |
73,095,750 | 73,103,885 | Method DrawRectanglePro() not rendering rectangle | I have been trying to test out raylib and I am trying to render rectangles at an angle, but I am unsure as to why they will not render. The method DrawRectangle() does work, despite DrawRectanglePro() not working.
#include <iostream>
#include "raylib.h"
int main() {
InitWindow(800, 800, "More Raylib Practice");
... | It looks like you're misusing the origin parameter, in your case { 400, 400 }. The origin parameter is used to set the origin of the draw point from the referenced rectangle.
Your code is saying, on a 10 x 10 square, move right 400, and down 400, then draw that at 10, 10. If you setup a 2d camera you would find your w... |
73,095,828 | 73,097,668 | Maximal value of the Boost Multiprecision type 'float128' gives me a compilation error with GCC in C++20 mode | This simple code can't be compiled with the -std=c++20 option:
#include <limits>
#include <boost/multiprecision/float128.hpp>
namespace bm = boost::multiprecision;
int main()
{
auto const m = std::numeric_limits<bm::float128>::max();
}
The compilation command and its error output:
hekto@ubuntu:~$ g++ -std=c++20 te... | The documentation states:
When compiling with gcc, you need to use the flag --std=gnu++11/14/17, as the suffix 'Q' is a GNU extension. Compilation fails with the flag --std=c++11/14/17 unless you also use -fext-numeric-literals.
So you need to specify --std=gnu++20 instead of --std=c++20. The boost documentation is n... |
73,096,623 | 73,097,080 | How to hide another class ui using Qt C++? | I've been trying to hide another class ui, but I can't figure it out.
As an example I have the MainWindow class and other two classes. This is a scheme of the MainWindow ui:
[---------------][---------------]
[ Class A ui ][ Class B ui ]
[---------------][---------------]
The top & bottom lines are just to ou... | one way is to add a signal in ClassA and emit it when clicking on the considered push button:
#ifndef CLASSA_H
#define CLASSA_H
#include <QWidget>
namespace Ui {
class ClassA;
}
class ClassA : public QWidget
{
Q_OBJECT
public:
explicit ClassA(QWidget *parent = nullptr);
~ClassA();
public signals:
... |
73,097,179 | 73,097,238 | Accessing C++ struct members by indices and undefined behavior | Say, we would like to access members of a C++ structure by indices. It could be conveniently implemented using unions:
#include <iostream>
struct VehicleState
{
struct State
{
double x, y, v, yaw;
};
union
{
State st;
double arr[4];
};
};
int main()
{
VehicleState... | Actually it's perfectly fine to read from a union member other than the one you have written too as long as you only access a common prefix. So
union {
State st;
struct {
double x;
};
} state;
state.st.x = 1;
if (state.x == 1) // perfectly fine.
The problem is that the rules for the layout of stru... |
73,097,219 | 73,097,850 | finding max catches if you can move at a certain speed while objects appear at particular timestamps? | I faced this problem in an interview, I couldn't solve it in interview.
I recall a similair problem that i solved during IOI though cannot recall it.
Given N houses in a line.
each of M pokemon makes an appearance at a house exactly once.
ex - a pokemon appears for an instant at 5th house at time = 6.
another pokemon a... | Observation: Each Pokemon disappears right after they appear, so we need to be at a house at time=x to catch the Pokemon. If we can not make it in time, we never stop there.
Solution: create a new directed graph G=(V,A) where each v_i in V represents a house h_i = house(v_i) where a Pokemon appears at time t(v_i).
Crea... |
73,097,221 | 73,097,679 | How can I simplify the function with two loops, or is it better to leave it as it is? | I have two almost identical functions where two loops are the same, but the code inside is different, how can I do it more correctly Leave it as it is or change both functions to one or how you do when faced with such code, just wondering which method do you think is correct .
template <class T1>
void function_... | Example (without template, to better show the underlying principle).
You can pass the code to test as a std::function.
#include <functional>
#include <vector>
void Test(std::function<void(int,int, std::vector<int>&)> fn, std::vector<int>& array_test)
{
for (int h = 0; h < 3; ++h) {
for (int i = 0; i < 7; +... |
73,097,240 | 73,097,335 | Problems with cin and reading input | I am new to C++ and I have a problem with cin in my code.
When I run this code, after I enter some words, it just skips and ignores the second cin in the code and I don't understand why.
I read that it happens because of Enter and Space in the new line, and I should use cin.ignore(), but it still does not work. For the... | for (string input; cin >> input;) {
words.push_back(input);
cin.ignore();
}
So, as you say in a comment, the user ends this loop by entering end of file (ctrl-Z on Windows console). After that, the file is at end. You can not continue reading from it, it is closed.
You have to figure out some other way to end ... |
73,097,267 | 73,180,619 | how to use mold linker with bazel and gcc10? | mold is the latest modern linker with high speed, I want to use it to replace default ld linker when compiling our heavy c++ repository.
I use Bazel + GCC 10.2 to compile, and mold docs provide a gcc -B/mold/path solution. However I don't find a way to pass this CLI option to bazel.
I tried bazel build --linkopt=-B/usr... | Peterson's answer can work in most cases, but if you are using an outdated Bazel version such as 0.2x like me, there is a bug for Bazel link stage. The bug leads to user link flags always be overwrite by Bazel default link flags.
To verify the bug, run bazel build --subcommands --linkopt=-B/any_path <your-target>, and ... |
73,097,441 | 73,097,576 | Concept constrained member function having dependent argument types | I was doing some experiments with concepts, and I was trying to have constrained member functions that must be instantiated only if a concept is satisfied:
template <typename T>
concept Fooable = requires(T o)
{
o.foo(uint());
};
template <typename T>
concept Barable = requires(T o)
{
o.bar(uint());
};
class ... | Since fun is not a template function, typename T::BarType is always instantiated and produces a hard error if T does not have a type alias named BarType. You might want to do
template <typename T>
class C
{
public:
template<Fooable U = T>
requires requires { typename U::FooType; }
void fun(typename U::Foo... |
73,097,919 | 73,098,000 | how to check a point if it lies inside a rectangle | I have a rectangle Rect (x,y,w,h) and a point P (px, py).
x and y are the top left coordinate of the rectangle.
w is it's width.
h is it's height.
px and py are the coordinate of the point P.
Does anyone knows the algorithm to check if P lies inside Rect.
Surprisingly, I couldn't find any correct answer for my question... | The point P(px, py) lies inside the Rectangle with top left pt. coordinates (x,y) and width and height w&h respectively if both the conditions satisfy:
x < px < (x+w)
y > py > (y-h)
Hope this helps :)
|
73,098,028 | 73,098,145 | Why is the size of the union greater than expected? | #include <iostream>
typedef union dbits {
double d;
struct {
unsigned int M1: 20;
unsigned int M2: 20;
unsigned int M3: 12;
unsigned int E: 11;
unsigned int s: 1;
};
};
int main(){
std::cout << "sizeof(dbits) = " << ... | members of a bit field will not cross boundaries of the specified storage type. So
unsigned int M1: 20;
unsigned int M2: 20;
will be 2 unsigned int using 20 out of 32 bit each.
In your second case 12 + 20 == 32 fits in a single unsigned int.
As for your last case members with different storage type can... |
73,098,525 | 73,098,570 | std::sort not sorting vector properly | I want to sort my vector of pairs by the ratio of the first to the second value of the pair. I am using C++ STL sort function but, I don't know, It is not sorting the vector properly here is my code:
comparator
bool comparator(const std::pair<int, int> &item1, const std::pair<int, int> &item2)
{
return (item1.first... | It seems you want to compare float results like
return (static_cast<double>( item1.first ) / item1.second) <
(static_cast<double>( item2.first ) / item2.second);
In this case the vector will be sorted in the ascending order and the result will be
1, 4
3, 5
4, 5
6, 7
8, 8
If you want to sort the vector in th... |
73,098,660 | 73,103,902 | "Merge" two signatures of operator () overload into one in a template class, how? | Let's suppose I have the following class in an header file header.h:
#pargma once
#include <type_traits>
#include <iostream>
#include <sstream>
struct foo
{
// Utils struct
template <class T, class... Ts>
struct is_any: std::disjunction <std::is_same <T, Ts>... >{};
// Standard case
template <class T_os, ... | You could make operator() a front-end for the real implementation. You can then make it forward the arguments to the real implementation and add std::cout if needed.
Example:
struct foo {
template <class T, class... Args>
const foo& operator()(T&& first, Args&&... args) const {
if constexpr (std::is_bas... |
73,098,915 | 73,098,965 | How to convert a string to array of strings made of characters in c++? | How to split a string into an array of strings for every character? Example:
INPUT:
string text = "String.";
OUTPUT:
["S" , "t" , "r" , "i" , "n" , "g" , "."]
I know that char variables exist, but in this case, I really need an array of strings because of the type of software I'm working on.
When I try to do this, th... | If you are going to make string, you should look at the string constructors. There's one that is suitable for you (#2 in the list I linked to)
for (int i = 0; i < text.size(); i++) {
process[i] = string(1, text[i]); // create a string with 1 copy of text[i]
}
You should also realise that sizeof does not get you th... |
73,099,107 | 73,099,138 | How to sort std::multimap entries based on keys and values via custom Compare predicate? | I'm looking for a way to sort std::multimap's entries in ascending order by keys, but if the keys match, in descending order by values.
Is it possible to implement with a custom Compare predicate?
| Map's Compare predicate only takes keys as arguments. Unfortunately you cannot use values to sort the entries within the same bucket with use of the predicate only.
Important - it's still possible to implement such scenario it with other means. Here is the answer how to do it if you are ok to use emplace_hint.
The key... |
73,099,409 | 73,099,555 | Making base class protected constructor public in derived class | Can someone please explain why the marked line does not compile? It seems to me that if B2 and D compile, B1 should too.
class A1 {
protected:
A1(int){}
};
class B1 : private A1 {
public:
using A1::A1;
};
class A2 {
protected:
A2(int){}
};
class B2 : private A2 {
public:
B2(int i) : A2(i) {}
};... | using-declaration behaves differently when designating constructors vs other members. For constructors, the visibility of the using-declaration is ignored; if selected by overload resolution, the constructor can be used if it's visible in the base class. For all other members, using-declaration introduces a synonym int... |
73,099,579 | 73,099,598 | cout a string from class outputs a "nan" | I created a class that holds the information about a character in a game. I also created a constructor for it. But when I cout a string or a float from the class, it outputs a "nan" or a weird and long number or just nothing.
look at the code:-
#include <iostream>
#include <conio.h>
#include <string>
#include <windows.... | Character(string atype, string aname, float aHP, float aMP, float astr, float adef, float aagility, int aLVL){
string type = atype;
string name = aname;
float HP = aHP;
float MP = aMP;
float str = astr;
float def = adef;
float agility = aagility;
int LVL = aLVL;
}
should be
Character(st... |
73,099,621 | 73,099,653 | C++ string and char* difference in example | This is from hackerrank "Inherited Code" example,
While this works and what() returns n, if I comment the return in what and uncomment the currently commented part what() returns junk.
They look the same to me, what is the difference?
/* Define the exception here */
struct BadLengthException : public exception {
... | string a is a local (ASDV) in what(). It goes out of scope when you return. a.c_str() is simply a pointer, it's non-owning and thus doesn't extend the lifetime of the char buffer, therefore it's UB. In case of UB, anything can happen, including returning junk.
|
73,099,837 | 73,099,911 | Why is `std::string_view` not implemented differently? | Given the following code we can see that std::string_view is invalidated when string grows beyond capacity (here SSO is in effect initially then contents are put on the heap)
#include <iostream>
#include <cassert>
#include <string>
using std::cout;
using std::endl;
int main() {
std::string s = "hi";
std::stri... | string_view knows nothing about string. It is not a "wrapper" around a string. It has no idea that std::string even exists as a type; the conversion from string to string_view happens within std::string. string_view has no association with or reliance on std::string.
In fact, that is the entire purpose of string_view: ... |
73,100,077 | 73,100,223 | why assert(str!=NULL) does not return an error? | Why did this not print an assert error?
This is my code:
#include<assert.h>
#include<stdio.h>
int main(){
int n =12;
char str[50] = "";
assert(n>=10);
printf("output :%d\n",n);
assert(str!=NULL);
printf("output :%s\n",str);
}
| char str[50] = "";
This makes str into an array of 50 chars, and initialises the memory to all zeroes (first byte explicitly from "" and rest implicitly, because C does not support partial initialisation of arrays or structs).
assert(str!=NULL);
When used in an expression, array is treated as pointer to its first el... |
73,100,129 | 73,100,492 | What is a static member function? Can we use a static function to initialize a parent functor? | I ran into a situation where I have two classes, class A is a templated class with a template function F, and B is A's child, which instantiate F. Can I just use a static function to do that?
template<typename F>
class A{
public:
class A(const F& f):_f{f}{}
F _f;
};
class B: public A<std::function<double(const... |
What is a static member function?
A function inside a class not bound to class instance.
Can we use a static function to initialize a parent functor?
Yes.
Can I just use a static function to do that?
Yes.
Can I do this?
No, your code has syntax errors. There should be no class before A constructor, and B():A<..... |
73,100,233 | 73,100,303 | how to overload function with different class object c++ | You can see in main Func im passing different objects at function, which is overloaded and have different kind of objects, but when i run same account transfer function only run, anyone can guide what im doing wrong, whats need to be done.
Easy words there are 3 functions made in class ACI Transfer(double balance, clas... |
trying to run all these 3 functions by passing their respected object
The other two overloaded functions have 3 parameters but you're passing only two arguments when calling the function transfer. Thus, the one ACI::transfer(double ,Account) with 2 parameters is the only viable candidate and will be called both times... |
73,100,757 | 73,101,339 | How would I make sure that the needed headers required in my C++ program are installed on the user's machine? | I have a C++ project that uses the popular Boost library. The problem is, if someone downloads my code off say, Github and tries to build it, it won't work unless they have Boost installed, which could be an inconvenience. I'm just wondering how I would go about making sure these headers are accessible for the user so ... | There are quite a lot of options on how to manage dependencies. In my experience many platforms define it's own conventional way of doing so. E.g. in iOS development people either use CocoaPods or SwiftPackages (and sometimes Carthage). For Android applications, developers usually define dependencies in dependencies bl... |
73,100,964 | 73,101,016 | Are there any advantages to pure virtual members (except the human error that they might prevent)? | I have a stack of classes with pure virtual members, it'll be populated by derived non-abstract classes. I'm getting the error:
Error C2259 'ABC': cannot instantiate abstract class TEMP c:\program files (x86)\microsoft visual studio\2017\enterprise\vc\tools\msvc\14.16.27023\include\xmemory0 879
This error... | In this call
s.push(DEF(x));
the temporary object of the type DEF is implicitly converted to an object of the type ABC. So if to call the virtual function then the virtual function of the class ABC will be called.
You can use the polymorphism when you use pointers or references.
Here is your updated program.
#include ... |
73,101,505 | 73,101,604 | how to add lambda function or perform custom operation in STL set in c++ | I need a set arranges the value in such a way that if the int values are different i need the lexographically greater string to come front else i want the smaller integer to come front
set<pair<int,string>,[&](auto &a,auto &b){
if(a.first==b.first)return a.second>b.second;
return a.first<b.first;
}>;
| It seems you mean the following
#include <iostream>
#include <string>
#include <utility>
#include <set>
#include <tuple>
int main()
{
auto less = []( const auto &p1, const auto &p2 )
{
return std::tie( p1.first, p2.second ) <
std::tie( p2.first, p1.second );
};
std::set<std::pa... |
73,101,924 | 73,102,126 | Assign pointer to 2d array to an array | So I got a function which creates me 2D array and fill it with test data.
Now I need to assign the pointer to an array
//Fill matrix with test data
int *testArrData(int m, int n){
int arr[n][m];
int* ptr;
ptr = &arr[0][0];
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
*((pt... | There are at least four problems with the function.
//Fill matrix with test data
int *testArrData(int m, int n){
int arr[n][m];
int* ptr;
ptr = &arr[0][0];
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
*((ptr+i*n)+j) = rand()%10;
}
}
return (int *) arr;
}
F... |
73,101,942 | 73,109,073 | Constexpr function evaluation on a template parameter object (MSVC vs clang/gcc) | As I understand it, the following should be valid C++20:
template<int i> struct A {};
struct B
{
constexpr int one() const { return 1; }
};
template<B b> A<b.one()> f() { return {}; }
void test()
{
f<B{}>();
}
MSVC does not like this (Visual Studio 2022, but godbolt appears to show all versions failing in some ... | Yes, seems like a bug to me as well.
The parser seems to have a problem specifically with the member function call via . in the template argument. It works when using ->:
template<B b> A<(&b)->one()> f() { return {}; }
|
73,101,971 | 73,109,045 | Why voltage from Raspberry Pi Pico ADC is not equal 0, when nothing is connected to the pin? | I was trying to read some voltages from a sensor, but before doing that, I checked how readings would look like, when nothing is connected to pins.
Here's my code based on examples:
#include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/gpio.h"
#include "hardware/adc.h"
int main() {
stdio_init_all();
c... | Pins are never not connected. They have a pullup/down resistor that can be switched on or off and they are connected to the read and write circuitry that can be switched between.
Those aren't physical switches. When you switch the pullup/down resistor off what that really means is that you make that a really high resis... |
73,102,119 | 73,102,127 | How to inherit constructors? OR how to make similar constructors? | I am making a class for a character with several attributes. I made it so the user has to choose between 3 objects made from the constructor of that first class.
I cant think of a way to choose between the objects so I want to create a class that inherits the attributes of the first class(basically a copycat) but will ... | class Chose : public Character{
public:
using Character::Character;
};
https://godbolt.org/z/TEG7Pvdxa
Note that you are trying use default constructor of Character which was removed since custom constructor was defined. As result default constructor of Chose can't be created implicitly (since base class do not h... |
73,102,933 | 73,102,959 | member function of an object of class map | I somehow not sure what is wrong with call to insert for the object "history" where history is of type map. I have checked that there should be an insert function for a map object where the insert function would take in a pair as an argument. However I keep getting the error of
#include <map>
using namespace std;
class... | std::map<ListNode, int> history;
This map's key is a ListNode.
ListNode *current = head;
current is a ListNode *, a pointer to a ListNode.
history.insert(make_pair(current, current->val));
This attempts to insert a ListNode * key into a map whose key is a ListNode. This is ill-formed. If a map's key is an int, an in... |
73,103,121 | 73,103,373 | If statement only works once | Here is my code:
#include <FastLED.h>
#define LED_PIN 7
#define NUM_LEDS 20
CRGB leds[NUM_LEDS];
void setup() {
pinMode(A0, INPUT_PULLUP);
FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);
}
void loop() {
if (digitalRead(A0) == HIGH) {
TEST ();
}
}
void TEST() {
leds[0] = C... | According to the rule of writing code, the description of the called function should be higher than the place of its call. I mean that the TEST() function should be between setup() and loop()
You need to turn off the LEDs after they have been turned on, this can be achieved with specific function from the FastLED libra... |
73,103,528 | 73,103,618 | cLion C++ "Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)" | Just started using cLion as an ide for c++. Am attempting to run this block of code where it reads a csv file and stores the values in a 189 x 141 2d vector. It then iterates through 5 for loops. Everything was running smoothly until I included the 5 nested for loops; at this point I was seeing the "Process finished wi... | for(int x=0;x<189;x++) {
innerarray.clear();
for (int y = 0; y < 141; y++) {
innerarrayval = rand() % 1000;
innerarray.push_back(innerarrayval);
}
ROB.push_back(innerarray);
}
This part of the initialization loops carefully, and gingerly, initialized the ... |
73,103,639 | 73,103,677 | How do I align my output when a word is too long? | I am trying to create a program where the user enters 5 candidates for an election along with their number of votes. The program's output creates a table where it shows each candidates name, their votes, percentage of votes, and the winner of the election. My code is below and a sample of the output is in a picture tha... | Remove all \ts and only use std::setw:
std::cout << std::left << std::setw(18) << candidateName[i]
<< std::right << std::setw(8) << candidatevotes[i] << ...
|
73,103,713 | 73,103,807 | why there is error when i use the overload | i'm using boost::asio, i want to know why there is error when i use different overload;
```
#include<boost/asio.hpp>
using namespace boost::asio;
int main(int argc,char* argv[]){
io_service ios;
ip::tcp::acceptor acc(ios);
}
```
it can run when i use the command"g++ -o server server.cpp -lboost_system -lboost_... | io_service ios();
This declares a function called ios returning io_service. This is known as the "Most Vexing Parse".
Either use {} instead of () (since C++11) or just leave the parentheses.
|
73,103,833 | 73,104,117 | Boost Karma for a boost::variant containing a custom class | I'd like to investigate boost::spirit::karma::generate as a replacement for std::stringstream for a boost::variant containing, apart from familiar types such as int and double, one or more custom classes (e.g. A). However I'm unable to even compile the code once I include one or more custom classes in the variant.
#in... | The error message informs you that A is not default-constructible. It's a long type expression, but helpfully summarized it for you: (aka 'A').
Adding a default value for d fixes it:
explicit A(double d = {}) : d(d) {}
Now with
std::cout << "iostream: " << a << std::endl;
std::cout << "stringstream: "; test_string... |
73,103,972 | 73,120,142 | multi-dimensional array type as template argument | The kokkos scientific computing library implements the multi-dimensional array (which they call View) such that it knows which dimensions are fixed at compile time and which dimensions are runtime variable. For example, to create a 3-dimensional array data of shape (N0, N1, N2), you can do one of the followings:
View<d... | This question can be split into two parts.
Get the dimensions from the input template parameter T.
Constructor accepts different numbers of values as run-time dimensions.
Let's look at it one by one.
To solve the first problem, a non-type typelist is used to represent the dimensions.
template <size_t... Ns>
struct D... |
73,104,095 | 73,104,135 | Are DLLs generally non-ideal for speed critical applications? | Up until now, I've only ever written and built static libraries, and so, I'm new to the shared library scene, or DLLs, as they are called on Windows.
From what I understand, the key feature of DLLs is that the library code is "loaded" and "unloaded" from the application as it makes calls into library. As such, my quest... | A DLL is typically loaded (and unloaded) only once by an application: either implicitly (if your executable is linked against it, via the corresponding export library) or explicitly (via calls to LoadLibrary() and FreeLibrary(), on Windows). It is not loaded each time one of its functions is called.
Once that DLL is lo... |
73,104,139 | 73,105,411 | Resolving the issue of unsafe function deprecation and misusing time-getting methods like std::ctime() or std::localtime() to get local time in C++ | I'm building a simple small program for fun, to kill time and learn something. I simply want my program to display local time (I live in Buffalo, NY, so I'm in ET). I put together an ostensibly ridiculous soup of libraries to ensure that my program is aware of everything:
#include <iostream>
#include <chrono>
#include ... | (Ideas for the answer were contributed by Adrian Mole and n. 1.8e9-where's-my-share m. in the comments to the OP question.)
The C4996 is simply a stumbling block designed by Microsoft. To bypass this "error", simply set the _CRT_SECURE_NO_WARNINGS flag to true by adding the following to the very top of the main file:
#... |
73,104,194 | 73,104,251 | String converted to Array. Modulo the value is incorrect | char* array{};
string digit4;
cout << "Enter a 4 digit-integer : " << endl;
cin >> digit4;
cout << "The 4 digit-integer you have entered is : " << digit4 << endl;
array = &digit4[0];
cout << "Digit 1 is : " << array[0] << endl;
int digit1 = (array[0] + 7) % 10;
cout << digit1 << endl;
return
I tried to convert ... | The expression array[0] evaluates to the character code for the digit '1', which is 49 in ASCII.
Therefore, assuming that you are using ASCII, the expression
(array[0] + 7) % 10;
is equivalent to
(49 + 7) % 10
which is 6.
If you want to get the value that is represented by the digit, then you can simply subtract '0' ... |
73,104,401 | 73,104,931 | Using QHttpMultiPart with PUT operation and form fields | I'm having quite a bit of struggle in trying to achieve a simple PUT request in QT. Frankly I am still a starter using this framework so I have much left to learn.
What I am trying to do is make a PUT request with 2 parameters this Cloudflare Workers KV API.
With that being said this is my current code snippet:
QString... | I will answer my own question because one of the reasons the above was not working it's because of my own fault.
Problem 1:
Bad formatting of metadata. Looks like Cloudflare API wants the metadata "compressed".
Problem 2:
Unable to retrieve API error response. Now this is an interesting one because I found countless fo... |
73,104,516 | 73,104,746 | How to make a template cycle? | I'm very often fiddling with cycle and they're almost the same, I think you can simplify a lot of code if you have one template.
// the blocks can be different, but the number is known before compilation
const int block_1 = 10,
block_2 = 4,
block_3 = 6,
block_4 = 3;
Basically all cycles a... | Yes, you can compose iota_view and cartesian_product_view to get nested indexes in C++23
constexpr inline auto for_funk = [](auto... index) {
return std::views::cartesian_product(std::views::iota(1, index-1)...);
};
const int block_1 = 10,
block_2 = 4,
block_3 = 6,
block_4 = 3;
for (aut... |
73,104,673 | 73,104,775 | Interpreting the & sign in C++ | My confusion:
Since both the pointers and references use the symbol &, and in pointers & symbol is usually interpreted as "the address of ...", I wonder whether it should be interpreted the same in references.
My theory:
When & sign appears on the right hand side of =, it can be interpreted as "the address of".
When & ... | Since there are only so many ASCII symbols, it's inevitable that they get re-used for contradictory purposes, and & is one such character.
It means either address of in a statement or reference to in a variable declaration. Thinking of the "right-hand-side" is close, but it's really just its presence in a statement or,... |
73,104,949 | 73,113,348 | Any metrics could measure vignetting effect of images? | I would like to detect the pictures suffered by Vignetting or not, but cannot find a way to measure it. I search by keywords like "Vignetting metrics, Vignetting detection, Vignetting classification", they all lead me to topics like "Create vignetting filters" or "Vignetting correction". Any metric could do that? Like ... | Use a polar warp and some simple statistics on the picture. You'll get a plot of the radial intensities. You'll see the characteristic attenuation of a vignette, but also picture content. This 1D signal is easier to analyze than the entire picture.
This is not guaranteed to always work. I'm not saying it should. It's a... |
73,105,084 | 73,105,159 | What does the system put in buffer when you enter RETURN in keyboard | It is well known that say if we use a loop of
cin.get(char_array, 10)
to read keyboard input. It will leave a 'delimiter'(corresponds to the 'ENTER' key) in the queue so the next iteration of cin.get(char_array, 10) will read the 'delimiter' and suddenly closed. We have to do this
cin.get(char_array, 10)
cin.get()
us... | The 'queue' associated with std::cin (it's normally known as a buffer) is the characters you type. This is true however you read from std::cin.
get(array, count, delim) reads until 1) end of file is reached, 2) count - 1 characters have been read, or 3) the next character in the queue is delim. If not supplied delim de... |
73,105,115 | 73,133,436 | How can Visual Studio C++ debugger be showing values of local variables that are at odds with another frame? | I'm building a game in UE5 with C++. If you have access to the Unreal Engine source code (get it here), I'm hitting an assertion on this line: https://github.com/EpicGames/UnrealEngine/blob/d9d435c9c280b99a6c679b517adedd3f4b02cfd7/Engine/Plugins/Runtime/StateTree/Source/StateTreeModule/Private/StateTreeExecutionContext... | Turns out the comments on the question gave me the right clue here:
The bottom line is that you cannot simply debug optimized code, and expect the debugger to adjust itself to the optimizations done by the compiler.
When I debugged using a non-optimized build of UE5, I quickly saw the issue, and the CurrentStatus.Sta... |
73,105,304 | 73,105,475 | How to find out if a std::vector in a string in cpp? | I have a string like ...hello...world..., and I want to check if it is in some strings,so I split it by ... and save it in a <vector> string,the problem is how to check both of item in input_str sequentially?
#include <iostream>
#include <vector>
using namespace std;
int main()
{
string input_str1 = "Good morning... | Initialize bool status = true; and remove status = true;. You start with the assumption that the string contains all words. Then, you iterate over the list of words and check each word. If a word doesn't exist, set status = false;.
Store the position of the last result and start the next search at that position.
#inclu... |
73,105,807 | 73,106,641 | MFC Multithread Raw Data Viewer Program Design | The program I'm working on has the following features:
Display the incoming data (thru an ethernet UDP socket)
Manipulate and calculate some data in the header and display
Save a # of frames upon user input
The program has the following structure:
a Main UI thread running (provided by MFC)
a thread which takes the d... | When you display the data (StretchBlt(....., pdlg->vbuf[0].data, ....);) in the display thread and this is accessing the display DC, you have to make sure you are doing it in sync with the main thread, for example, by using atomic locks. Or as an alternately better solution, do the display in main thread and remove the... |
73,106,189 | 73,106,546 | Ambiguity when calling overloaded function with vector as param | I am writing a class in which I am overloading operator[] and I want one function to have vector as input and the second one to have vector of vectors as input, but when I call it like
obj[{ 0 }]
then I got ambigious call error. The functions are declared like
const Tensor operator[](const std::vector<std::vector<uint... | {0} has no type. and it is valid to construct both std::vector<uint32_t> and std::vector<std::vector<uint32_t>> (without overload resolution preference).
You might specify the type explicitly at call site:
obj[std::vector<uint32_t>{0}];
obj[std::vector<std::vector<uint32_t>>{0}];
or add extra overload with higher prio... |
73,106,332 | 73,108,189 | Find the remainder after dividing the sum of two integers by the third | I'm trying to find a solution to a task. My code passed only 3 autotests. I checked that the solution satisfies the max/min cases. Probably there are situations when my code is not valid.
Description of the task: Find the remainder after dividing the sum of two integers by the third.
Input: The first line of input cont... | Please note that in C++ reminder for negative values:
was implementation defined until C++11
integer division is rounded towards zero since C++11 which makes reminder negative sometimes.
Now most probably in your task modulo result should be always in range <0, C) (or written differently <0, C - 1>). So to handle ca... |
73,106,847 | 73,106,967 | Terminate called without an active exception : LeetCode Question 74 | I'm writing a simple program to search for an element in a 2D matrix. It's not giving me an active/named exception, but it just throws me a Runtime error.
Any help with as to why this is happening?
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
for (int i=0 ;i< matrix.... | }throw;
A throw without following expression can be used inside an exception handler to re-throw the currently handled exception.
However, at this point your program does not have an active exception. In this case, throw calls std::terminate().
This seems to be an edit artifact.
|
73,107,077 | 73,107,249 | Function template overload with constraints | I have the following code:
// converters.h
#pragma once
#include <iostream>
#include <type_traits>
template <typename TTo, typename TFrom>
static TTo convert(const TFrom& from)
{
TTo t = static_cast<TTo>(from);
std::cout << "From type: " << typeid(TFrom).name() << "\nTo type: " << typeid(TTo).name();
re... | In this function declaration:
template<typename TTo, typename TFrom>
static int convert(std::enable_if_t<std::is_enum_v<TFrom>, TFrom> const& from);
type TFrom appears in a non-deduced context. So, when you call:
convert<int>(Season::Spring);
the compiler can only call (due to SFINAE)
template <typename TTo, typename... |
73,107,532 | 73,107,852 | Program crashes when using custom compartor for std::set | I tried to use custom comparator in a std::set. When I insert cuisine "japaneses" in a variable bucketCuisines, I get error DEADLYSIGNAL.
But, If i eliminate the custom comparator cmp there is no problem. But of course my results are incorrect.
Input:
["FoodRatings","highestRated","highestRated","changeRating","highest... | Your data type set<pair<int, string>, decltype(cmp)*> is an odd way to specify the comparator as a function pointer. But that's what it does, and the issue is likely because you never provide a valid comparator when constructing these sets.
When you add an entry to bucketCuisines, you're currently relying on the defaul... |
73,108,025 | 73,108,171 | Why does the freed memory is less than allocated memory when overloading new and delete operators? | I created a class and overloaded new and delete operators to print the size of memory allocated/freed. In the example below, it allocated 28 bytes but frees 4 bytes. Why?
#include <iostream>
#include <string>
using namespace std;
class Person
{
private:
string name;
int age;
public:
Person() {
cou... | sizeof(p) is the size of void*, the size of a pointer to void. It is not the size of the block of memory to which this pointer is pointing, that is sizeof(Person).
A void* alone carries no information on the size of the pointee. Though, in the background free "knows" how big is the memory block associated with p becaus... |
73,109,010 | 73,109,366 | How to access ui element from another dialog | I have a this code for get avaiable serial ports on Main Window.
QString parsedPortName = QSerialPortInfo::availablePorts().at(ui -> comboBoxDevices -> currentIndex()).portName();
I need access this avaiable ports from another Page. Hiw can I do that?
Here, on my Second Window I need replace avaiable comports with (... | The usual way would be to have something like this in the first dialog:
QString parsedPortName = QSerialPortInfo::availablePorts().at(ui -> comboBoxDevices -> currentIndex()).portName();
emit portNameChanged(parsedPortName); // add this signal to the class
And then in the second window, you would have a slot, which re... |
73,109,477 | 73,109,578 | Class member names as non-type template parameter | I have a class which is generated from a tool with member variable names that vary. I would like to use a single templated class to access these members. I can do this in the following way by using a non-type member pointer:
template<typename MODULE,
int MODULE::*a> class Foo {
public:
Foo() {
MODULE m... | You cannot have a pointer to reference member (see eg How to obtain pointer to reference member? and Reference as a non-type template argument), but you can have a pointer to member function that returns the value by reference:
#include <iostream>
template<typename MODULE,
int& (MODULE::*a)()> class Foo {
public... |
73,109,985 | 73,110,268 | Elegant way to access objects created in qApplication main function | I want to create a window application with Qt framework and C++, in which an object is created to operate hardware, and should be accessible to MainWindow and all its members and methods. I do not have very much experience of doing things like this.
int main(int argc, char *argv[]) {
QApplication qApp(argc, argv);
... | MainWindow is subclassing QMainWindow, but it's a regular C++ class, so just store either an instance directly, or a pointer, as a member variable on it.
In MainWindow.h (or .hpp):
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
U... |
73,110,191 | 73,110,334 | Unable to initialize a template variable inside a class, why? | I don't understand why if I initialize this template variable globally, like this:
template <class T> struct null_string { static const std::string value; };
template<class T> const std::string null_string<T>::value = "";
template<class T> std::string const null_str = null_string<const T&>::value;
it works, but if I t... | Add missing static. Then, either move variable definitions to namespace scope:
class foo
{
template <class T> struct null_string { static const std::string value; };
template <class T> static std::string const null_str;
};
template <class T> const std::string foo::null_string<T>::value = "";
template <class T>... |
73,110,731 | 73,110,829 | Importing x86_64 DLL in project with x86 environment through P/Invoke | My current target framework is .NET Framework v4.0.
I'm having issues importing the DLL as I get the "BadImageFormatException" similar to this post BadImageFormatException when loading 32 bit DLL, target is x86
From there I realised that the DLL (retrieved from NuGet) can only be built in x64, but my solution can only ... | You can not load a 64-bit dll in a 32-bit process. Your options are:
Update your application to x64 mode. This typically requires all native components to be changed to x64 versions. You said you team decided on x86, but decisions can be re-evaluated if you have good enough reasons to.
Find a way to get a x86 version ... |
73,112,048 | 73,112,060 | Difference in function argument between int pointer and int array | What is the difference between taking as a function argument an int pointer or an int array in C++?
void arrayFunction1(int * x) {
for(int i = 0; i < 10; i++) {
cout << x[i] << endl;
}
}
void arrayFunction2(int x[]) {
for(int i = 0; i < 10; i++) {
cout << x[i] << endl;
}
}
int main() {
int dstdata[1... | There are completely identical. In a function parameter int x[] is just another way of writing int* x. Even int x[10] is the same (the 10 is completely ignored).
Now why Kernighan and Ritchie (the inventors of C) thought this piece of deception was a good idea is another question. I guess they weren't thinking of all t... |
73,112,288 | 73,131,728 | Can Qt Remote Objects be used to share an entire mainwindow UI? | I'm currently looking into Qt RO as a possible solution for my current need to remotely access a UI without using Qt WebGL. I am having trouble finding any good example uses of Qt RO outside of the starter ones in the qt docs.
Will Qt RO fit my needs and does anyone know of a good example?
| Custom types work just fine with Qt Remote Objects. Just like with any other meta object compiler issue in Nuke, you just need to make sure that the type is known to the meta object compiler.
So, for example, you will need to register it.
PROP(SomeOtherType myCustomType) // Custom types work. Needs
#include for th... |
73,113,173 | 73,113,358 | How to implement cast for "smart pointer" non-const to const | I am attempting to understand the internals of std::shared_ptr by writing my own (VERY BASIC) implementation. What I have so far is the following (with most of the operators and other code removed).
template <typename T>
struct ControlBlock {
unsigned int refCount;
T* ptr;
};
template <typename T>
class MyPoi... |
How to implement cast for "smart pointer" non-const to const
Implement exactly that - a conversion operator from non-const to const. With help of how can I use std::enable_if in a conversion operator? to do some SFINAE:
#include <iostream>
#include <type_traits>
template <typename T>
struct ControlBlock {
unsign... |
73,113,250 | 73,113,309 | Why returning string is not printing in C++ | I am having an issue with my C++ code. I am learning C++. I have written a C++ code for deleting a character from a string. My code is running without an error but not getting a output.
My Code:
#include <iostream>
#include <string>
using namespace std;
string deletion(string s, int position) {
string newS; ... | This string has zero length
string newS;
This code attempts to write a character to a zero length string
newS[j] = s[i];
That is an out of bounds error and therefore your code has undefined behaviour.
Here's your code rewritten so that it adds characters to the string.
string deletion(string s, int position) {
stri... |
73,113,402 | 73,114,714 | I need to read txt file and have each line run through the code in c++. I tried while before if statement and got caught in a loop | not very good at coding yet, and I am doing a c++ program that needs to read txt file and take line-by-line string input and iterate it through the program. each line has 18 numbers. It reads the lines but only cycles the last line. I need it to run all lines through the equation, so I can verify the checksum of each u... |
First of all you have to understand what is the use of the instruction using namespace std; Because you don't need to put std:: before the getline() for example.
It's normal that your code treats only the last line of your text file because it's this line that you store last before closing the file. If you want to co... |
73,113,594 | 73,114,139 | Built-in way to pass JS objects to C++ using emscripten | Is there a simple built-in way to pass JS objects to C++?
I tried doing it the obvious way:
echo.cpp:
#include <iostream>
#include <emscripten.h>
#include <emscripten/val.h>
using emscripten::val;
#ifdef __cplusplus
extern "C" {
#endif
EMSCRIPTEN_KEEPALIVE void echo(val x){
val::global("console").call<void>("l... | Via the docs :
EMSCRIPTEN_BINDINGS(my_module) {
function("lerp", &lerp);
}
my_module is just a (globally) unique name you have to add, it doesn't have any other purpose.
void echo(EM_VAL x_ptr){
// converts it to object from the pointer
val x = val::take_ownership(x_ptr);
val::global("console").call<void>("log... |
73,113,840 | 73,116,691 | C++ - Automatically insert a pair-like object into a map? | Lets say we have some pair like class:
class PairLike{
public:
string key;
int val;
PairLike(string Key, int Val) : key(Key), val(Val){};
//...other members
};
A few objects to go along with it:
PairLike p1("a",1);
PairLike p2("b",2);
PairLike p3("c",3);
PairLike p4("d",4);
Is there a way of automati... | You could provide a conversion operator for converting to std::pair:
class PairLike{
public:
// ...
operator std::pair<const std::string, int>() {
return {key, val};
}
};
And use it like:
std::map<string, int> container{p1,p2,p3};
container.insert(p4);
|
73,114,876 | 73,114,999 | Why do I get a weird error about an uninstantiated template being undefined? | When I compile this code with MSVC:
#include <type_traits>
template<class> struct S { };
template<class T>
using Foo = std::integral_constant<unsigned, sizeof(S<std::underlying_type_t<T>>)>;
int main() { }
I get:
error C2027: use of undefined type 'S<_Underlying_type<_Ty,std::is_enum_v<_Ty>>::type>'
note: see declarat... | I think I figured out a workaround (I think it's a longstanding bug):
#include <type_traits>
template<class> struct S { };
template<class T>
struct Bar : std::integral_constant<unsigned, sizeof(S<std::underlying_type_t<T>>)> { };
template<class T>
using Foo = typename Bar<T>::type;
int main() { }
|
73,114,946 | 73,115,351 | c++ TCP client and server not able to communicate on local machine | I have built a simple c++ TCP server and client using winsock. The code all compiles without error however either the server is refusing connections or my client is failing to connect properly.
The code is alot to put onto stackoverflow so here is a pastebin for the server and Client.
https://pastebin.com/ZQavPxsR - Se... | Your server is not initializing the service.sin_port field before calling bind(), so the code exhibits undefined behavior. Your listening socket will end up trying to bind to whatever random port value was already present in the memory that the sin_port field occupies. And if that value happens to be 0, then bind() w... |
73,115,064 | 73,115,303 | How check what boost::datetime correct? | How i can check what input string incorrect and throw exception? Now it string just accepting to constructor and converting to something wrong but exception not throw
#include <boost/date_time.hpp>
namespace bt = boost::posix_time;
using namespace boost;
using namespace gregorian;
using namespace boost::posix_time;
... | Hope it help someone. Need set the streams exception flags.
bt::ptime from_string_dtime(const std::string& s)
{
bt::ptime pt;
std::istringstream is(s);
is.exceptions(std::ifstream::failbit | std::ifstream::badbit); // Set exception flags
is.imbue(std::locale(std::locale::classic(), new bt::time_input_fa... |
73,115,298 | 73,115,350 | Randomly Generate Even Split of 1s and 0s in Array | I have a simple array, 20 members long, that I read a single value from, one at a time.
The array currently looks like this for testing purposes:
int PhaseTesting1Array[20] = { 1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0};
What I need to do is randomize each of the members so that each member is randomly a 1 or 0, and th... | You can use std::shuffle with a predefined vector with 10 ones and 10 zeros. The following code is slightly adapted from cppreference.com.
#include <random>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <vector>
int main()
{
std::vector<int> v = {1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0};
... |
73,115,436 | 73,115,480 | How can I use SFINAE to disable a function inside a class based on template type | I have a template class
template<typename TLoader, typename TCreator>
class ManagerGroup {
public:
uint32_t loadFromPath(const Path &path) {
return mLoader.load(path);
}
void createFile(uint32_t handle) {
return mCreator.create(handle);
}
private:
TLoader mLoader;
TCreator mCreator;
};
For the lo... | In order for SFINAE to work you need to use a parameter that is being deduced. In your case TCreator is already known so you can't use it. You can instead get around the problem by adding your own parameter and defaulting it to TCreator like
template<typename T = TCreator,
std::enable_if_t<!std::is_same_v<T,... |
73,115,619 | 73,115,969 | using set_union() with a lambda | I would like to use set_union() and just scan the output without having to store it.
Something like this (it doesn't compile using g++12.1.0):
#include <vector>
#include <algorithm>
#include <stdio.h>
using namespace std;
int main()
{
vector<int> a = {1,2,3}, b={4,5,6};
ranges::set_union(a, b, [](int i){printf... | You need to supply an "output iterator" for set_union() to pass elements to. It does not accept a lambda (or other callable type). You can use std::ostream_iterator for this, eg:
#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>
// ...
vector<int> a = {1,2,3}, b={4,5,6};
ranges::set_union(a... |
73,115,800 | 73,250,158 | Unknown signal exception when debugging on Visual Studio Code | I'm creating a template class for dynamic arrays. The .hpp file is as follows:
#include <cstddef>
#include <cstring>
#include <stdexcept>
template <typename T> class array
{
private:
T* m_data;
std::size_t m_size;
public:
array(std::size_t size) : m_size(size) { m_data = new T[size](); ... | I eventually found out that there's a compatibility issue between clangd and the Microsoft C/C++ extensions. Uninstalling clangd and reinstalling Microsoft C/C++ solved the issue and other related problems.
|
73,116,189 | 73,116,440 | Pointers vs vectors for arrays c++ | In the case I am creating an 'array' on stack in c++, is it better to initialise an empty vector with a reserved number of elements and then pass this to a function like foo() as a reference as below. Or is it better to set an array arrb of size nelems, then using a pointer p_arrb to the address of the first element in... | You can't use the arrb variant because the size of an array must be a compile-time constant in C++, but you are trying to use a runtime size here.
If your compiler is compiling this, then it is doing so only because it supports these so-called variable-length arrays as a non-standard extension. Other compilers will not... |
73,116,419 | 73,116,602 | How can I pass these references to the same function? | I have a function parse(Stream & in) I'd like to call as both:
// asFile() is a static method that returns a Stream object by value
parse(Stream::asFile("filename.txt"));
and also
Stream file = Stream::asFile("filename.txt");
parse(file);
file.getPos(); // file retains state set by the parse function
But it runs ... | Is this what you are looking for?
#include <iostream>
#include <string>
// An object to simulate the state of your stream.
// Whatever in here must be movable.
// Here I am relying on default compiler generated move operators.
struct Data
{
std::string data;
};
// You don't provide a definition of stream.
// This... |
73,116,578 | 73,116,655 | Function pointer inside class point to that class's member function | I am familiar with the function pointer to class member issue, which requires the signature to be ClassName::*FuncPtr, but I have this nuanced problem where I need the function pointer to be to a containing class member:
class F
{
public:
class Container;
typedef void (Container::*FuncPtr)();
F(FuncPtr... | You need to move the forward declaration class Container; outside of F. Inside of F, it is declaring F::Container, which is a different type than Container.
Also, (*this.*m_fp)() (alternatively (this->*m_fp)()) won't work at all, as m_fp is expecting a Container object on the left side of .* (or ->*), but this is point... |
73,117,085 | 73,117,112 | Why does the program work after removing the symbol information? | I made one SO file and compiled it with a compile option called "-Xlinker --strip-all " to counter any reverse engineering (use clang).
Thanks to this, most of the symbols of functions other than functions directly exposed to the outside do not appear (objdump -TC test.so). The question is, if a symbol is deleted like ... | You're right, debugging symbols aren't needed by the program itself to execute; the linker computes (and therefore knows at link-time) what the memory-address of each function/global-variable/etc will be at run-time, so it can just place that memory-address directly into the executable where necessary.
The symbols are ... |
73,117,349 | 73,117,805 | managing global state with parameterization (without singleton) but with a templated class | I am writing a small pub/sub application in c++14/17 for practice and self-learning. I say 14/17 because the only feature of c++17 I have used for this project so far has been the std::scoped_lock.
In this toy application, the publishers and subscribers are on the same OS process (same compiled binary).
A reasonable ... | Use a base class QueueBase and stores the base class pointers.
struct QueueBase {
virtual ~QueueBase() {}
};
template <class T>
class Queue: QueueBase {};
class Broker {
private:
std::unordered_map<std::string, QueueBase*> queues_;
};
When you need access queues_, dynamic_cast to the type you want.
e... |
73,118,134 | 73,118,213 | C++ template class error: function returning a function | I want to make a simple logger which automatically runs a function and returns its value.
The class is defined as:
template <typename R, typename... Args>
class Logger3
{
Logger3(function<R(Args...)> func,
const string& name):
func{func},
name{name}
{}
R operator() (Args ...args... | There are 3 issues in your code:
The Logger3 class template requires R to be the return value of the function (and Args it's arguments).
(R is not a function type as implied by your attempt to instantiate Logger3).
Therefore instantiating the Logger3 in your case of a function that gets 2 ints and returns an int shoul... |
73,118,274 | 73,124,432 | Making boost::spirit::hold_any accept vectors | According to its author @hkaiser, here boost::spirit::hold_any is a more performant alternative to boost::any and can, for the most part, be used as a drop-in replacement for the latter. I'm interested in it since it purports to allow for easy output streaming, a feature that boost::any lacks.
While I'm able to input s... | Firstly, that advice is 12 years old. Since then std::any was even standardized. I would not assume that hold_any is still the better choice (on the contrary).
Also, note that the answer you implied contains the exact explanation:
This class has two differences if compared to boost::any:
it utilizes the small object ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.