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 |
|---|---|---|---|---|
71,121,818 | 71,121,982 | How to write partition for quicksort with C++ | I am writing an algorithm in C++ where the user types how many numbers they want to be sorted, then the program generates an array of random numbers, and sorts them. It also displays how much time it took to sort.
It only works for some of the trials, even if I use the same input. For example, if I ask the program to s... |
#include <bits/stdc++.h>
using namespace std;
int partition(int arr[], int leftIndex, int rightIndex)
{
int pivotIndex = leftIndex;
int pivotValue = arr[pivotIndex];
int i = leftIndex;
int j = rightIndex;
while(i < j){
while(arr[i] <= pivotValue){
... |
71,122,029 | 71,230,480 | Missing C++20 headers on Ubuntu 20.04 with Clang 13 | I have installed clang-13, but when I try to compile a program that uses C++20 headers, I get missing header errors.
#include <numeric>
#include <numbers> // missing
It seems that CMake uses the system headers (from the old GCC headers shipped with ubuntu). How do I convince it to use the Clang's headers instead?
Nu... | Installing the latest version of g++ fixed the issue for me. For example, g++-11 is the latest version at the moment. To install it on Ubuntu:
Add the toolchain ppa to ensure that the latest version is available:
sudo add-apt-repository --update -y ppa:ubuntu-toolchain-r/test
sudo apt-get update -y
Then install
sudo a... |
71,122,472 | 71,122,558 | Can I make the data of an entire C++ class be std::atomic<> | I havea class, used for data storage, of which there is only a single instance.
The caller is message driven and has become too large and is a prime candidate for refactoring, such that each message is handled by a separate thread. However, these could then compete to read/write the data.
If I were using mutexes (mutic... | std::atomic requires the type to be trivially copyable. Since you are saying std::vector is involved, that makes it impossible to use it, either on the whole structure or the std::vector itself.
The purpose of std::atomic is to be able to atomically replace the whole value of the object. You cannot do something like ac... |
71,123,142 | 71,123,238 | What causes compiling error with templated class? | I have simple codes for templated and non-templated versions of the same class. Each class has the same data structure (Point). The compiling problem happens for the templated class when defining the function with the structure Point externally. I compiled the codes with Visual Studio.
//non-templated class is defined ... | The problem is that Geometry2<type>::Point is a dependent qualified name. Moreover, this dependent name is a type so you need to tell this to the compiler which you can do by adding the keyword typename before Geometry2<type>::Point. So the modified code looks like:
template<class type>
typename Geometry2<type>::Point ... |
71,123,291 | 71,123,376 | C++, why does std::set allow lower_bound() on a type different than that of the set elements, but only if I add less<> in the set declaration? | I have this class with an overloaded comparator:
struct Foo {
int x;
bool operator < (Foo other) const {
return x < other.x;
}
bool operator < (int val) const {
return x < val;
}
};
and I make a set on it:
set<Foo> s;
I'm allowed to call lower_bound() on a Foo, but not on an int (a... |
why does std::set allow lower_bound() on a type different than that of the set elements
Because it is useful, and potentially more efficient.
Consider for example a set of std::strings. Creating (large) strings is expensive. If you have a string view, you can use std::less<> to compare the view to the strings of the ... |
71,123,367 | 71,123,883 | Encapsulation along with constructors | I want the int Medals which I put private to be unable to have negative values, but I don't know how to implement that encapsulation along with constructors. I made it so that each athlete type inherits the Athlete constructor but I don't know where to call the setMedals function for it to work.
#include <iostream>
#i... | tl;dr:
Calling non-virtual function inside a constructor is generally fine, although I'd pay attention to it when dealing with larger objects.
So, sth like this should do:
class Athlete
{
private:
unsigned medals{0};
public:
string name;
void setMedals(int m) //or just use unsigned...
{
if (m >= 0)
me... |
71,123,838 | 71,124,448 | Pass vector of objects of derived class to function which takes vector of objects of base class | I'm new to c++ but I have experience with OOP in other languages such as java. I have three classes: class Sortable {...};, class Letter: Sortable {...};, and class Sorter {...};. Sorter has a public function vector<Sortable> sort(vector<Sortable> items_).
In main, I make a vector, vector<Letter> letters; which I give ... | The idiomatic way that this would be done in C++ is to discard class Sortable and class Sorter, and have a free function template sort. Letter could either have an operator <, or you would use a function that defined "less than" for a particular context.
Since C++20 things have gotten slightly nicer, as you can define ... |
71,123,884 | 71,124,076 | Using r-value references outside of constructors/assignment operators | I'm currently learning about R-value references by reading tutorials. Many tutorials mention move constructors/assignment operators as the main use case of R-value references. So I'm wondering whether/how they should be used outside of the "Rule of 5".
Say I have a function
std::string foo();
which returns a potential... |
My understanding is that 2. and 3. are essentially the same
No, in fact 1. and 2. are essentially the same, but 3. is different.
In both 1. and 2. my_string is an lvalue, since names of variables are always lvalues. In both cases the string object lives until the end of the scope. In case of 1. because that is the sc... |
71,124,571 | 71,124,626 | How can I extern classes in a namespace? | I want to extern classes in a namespace, without defining the entire class again. For example, I have class A:
class A
{
private:
int value;
public:
A(int value);
int get_value();
};
and class B:
class B
{
private:
int value;
public:
B(int value);
int get... | If you want to refer to the same classes as though they were members of the namespace, then you can do that with a pair of using declarations.
namespace kc
{
using ::A;
using ::B;
};
Note however, that this does not make the classes into members of the namespace, and language features like ADL won't be affecte... |
71,124,629 | 71,127,783 | Wrap python argument for pybind11 overloaded methods | I'm trying to create python bindings for some legacy C++ code which implemented its own 'extended' string class aString which it uses extensively. This works fine for .def(py::init<const std::string &, int>()), but once I start trying to wrap overloaded methods pybind11 does not appear to automatically cast std::string... | You can enable an implicit conversion between types by adding the following statement:
py::implicitly_convertible<std::string, aString>();
In general py::implicitly_convertible<A, B>() works only if (as in your case) B has a constructor that takes A as its only argument.
|
71,124,650 | 71,124,738 | Why do I get a WM_CHAR message with char code 3 when I press Ctrl + C? | I have a simple Win32 desktop application listening the keyboard message.
When I press Ctrl + C, I got the following message sequence:
WM_DOWN Ctrl
WM_DOWN C
WM_CHAR wParam=3
WM_UP Ctrl
WM_UP C
Why do I get a WM_CHAR message whose char code is 3?
| Historical. "C" is the third letter of the alphabet. Ctrl-B is 2.
|
71,124,824 | 71,127,060 | create a matrix with condition in C++ | I want to create a matrix B from a matrix A, in C++.
First column of A is distance D1, second column is distance D2. Matrix B copies the same columns (and rows) of A, except when in A it happens that D2-D1=delta exceeds a threshold. In this case, the row of A is break in two rows in B.
I wrote an algorithm, but the pro... | 1.You can use push_back to avoid the size definition
2.You updated D1 and D2 instead of newD1 and newD2
#include <vector>
#include <iostream>
using namespace std;
int main()
{
std::vector<float> D1 = { 0,5,15 };
std::vector<float> D2 = { 5,15,17 };
std::vector<float> ... |
71,125,138 | 71,131,487 | SWIG - C++ to python - enum that has ULL values being converted to 0 | I have a legacy C++ code base that I am using SWIG to generate python bindings for.
In this code base there are enums all over that have specific values that are then used for binary operations.
A typical header file used looks something like this:
namespace doom
{
class Bar
{
public:
struct FooIdent
{
... | SWIG by default treats enum constants as int, even if you override with:
enum FooPresence : unsigned long long { ... }
This generates code in the test_wrap.cxx file like:
SWIG_Python_SetConstant(d, "Foo1",SWIG_From_int(static_cast< int >(Foo1)));
SWIG_Python_SetConstant(d, "Foo2",SWIG_From_int(static_cast< int >(Foo2)... |
71,125,547 | 71,125,832 | How to use signals in C++ and How they react? | I am trying to learn all interactions about signals and I discovered a funny interaction in it I can't understand.
Here's an abstract of the program, Im instructed to do execvp with grandchild, while child needs to wait for grandchild to finish. It runs correctly when without any signal interactions.
void say_Hi(int nu... | Answer:
kill(getpid(), SIG_USR1);
|
71,127,515 | 71,128,221 | How to link WinInet using msys bash shell | I am having hard time figuring out how to link WinInet when compiling from bash shell in windows (msys)
'Makefile'
main:
g++ -s -static -static-libgcc -static-libstdc++ -lwininet main.cpp -o main
'main.cpp'
#include <Windows.h>
#include <wininet.h>
#define MAX 4096
#pragma comment (lib, "Wininet.lib")
void R... | The problem is in your make file, you should move -lwininet after main.cpp
g++ -s main.cpp -static -static-libgcc -static-libstdc++ -lwininet -Os -o main
|
71,127,814 | 71,128,090 | MSVC 2019 _fxrstor64 and _fxsave64 intrinsics availability | What are the minimum preprocessor checks I need to make to be sure the compiler is MSVC2019 and that the _fxrstor64 and _fxsave64 intrinsics are available for use?
| To check that you have (at least) the MSVC 2019 compiler, you should use the following:
#if !defined(_MSC_VER) || (_MSC_VER < 1900)
#error "Not MSVC or MSVC is too old"
#endif
For the _fxrstor64 and _fxsave64 intrinsics to be available to MSVC, you need to check that the "immintrin.h" header has been included:
#ifndef... |
71,128,152 | 71,128,208 | Duplication of concept requirement checks. Should we care about them? | When functions nest, the concept requirement checks often duplicate.
Look at the example below,
template<typename I>
requires std::forward_iterator<I>
auto fun1(I i){ ... };
template<typename I>
requires std::forward_iterator<I>
auto fun2(I i){
fun1(i);
....
}
fun1 is called inside fun2, thus std::forward_ite... | If fun1 is called by someone other than fun2, then the presence of the concept is not duplication. Code which calls just fun1 needs a conceptualized interface for it as well. They're two independent functions; one of them just so happens to call the other.
If fun1 is only called by fun2, then the concept could be remov... |
71,128,171 | 71,132,346 | Design of data storage C++ application (maybe relational database) | I need to store and load some data in a C++ application. This data is basically going to end up as a set of tables as per a relational database.
I write the data to tables using something like csv format, then parse them myself and apply the database logic I need in my C++ code. But it seems stupid to reinvent the whee... | You can try sqlite.
Here are some simple code examples: https://www.tutorialspoint.com/sqlite/sqlite_c_cpp.htm
|
71,128,326 | 71,128,618 | shader in C++ opengl2.1 doesn't compile in arch linux | I am trying to create a red triangle in C++ using graphics api opengl 2.1 like below:
it will still compile but my code says that there is a error and is in white shown below:
opengl 2.1 is supported!
error!
my code is:
#include <GL/gl.h>
#include <GL/glew.h>
#include <GL/glu.h>
#include <GLFW/glfw3.h>
#include <io... | The profile string core might not be supported by a pure GLSL 120 implementation, use
#version 120
in and out are GLSL 130, layout qualifiers are GLSL 330. You need
attribute vec4 position;
In the fragment shader, remove the out variable and do
gl_FragColor = vec4(1.0,0.0,0.0,1.0);
These are the most obvious problem... |
71,129,442 | 71,129,731 | cppcheck suggests to reduce scope of variable, should I? | So I have something like this
int age;
for (auto person : persons) {
age = std::stoi(person[0]);
/* Do other stuff with age in this loop*/
}
Other than style, are there any performance benefits to declaring int age = std::stoi(person[0]); inside the loop?
|
are there any performance benefits
Because of the "as-if" rule, it's reasonable to assume that there is no performance difference between two equivalent ways of declaring the same variable.
|
71,129,489 | 71,129,692 | Why having both default destructor and vector member prevents class to be "nothrow movable constructible"? | Given the following code:
#include <iostream>
#include <vector>
#include <type_traits>
class Test {
public:
~Test() = default;
std::vector<int> m_vector;
};
int main() {
std::cout << std::is_nothrow_move_constructible_v<Test> << std::endl;
return 0;
}
It outputs 0, meaning the Test class can't be "n... | See [class.copy.ctor]/8:
If the definition of a class X does not explicitly declare a move constructor, a non-explicit one will be implicitly declared as defaulted if and only if [other conditions omitted, and] X does not have a user-declared destructor.
Thus, the Test class only has a copy constructor, not a move co... |
71,129,840 | 71,141,900 | Thrust : how could i fill an array by range with index and range | I try to fill an array by range using index and values
thrust::device_vector<int> vec(12)
vec[1] = 2;
vec[6] = 3;
vec[10] = 1;
the result should be
vec { 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0}
instead i have
vec { 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0}
does some could tell where i'm wrong ?
Thanks
He... | Here the code for the expected result.
The array give index and the number of flag to be set:
so for
thrust::device_vector<int> vec(12)
vec[1] = 2;
vec[6] = 3;
vec[10] = 1;
the result will be
vec { 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0}
#include <thrust/device_vector.h>
#include <thrust/scan.h>
#inclu... |
71,130,219 | 71,131,723 | CMake: How to compile with different library versions of Qt? | How do you get CMake to compile conditionally with Qt4.8 or Qt5?
In other words, if Qt5 is available then compile with Qt5.
Otherwise if Qt4.8 is available use that.
In my CMake, I have:
find_package(Qt5 COMPONENTS Core Gui Widgets...)
This works fine with my Qt5 builds, but how do I get the same software to build wit... | Automatically selecting an available version of Qt is fairly easy with the NAME option of the find_package command. The problem is that Qt4 and Qt5 have different names for the same modules.
# We first try to find the main module of Qt4, Qt5 or Qt6
find_package(QT NAMES Qt4 Qt5 Qt6 REQUIRED)
set(QT Qt${QT_VERSION_MAJOR... |
71,130,323 | 71,130,766 | Function to explicitly istantiate a given template function with more standard types? | I have the following question. Supposing I have a header file header.hpp with this template function declaration:
template <typename T> extern T func();
And in the header.cpp file I have the function definition:
template <typename T> T func() { \* do something */ };
//Following lines are for explicit istantiation of ... | There is no function like that. The explicit template instantiation must appear at namespace scope, so a "function" like that would have to be some sort of compiler magic (that doesn't exist), or use the preprocessor to expand into the required declarations.
Something like Boost.PP has machinery to approximate what you... |
71,130,388 | 71,130,866 | How to exactly invoke a function by using a member function pointer(and generics)? | Im having troubles invoking a function by using function pointer declared as a member of a struct inside of a class
In the master.cpp:
#include "headers/master.hh"
#include "headers/bus.hh"
#include <memory.h>
#include <stdint.h>
#include <iostream>
int main()
{
int size = 4;
Bus prova;
int su = (prova.BIO... | I have no idea why this was repeatedly closed as a duplicate to the C++ template-header question. You seem to be misunderstanding pointer-to-member syntax. I think what you're seeking is:
int su = (prova.*prova.BIOS_ROM.read_ptr)(prova.BIOS_ROM, size);
The general syntax for concrete objects or references to fire memb... |
71,130,626 | 71,130,767 | Base class constructor automatic call | I have troubles understanding the output of the following code when it comes to the first printed number.
#include <iostream>
#include <string>
using namespace std;
class A{
public:
int x;
A(){
x = 5;
}
};
class B: public A{
public:
static int x;
B(){
x++;
}
B(int i){
... | The first thing to note is that A::x is different from B::x. B does inherit A::x, but it introduces a new B::x which is static. Hence x in the scope of Brefers to B::x (not to A::x). Ergo, you can remove the base class without changing the output:
#include <iostream>
#include <string>
using namespace std;
class B {
p... |
71,130,727 | 71,130,951 | What Win32 message is sent to window at the beginning of resize? | I need Win32 analog of C#'s ResizeBegin to store some data before receiving the first WM_SIZE. I believe I used it very long ago, but cannot find any reference.
For some weird reason, Spy++ on my computer is not operational (both 64- and 32-bit versions, I will deal with them later). I hope, somebody can help me out, t... | You're looking for the WM_SIZING message.
|
71,131,095 | 71,131,170 | Are default memory allocations in class declaration considered a good practice? | I have a class the members of which are allocated on heap
// client.h
#include <QString>
#include <QTcpSocket>
#include <QTextEdit>
#include <QLineEdit>
#include <QWidget>
class Client : public QWidget
{
Q_OBJECT
public:
Client(const QString &computerName, int portNumber,
QWidget *parent = nullptr... | A default member initialiser that allocates memory is not a bad practice.
However, not deleting such dynamic allocations in the destructor is a bad practice. Owning bare pointers in the first place are a bad practice. Furthermore, unnecessary dynamic allocation is a bad practice.
But that's apparently a problem with ... |
71,131,187 | 71,133,248 | CMake, edit fields visible with ccmake | I have searched online, but I haven't found anything because I don't know the correct keywords to express what I need.
I am in a the build/ directory of a repository; if I run ccmake ../ there is a list of "flags (?)" that I can turn ON/OFF in order to decide what stuff do I want to build. If I want to turn ON the BUIL... | ccmake is a graphical interface around cmake. With access to command line, you just type what options you want to set. You do not need to have ccmake.
cmake ../ -DBUILD_THIS=ON
|
71,132,242 | 71,136,020 | Unable find real root for Cubic Equation in C++ | I am writing a C++ program for finding the real root, x for a cubic equation 〖ax〗^3+〖bx〗^2+ cx+d=0 where a≠0 and b=0.
Unfortunately, I could not output the "test case 1 & 4" (ps. sample output provided below link). Perhaps any logic syntax in my coding? Greatly appreciated if anyone could show me the correct way to... | Your code is almost done. You need to improve some points.
Change int a , b, c , d; to double a , b, c , d;
Change condition while (stop=true) to while (stop==true)
I tested and it works as your example.
|
71,132,612 | 71,134,019 | Program is not accessing correct index of array.. Why? | I come to this site in need of help, after struggling with this problem for a few days now. I am trying to program a poem that accepts some data from standard input and then outputs a poem based on that data.
The code seems to be working, but it is not correct! It is giving me the wrong index of the array I am using. I... | You haven't mentioned what exactly the task is but I can at least explain to you parts of the problem.
Are the correct syllables being printed?
Let's assess if the correct syllables are being printed. I ran your code on my machine (with the input you provided that is "100 3 1 5 7 5") and got:
nahoewachi
tetsunnunoyasa
... |
71,133,730 | 71,135,010 | How to clear VTK points | I am new to vtk and I am writing an app to draw multiple shapes. The shapes are drawn using point picking event as follow:
void Visualizer::pointPickingEventOccurred (const pcl::visualization::PointPickingEvent &event)
{
std::cout << "[INOF] Point picking event occurred." << std::endl;
float x, y, z;
... | A simple call to points->Reset() will do the trick.
It will make the object look empty without actually releasing the memory.
|
71,133,807 | 71,146,220 | Issue when using property_tree for a ini file | Strange error when compiling with property tree to write and read a ini (text) file. Simple standalone program(MSVP) works fine. But when i include it in my main code, I get this error. What could this mean ?
It looks like it is not happy with me including
#include <boost/property_tree/ptree.hpp>
#include <boost/proper... | Something defines path in the surrounding scope. The error message tells you this:
ptree_implementation:57.hpp: In member function ‘basic_ptree<...>& basic_ptree<...>::get_child(const path_type& path)’:
error: declaration of ‘path’ shadows a global declaration [-Werror=shadow]
A simple repro would be e.g.
Live On Coli... |
71,133,891 | 71,134,005 | Why does GetKeyState work properly when it is on the stack, but when it is on the heap it causes a silent exit? | I might be missing something obvious, and forgive me if I am.
Anyways, I have a class Keys which has method SPrintScreen as follows:
class Keys{
uint32_t sentQM;
// create array to be passed to SendInput function
INPUT printscreen[2];
// set both types to keyboard events
printscreen[0].type = INPU... | Keys* keys;
does not create a Keys object. It creates a pointer to a keys object. In order do something you have to do 2 more things
create a Keys objects
point keys at it
Like this
Keys *keyObj = new Keys();
keys = keyObj;
obviously you would actually do
Keys *keys = new Keys();
This makes a Keys object on the he... |
71,133,972 | 71,134,136 | Is there a way to detect command line arguments not running tests? | Using the googletest framework I want to write my own main function. Basically some custom initialization step needs to happen before RUN_ALL_TESTS is called. I'd like to skip this step, if the command line parameters for googletest indicate, no tests should be run (e.g. if --gtest_list_tests is passed).
Is it possible... | command line arguments are detected using the GTEST_FLAG macro. An example of what you're trying to do might look like:
#include <gtest/gtest.h>
TEST(equality, always_passes) {
EXPECT_TRUE(true);
}
bool RunAllTestsDoesNotRunTests()
{
return ::testing::GTEST_FLAG(list_tests);
}
void DoExpensiveInitialization(... |
71,134,328 | 71,134,385 | int32_t and int64_t Conversion Issues | In the following line of code, positive is a vector of int32_t elements.
int32_t pos_accum = accumulate(positive.begin(), positive.end(), std::multiplies<int32_t>());
The compiler generates the following error that seems to make no sense:
No suitable conversion function from "std::multiplies<int32_t>" to "int32_t" exi... | The signature of std::accumulate that accepts a binary operator is
template< class InputIt, class T, class BinaryOperation >
constexpr T accumulate( InputIt first, InputIt last, T init, BinaryOperation op );
You're missing the init argument, which represents the initial value of the accumulation. Try
accumulate(positi... |
71,134,920 | 71,135,023 | Pass parameter pack to function repeatedly | I need to pass a parameter pack to a function repeatedly in a loop, like this:
void printString(string str)
{
cout << "The string is: \"" << str << "\"" << endl;
}
template <typename FunctionType, typename ...Args>
void RunWithArgs(FunctionType functionToCall, Args...args)
{
for (int i = 0; i < 3; i++)
... | In this line:
functionToCall(forward <Args>(args)...);
You are forwarding the argument, which in this case, moves it. If you don't want to move, but instead want to copy, then do that:
functionToCall(args...);
Here is a live example.
|
71,135,243 | 71,135,358 | passing one image from batch to function in c++ | I'm trying to change a code in this repo from 2D to 3D; https://github.com/sadeepj/crfasrnn_keras
However, my C++ is super rusty and I'm having a hard time with one problem.
I'm trying to pass the Tensor& out to this function;
void ModifiedPermutohedral::compute(Tensor& out, const Tensor& in, int value_size, bool rever... | Although I am not familiar with tensorflow C++, I noticed that in mp.compute(output_tensor->SubSlice(b), input_tensor.SubSlice(b), channels, backwards_);, first argument is a rvalue such that which cannot be used for value assigning purpose. I suggest:
auto sliced_putput = output_tensor->SubSlice(b);
mp.compute(sliced_... |
71,135,323 | 71,135,490 | How to properly constrain an iterator based function using concepts | I have trouble understanding the concepts defined in the <iterator> header. I couldn't find good examples using them.
I tried to use the concepts in a simple function to provide better error messages. I don't understand why the output_iterator takes a type but input_iterator doesn't any. Furthermore I don't know how to... |
I don't understand why the output_iterator takes a type but input_iterator doesn't any.
Because input iterators have concrete type: it's the type you get from *it. That's the iterator's reference type (iter_reference_t<I>).
But output iterators don't - they just have a set of types that you can write into them. It do... |
71,135,432 | 71,135,518 | Trying to validate double as only numbers | I just started C++ and need some help.
Basically, my code is working the way I want. However, as you can see below, when I type a number and a letter, the code still counts the variable as only a number.
I want the same error message that displays when someone types a letter then a number the same way for this. I know ... | To check the validity of the input, I would suggest utilizing stod() and exception handling. Because cin takes as many expressions that can be interpreted to number as possible, and returns nonzero value if that happened. However, stod() can check the number of characters that was parsed, and if we check whether whole ... |
71,135,484 | 71,135,591 | I'm trying to link hdf5 to c++ code (Mac) | I have the files:
main.cpp, tools.cpp, tools.h, integrator.cpp, and integrator.h.
I have tried to link HDF5 to this code (it compiles/links just fine without hdf5 stuff).
Here's what I am using to compile:
g++ -Wall -Werror -pedantic -std=c++1y -I /usr/local/include -L/usr/local/lib -lhdf5 -lhdf5_hl -lhdf5_cpp main.cp... | Maybe you want also link with -lhdf5_hl_cpp. If you had used cmake, as I suggested today, you would not have such issues.
|
71,135,584 | 71,136,043 | C++ parse a file and store contents into a map | I am new, I parsed this text file and I am trying to store its contents into a map and print them out. I can't seem to get the itr to work.
this is the text file
addq Src,Dest
subq Src,Dest
imulq Src,Dest
salq Src,Dest
sarq Src,Dest
shrq Src,Dest
xorq Src,Dest
andq Src,Dest
orq Src,Dest
incq Dest
decq Dest
n... | This works:
map<string, string>::iterator itr;
for (itr = registers.begin(); itr != registers.end(); ++itr)
{
// " : " separates itr->first and itr->second. Can be changed.
std::cout << itr->first << " : " << itr->second << std::endl;
}
Final code:
#include <iostream>
#include <fstream>
#include <sstream>
#i... |
71,135,589 | 71,135,656 | Changing variable in c++ | I started learning C++ and I made a simple thing like printing variables etc, but I wanted to make a new value on a variable like in Python:
test = "hello world"
print(test)
test = 5
print(test + 6)
So I had this:
string test = "hello world";
cout << test << "\n";
And now I wanted to assign a number to test, so I use... |
is it possible to assign a new type to a variable somehow?
A new type, no. C++ is a statically typed language. Variable types are specified at compile-time and cannot change at runtime.
For what you are asking, the closest thing available is std::variant in C++17 and later, which is a fixed class type that can hold... |
71,135,634 | 71,135,799 | display list is only displaying the head of the node | I wrote a code that asks the user to enter a custom list, and I want to display it, but it's only displaying the head node.
I want to know if the problem is from the display function or the input function. I want to remove the display function later, but I want my list to be created.
Here is my code:
#pragma once
#incl... | inputList fails to link the nodes together. We could probably get away with something like
tmp = new node;
cur->next = tmp; // point current node's next at new node
cur = cur->next;
but here's a cleaner approach:
node* inputList() {
node * head; // storage for the start of the list. Keeps track so we
... |
71,135,887 | 71,136,233 | Does arithmetic overflow overwrite data? | std::uint8_t x = 256; //Implicitly converts to 0
std::uint8_t y = 255;
y++;
For x, I assume everything is handled because 100000000 gets converted to 00000000 using some defined conversion from int to uint8_t. x's memory should be 0 00000000 not 1 00000000.
However with y I believe the overflow stays in memory. y is ... |
Does arithmetic overflow overwrite data?
The behaviour of signed arithmetic overflow is undefined. It's neither guaranteed to overwrite data, nor guaranteed to not overwrite data.
std::uint8_t y = 255;
y++;
Unsigned overflow is well defined. y will be 0, and there are no other side-effects.
Citation from the C++ ... |
71,135,955 | 71,135,986 | problem of using const when passing a pointer | Visual studio shows a error saying "the object has type quantifiers that are not compatible with the member function 'somfunc' "
class T_ship {
public:
...
float ship_run(int ship_len);
// function ship_run doesn't change any class member values
};
There is a function in main() with *... | If you want the actual pointer to be const and not the object pointed to, put the const in front of the type, so like this:
T_ship * const
However in your case if the function ship_run doesn't modify anything you should
mark it as const at the end of the function as well so like this:
float ship_run(int v) const { /* y... |
71,136,128 | 71,136,224 | c++ qt can i fill a QVariant with multiple struct objects | I have the following struct:
struct FileInfo {
QString fileName;
QString fileSize;
QString md5Sum;
};
is it possible to put approximately 30 such objects into a QVariant and then be able to iterate through the QVariant to retrieve one of the structs based on index and then cast the object back into a struct and query ... | You can consider QVariantList to store object as QVariant. Of course, you can convert back into your custom struct.
Example.
struct FileInfo {
QString fileName;
QString fileSize;
QString md5sum;
};
int main()
{
QVariantList variantList;
for(int i = 0; i < 30; i++) {
FileInfo info{QString("... |
71,136,439 | 71,137,444 | C++ regex_replace not substituting Latex like expression | Looks like regex_replace is only replacing the left parenthesis. And that too is not without a backslash:
#include <iostream>
#include <regex>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
string text = "\\left( 0 + 1 \\right)";
text = regex_replace(text, regex("\\left\\("), "(");
te... | It seems \\\\ is required instead of \\. And also for round braces, I used [(] and [)].
#include <iostream>
#include <regex>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
string text = "\\left( 0 + 1 \\right)";
text = regex_replace(text, regex("\\\\left[(]"), "(");
cout << text << en... |
71,136,451 | 71,136,740 | Return value of (std::cin >> variable) | I am a C++ beginner,
#include <iostream>
int main()
{
char v1;
// valid no warning
std::cout << (std::cin >> v1) << std::endl; // return value of the expression expected
return 0;
}
// output: 1
// return value of the expression is 1?
Is the return value of (std::cin >> v1) really 1? Why?
| I don't know of a current compiler that will accept your code as it stands right now. g++, clang and Microsoft all reject it, saying they can't find an overload to match the arguments (i.e., an operator<< for ostream that takes an istream as an operand).
It's possible to get the result you've posited with code on this ... |
71,136,464 | 71,136,615 | why cannot we initialize a node without using a pointer? | I have recently started learning data structure and as a beginner, I have a query while implementing linked list nodes, why do we have to initialize node using a pointer only?
class node{
public:
int data;
node* next;
node(int val){
data = val;
next = NULL;
}
};
int main(){
nod... | Actually you can initialize the node by value. If you want to initialize a node with value, according to your constructor node(int val), you have to code like below:
class node{
public:
int data;
node* next;
explicit node(int val){
data = val;
next = NULL;
}
};
int main(){
int ... |
71,136,617 | 71,143,165 | char passed into function that receives char. yet char& is in error | error: no match for call to ‘(std::_Mem_fn<void (CNC::CGUI::*)(float, char)>) (float, char&)’
void CGUI::null(float numP, char dir){}
void CGUI::Function()
{
auto function_X_axis = std::mem_fn(&CGUI::null);
}
void Move_X_axis(float numP, char dir){}
void CGUI::Function2()
{
function_X_axis = std::mem_fn(&CGU... | Probably because the argument could be passed as lvalue reference to char.
Passing by value would be as good.
It doesn't really matter as your problem is lack of the CGUI object:
#include <functional>
struct CGUI
{
void null(float, char);
};
void CGUI::null(float numP, char dir){}
int main()
{
CGUI gui;
... |
71,136,842 | 71,146,211 | Why unique_ptr's Deleter need an argument of type unique_ptr<T, Deleter>::pointer? | I see the describtion about unique_ptr on cppreference, it says Deleter must be FunctionObject or lvalue reference to a FunctionObject or lvalue reference to function, callable with an argument of type unique_ptr<T, Deleter>::pointer, I don't understand why there is such a requirement that
FunctionObject must have a... | That requirement is expressing that unique_ptr more or less looks like this:
class unique_ptr {
pointer ptr;
[[no_unique_address]] deleter_type del;
public:
/* other members */
~unique_ptr() { del(ptr); }
};
That is, it ensures that the pointed-to value is "freed" when the pointer is destroyed, whatev... |
71,137,509 | 71,138,045 | Unable to overload '[ ]' in here. C++ Noob here | I am trying to implement a linkedlist in C++ and trying to incorporate array like data access using '[]'.
First I declared a Node class as the following.
class Node{
public:
int data;
Node *next, *prev;
Node(int val){
this -> data = val;
this -> next = NULL;
this -> prev = NU... | Since l is a pointer which is created by
LinkedList *l = new LinkedList();
it needs to be dereferenced to be able to use operator first.
This would solve your problem:
cout << (*l)[0];
But I suggest you to not create LinkedList with new keyword so you can avoid using raw pointers and memory leaks in the application cod... |
71,137,994 | 71,138,034 | Define a friend function for a static class method? | Does someone know how to let outside world access private static methods? The only way I could think of is via friend function, but that doesn't seem to work.
Header file here:
#pragma once
#include <iostream>
class MyClass {
public:
friend void AtFork();
private:
static void Disp() { std::cout << "hello w... | The issue in your code is the anonymous namespace. The AtFork in main.cpp can only be accessed within main.cpp. The AtFork you declared as friend is a different one. Do not use an anonymous namespace and the code compiles fine:
#include <iostream>
class MyClass {
public:
friend void AtFork();
private:
stati... |
71,138,072 | 71,138,358 | FLIPCOIN problem solution using SegmentTree has high runtime | I've been trying to solve the FLIPCOIN question of CodeChef (https://www.codechef.com/problems/FLIPCOIN) but I always received the message Time Limit Exceeded.
The input is as follows: First comes a number n, the length of a row of coins, all turned tails up initially, and a number q, the number of tasks.
After that fo... | The reason why your code is slow is that while your range queries take logarithmic time, your range updates take linear time. When updating a range of length n, you don't want to look at all n elements in that range. Instead, you want to make your updates lazy.
What does that mean?
If the range of a SegTree node is ful... |
71,138,247 | 71,138,563 | Can we have multiple c files to define functions for one header file? | Newbie to C and C++.
I have one .h file in which some functions are declared.
I'm trying to implement the functions in two separate .c files, but when compiling I got a linker error.
Is it not allowed?
| Yes it is allowed. Here is a very simple example:
foobar.h: declares foo and bar
void foo(void);
void bar(void);
foo.c: implements foo
#include <stdio.h>
#include "foobar.h"
void foo(void)
{
printf("foo\n");
}
bar.c: implements bar
#include <stdio.h>
#include "foobar.h"
void bar(void)
{
printf("bar\n");
}
main... |
71,138,291 | 71,138,732 | `std::cout << FooStuff::Foo();` chooses completely unrelated overload instead of exactly matching one | I have this code:
#include <iostream>
namespace FooStuff
{
struct Foo { };
}
decltype(std::cout)& operator << (decltype(std::cout)& left, const FooStuff::Foo& right)
{
return left;
}
void test1()
{
// This works fine
std::cout << FooStuff::Foo();
}
As far as I can tell, this is the best operator << ... | When you write std::cout << FooStuff::Foo(); name lookup is done to determine the candidates for << to use in overload resolution.
For overload resolution of operators there are two parts to this lookup: unqualified name lookup of operator<< and argument-dependent lookup of operator<<.
For unqualified name lookup, as i... |
71,138,329 | 71,138,572 | std::initializer_list and std::make_shared: too many arguments ... 3 expected 0 provided | I am not really getting any smarter from these error messages.
Minimal (not) Working Example on godbolt
#include <initializer_list>
#include <memory>
#include <vector>
struct S
{
int j;
double y;
std::vector<int> data;
S(int i, double x, std::initializer_list<int> list)
: j(i)
, y(x)
, dat... | {1,2,3} can be multiple things, and make_shared has no possibility of knowing what it is at the time parameter pack is expanded.
If you don't want to state the long std::initializer_list<int>{1,2,3} explicitly, the easiest solutions would be:
a. shortening the type's name: using ints=std::initializer_list<int>;
b. wrap... |
71,138,600 | 71,139,766 | Permutations of an int array, using recursion | Exercise is as follows:
Generate every possible sequence whose elements are from the set {0,
1, 2} where 0 occurs m times, 1 occurs p times, and 2 occurs q times. The input file
contains three natural numbers separated by spaces, with a maximum value of 100. The solution must be written to the output file line by line... | Here's what I came up with. Each recursive step will attempt to append "0", "1", or "2" to the string being built until there's no available digits to add.
#include <iostream>
#include <string>
using namespace std;
void GeneratePermutations(int zeros, int ones, int twos, const string& leading)
{
if ((zeros <= 0... |
71,138,955 | 71,140,203 | C++ alternative to singleton design when a function-only class needs to be initialize at least once? | #include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <random>
#include <map>
#include <math.h>
#include <cstring>
using namespace std;
class MathClass {
private:
size_t current_capacity;
double* logfact;
bool inited = false;
MathClass() {
... | I agree with comments: Why hide the fact that MathClass caches results from the user? I, as a potential user, see no real benefit, rather potential confusion. If I want to reuse previously cached results stored in an instance I can do that. You need not wrap the whole class in a singleton for me to enable that. Also th... |
71,139,220 | 71,140,583 | How can ignore bazel features like `treat_warnings_as_errors` only on some files? | I have a library like the following in my bazel build file for C++:
cc_library(
name = "mylib",
srcs = [
"main.cpp",
"file1.cpp",
"file2.cpp",
...
],
hdrs = [
"main.h",
"file1.h",
"file2.h",
...
],
features = [
"treat_warnin... | My solution for this was creating a new library as a wrapper for third_party_dependency not to mess up with third party code and on that second library I just had to add #pragma GCC system_header on the header file so that my gcc compiler ignores that file.
redits for How to eliminate external lib/third party warnings ... |
71,139,251 | 71,142,509 | How to add a server certificate to WebView2 | Assume we are going to visit the website that is only known by our little circle, and we want to protect the connections so HTTPS will be used. Because this is a small circle, we don't want to send a X.509 request to a CA and wait for the certificate. We want to use a self-signed X.509 certificate. Now, the problem is ... | WebView2 uses the computer's certificate store, just like the Edge browser.
So you simply install your self-signed certificate in the certificate store, under 'Trusted root certificates'. Now the computer accepts the certificate and so will WebView2.
Actually I recommend you create two certificates, on root certificate... |
71,140,123 | 71,140,446 | How to inherit from an abstract class properly in C++? | I couldn't find a proper topic for this question as I haven't got a proper error message.
I'm trying to create a management system for a restaurant which mainly provides pizza as well as other foods(pasta, wings, etc). I want this system to be used by the staff. I have created an abstract class named Foods that can be ... | You need to implement the static member variables sauces and drinks in functions.cpp and not in interfaces.h.
functions.cpp
namespace foods {
int Pizza::retPrice() {
return (price + 5);
}
void Pizza::ask() {
std::cout << "Hello World!";
}
// implement the static variables here.
const std::vector<st... |
71,141,181 | 71,152,194 | Fetch SCT list from x509 certificate |
How can I fetch this SCT list from PCCERT_CONTEXT? Is there any straightforward win API?
| With the following code snippet, I could able to fetch the SCT list as a string from X509 certificate
std::wstring GetSCTString(PCCERT_CONTEXT certInfo)
{
PCERT_EXTENSION ext;
ext = CertFindExtension(szOID_CT_CERT_SCTLIST, certInfo->pCertInfo->cExtension, certInfo->pCertInfo->rgExtension);
if (NULL != ext)
... |
71,141,631 | 71,142,317 | Initializing Texture2DArray | I'm trying to create and initialize a 2D texture array in the following way:
D3D11_TEXTURE2D_DESC desc{};
desc.ArraySize = 10; // there should be 10 textures
desc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_UNORDERED_ACCESS;
desc.Usage = D3D11_USAGE_DEFAULT;
desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
desc.Wi... | Problem solved: for texture array you have to pass an array of D3D11_SUBRESOURCE_DATA in CreateTexture2D function.
|
71,141,761 | 71,143,147 | Reading a .dat File in C++ gives Symbols instead of Numbers | I am trying to open a .dat binary file in C++ as an exercise, however when I try to print out the contents of the file, I receive symbols instead of numbers.
Here is the code on how I read the .dat file:
int main() {
errno_t status;
std::FILE *input_file;
status = fopen_s(&input_file, filename, "rb");
... | The loop
for (int i = 0; i < 10; i++) {
std::cout << content[i];
}
is printing the data by interpreting the data as representing the character codes of invidual characters. However, this is not what the data represents. The data actually represents single-precision floating-point numbers. Therefore, you should int... |
71,142,195 | 71,198,789 | can i speed up more than _mm256_i32gather_epi32 | I made a gamma conversion code for 4k video
/** gamma0
input range : 0 ~ 1,023
output range : 0 ~ ?
*/
v00 = _mm256_unpacklo_epi16(v0, _mm256_setzero_si256());
v01 = _mm256_unpackhi_epi16(v0, _mm256_setzero_si256());
v10 = _mm256_unpacklo_epi16(v1, _mm256_setzero_si256());
v11 = _mm256_... | Since the context of your question is still a bit vague for me, just some general ideas you could try (some may be just slightly better or even worse compared to what you have at the moment, all code below is untested):
LUT with 16 bit values using _mm256_i32gather_epi32
Even though it loads 32bit values, you can still... |
71,142,279 | 71,142,577 | What's the difference between two QHeaderView signals? | On Qt doc website in QHeaderView class i found two signals with similar descriptions:
void QHeaderView::sectionDoubleClicked(int logicalIndex)
and
void QHeaderView::sectionHandleDoubleClicked(int logicalIndex)
what's the difference between the two of these? When should I use the first, and when the other?
| Although the documentation strings are exactly the same,
void QHeaderView::sectionDoubleClicked(int logicalIndex)
This signal is emitted when a section is double-clicked. The section's logical index is specified by logicalIndex.
[signal]void QHeaderView::sectionHandleDoubleClicked(int logicalIndex)
This signal is em... |
71,142,385 | 71,142,540 | Is it possible to pass static function as template argument without adding new function argument? | One can pass callback to other function using template to abstract from real callback type:
float foo(int x, int y) {return x*y;}
template<class F>
void call_it(F f, int a, int b)
{
f(a,b);
}
There is a cost of passing f as an argument and calling it indirectly. I wonder if, in case f is a static function it is ... | You can use a non-type template parameter. To still allow all kinds of callables you can use auto:
#include <iostream>
struct foo {
static float bar(int a,int b){
std::cout << "foo: " << a << " " << b;
return a + b;
}
};
template <auto f>
float call_it(int a,int b){
return f(a,b);
}
int m... |
71,142,574 | 71,231,921 | confusion with cppyy for overloaded methods and error handling | I have a c++ class with several constructors:
MyClass(const std::string& configfilename);
MyClass(const MyClass& other);
I have python bindings for this class that were generated with cppyy - I don't do this myself, this is all part of the framework I'm using (CERN ROOT, in case you're wondering).
Now, I have a piece ... | cppyy doesn't use try/except for overload resolution, hence there are also no __context__ and __cause__ set. To be more precise: the C++ exception is not an error that occurs during a handler. Rather, as-yet unresolved overloads are prioritized, then tried in order, with no distinction made between a Python failure (e.... |
71,142,707 | 71,142,964 | Calling undeclared function template from inside another function template | I am learning about templates in C++ and so trying out different examples. One such example whose output i am unable to understand is given below:
template<typename T> void func(T p) {
g<T>(p); //ERROR
g(p); //NO ERROR?
}
int main()
{
}
When i try to compile the above code snippet, i get error saying:
prog.cc: I... | Case 1
Here we consider the statement: g<T>(p);
template<typename T> void func(T p) {
g<T>(p); //ERROR
}
int main()
{
}
In the above code snippet the name g is a unqualified dependent name. And from source: two phase lookup:
During the first phase, while parsing a template unqualified dependent names are looked up u... |
71,143,129 | 71,144,161 | Is there a way to convert a base 2^64 number to its base10 value in string form or display it in standard out in C or C++ without using big num libs? | Let's say I have a very large number represented using an array of unsigned long(int64), and I want to see its base10 form either stored in a string and/or display it to the standard out directly, how would I do that in C or C++ without using libraries like gmp or boost?, what algorithm or method should I know?
below ... | Repeatedly "mod 10" the array to find the next least significant decimal digit, then "divide by 10". Repeat as needed.
Avoid unsigned long to encode 64-bit values as it may be only 32-bit.
If code can encode the number not using the widest type and use uin32_t, then doing the repeated "mod 10" of the array is not so ... |
71,143,176 | 71,524,778 | How to create a shared library using object library in CMake | I have two shared libraries each one having its own CMakeLists.txt. The directory structure is like this.
main_dir
|--- subdir
| |--- src1.cpp
| |--- src2.cpp
| |--- src3.cpp
| |--- CMakeLists.txt
|--- src11.cpp
|--- CMakeLists.txt
Currently, I am able to build both main library and sub library (say main.s... | I was able to get it working by setting PARENT_SCOPE for the object library in the suddirectory. The modifications to the original code look like this.
main_dir/CMakeLists.txt
set(SUBARCHIVE_OBJECTS)
add_subdirectory(subdir)
target_link_libraries(mainlib private ${SUBARCHIVE_OBJECTS}
subdir/CMakeLists.txt
add_library... |
71,143,460 | 71,143,614 | how to set filter from another view? | std::vector v1 {4,2,7,6,4,1};
std::vector v2 {3,0,0,0,0,3};
I want to get the values in v1 with the condition v2=3
my desired result [4,1]
I tried with filter but it seems to work only with a specified value.
auto rng = v1 | ranges::views::filter([](int x){return ...;});
How can I do this without using for-loop?
| Should be something along these lines:
zip v1 and v2,
filter based on the .second of each element with the condition you like
transform to only retain the .first of the survived elements
Here's a working demo:
#include <iostream>
#include <range/v3/view/filter.hpp>
#include <range/v3/view/transform.hpp>
#include <ran... |
71,143,920 | 71,144,906 | std::ranges::find_if - no type in std::common_reference | I'm using the SG14 flat_map as a container.
As per a standard map, it takes Key and Value template parameters.
Unlike a standard map, however, it doesn't store std::pair<Key, Value> in a binary search tree, but rather stores the keys and values in two separate containers (additional template arguments which default to ... |
Why does the combination of const range and const auto& lambda
argument fail to compile, while pasing a mutable range works and
taking the lambda argument by value works?
First, the operator*() of the iterator of flat_map is defined as follows:
reference operator*() const {
return reference{*kit_, *vit_};
}
And th... |
71,143,968 | 71,147,781 | How to get a python list that is converted to a string, assigned to attributes in a struct in C++ | Okay I am editing my original post. Apologies for not being clear enough earlier. I am relatively new to the developer role, specifically C,C++,Python and Embedded Linux.
There is a python list plist = [2,434]
This data is sent to another program written in C++ using socket programming.
plist = str(plist)
sock = socket... | C++ is a powerful language but part of that power is to let you do things that aren't "correct". The way you are trying to cast a char * to a PLAYER_HEADER* just doesn't work as you are expecting it to. You need to parse the string, ignoring parts you don't want and converting the parts you keep to the correct data typ... |
71,144,609 | 71,153,708 | How to set a new window into a GroupBox in QT? | I have a Window with a Group Box called Function control box
I want to include this window into that group box
I do that by using this code
ui->functionControlBoxGroupBox->setParent(componentIdentification);
Where componentIdentification in an UI object of the window above.
But it seems that nothing happens. Why?
Th... | Conceptually, the group box is supposed to be the other window's parent (not the opposite), thus you should do:
componentIdentification->setParent(ui->functionControlBoxGroupBox);
A better way to do the same thing: set a layout to the parent (the group box) and add the child window to the layout, i.e., in construction... |
71,145,570 | 71,193,609 | Can't open thread token of NamedPipe client: "Cannot open an anonymous level security token" | I am trying to impersonate a client with SYSTEM privileges.
I noticed that this client it trying to connect to the named pipe: \\.\pipe\abc.
I setup a named pipe server \\.\pipe\abc and wait for it to connect.
Once it was connected, it failed:
[+] Creating pipe server
[+] Waiting for client to connect
[+] Client connec... | based on comments, in client code -
FILE_FLAG_OPEN_NO_RECALL | FILE_FLAG_OVERLAPPED;
used if place dwFlagsAndAttributes in call of CreateFile
however need notice that FILE_FLAG_OPEN_NO_RECALL == (SECURITY_SQOS_PRESENT|SECURITY_ANONYMOUS) and FILE_FLAG_OPEN_NO_RECALL == SECURITY_SQOS_PRESENT
both this flags have the sam... |
71,147,238 | 71,147,390 | Vector Keeps over printing output | #include <iostream>
#include <stdlib.h>
#include <pthread.h>
#include <fstream>
#include <sstream>
#include <mutex>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <vector>
using namespace std;
#define NUM_THREADS 2
pthread_mutex_t mutexChild;
pthread_cond_t condChild;
ve... | while (!inFile.eof())
{
getline(inFile, line);
for (int i = 0; i < vect.size(); i++)
cout << vect[i] << endl;
}
prints out the contents of the vector built in the child thread once for every line in the file (sort of. See Why is iostream::eof inside a loop cond... |
71,147,810 | 71,156,072 | How to change background color in QGraphicsScene? | I want to give background color in my QGraphicsScene. For that, I have override drawBackground() method, and tried to set color but it is not working. Background color is not changing.
Here is my drawBackground() method.
Widget.h
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public ... | Your code has a number of problems or, at least, inconsistencies. Firstly your Widget class makes use of both inheritance and composition with regard to QGraphicsView in that it derived from QGraphicsView and has a QGraphicsView member. That may be what you want but it seems unlikely.
Firstly, you say...
I want to s... |
71,147,822 | 71,148,165 | opengl draw tringle with projection and view projection | I am trying to draw a tringle with OpenGL by using projection view and model matrices.
this is my shader
gl_Position = view * projection * model * vec4(pos, 1.0);
and this is my code
glm::mat4 view = glm::translate(view, glm::vec3(0.0f, -0.5f, -2.0f));
glm::mat4 proj = glm::perspective(glm::radians(45.0f), (flo... | The correct MVP matrix multiplication order should be:
gl_Position = projection * view * model * vec4(pos, 1.0);
Think about matrix-vector multiplication as it associates right-to-left: first you transform from model to world space, then from world to view space (via inverse camera matrix) and finally you project from ... |
71,148,130 | 71,151,713 | How would you implement a lazy "range factory" for C++20 ranges that just calls a generator function? | I like the idea of the lazy ranges you can make with std::views::iota but was surprised to see that iota is currently the only thing like it in the standard; it is the only "range factory" besides views::single and views::empty. There is not currently, for example, the equivalent of std::generate as a range factory.
I ... | The reason why generate2 cannot work is that it does not model the range concept, that is, the type returned by its begin() does not model input_iterator, because input_iterator requires difference_type and value_type to exist and i++ is a valid expression.
In addition, your iterator does not satisfy sentinel_for<itera... |
71,148,182 | 71,148,259 | Object reading and writing overload in C++ | I know that the assignment operator can be overloaded. When writing to an object, the object's overload function is called.
Obj = 10; // Obj's assignment overload function called.
Is there a way to define a function to be called when an object is read?
int a = Obj;
In this case Obj's reading function would be called ... | You're looking for what's sometimes called a cast operator.
example:
#include <iostream>
struct example
{
int val;
operator int() const { return val; }
};
int main ()
{
example x{42};
int y = x;
std::cout << y;
}
Will print 42.
|
71,150,660 | 71,150,981 | Extracting vectors from Structure in header file | This is the header file in question:
namespace osc {
using namespace gdt;
struct TriangleMesh {
std::vector<vec3f> vertex;
std::vector<vec3f> normal;
std::vector<vec2f> texcoord;
std::vector<vec3i> index;
// material data:
vec3f diffuse;
};
struct Model {
~Model()
{... | loadOBJ() gives you a pointer to a Model object.
Model has a std::vector (a dynamic array) member named meshes that holds pointers to TriangleMesh objects.
TriangleMesh has a std::vector member named vertex holding vec3f objects.
You can iterate the various vectors like this:
osc::Model *model = osc::loadOBJ(...);
if (... |
71,150,895 | 71,151,247 | My code should render the front of a cube, but instead shows the back. Why? | I'm rendering this cube and it should show the front of the cube but instead it shows the back (green color). How do i solve this? I've been sitting for a couple of hours trying to fix this but nothing helped. I was trying various things like changing the order in which the triangles are rendered and it didn't help eit... | You currently are using glEnable(GL_DEPTH_TEST) withglDepthFunc(GL_LESS), which means only fragments having a smaller z (or depth) component are rendered when rendering overlapped triangles. Since your vertex positions are defined with the back-face having a smaller z coordinate than the front-face, all front-face frag... |
71,151,350 | 71,151,505 | C++ Member Functions (getters) | I've seen people define a member function like this:
void getValue(int& v)
{
v = m_value;
}
and also like this:
int getValue()
{
return m_value;
}
I guess the first saves memory? Is that the only time you would use the first type of get-function? The second seems a lot more convenient.
| I thought I would godbolt it for you
source
#include <iostream>
struct Foof{
int m_val;
Foof(int v){
m_val = v;
}
void woodle()
{
if(m_val > 42)
m_val++;
else
m_val--;
}
void Get1(int &v)
{
v = m_val;
}
int Get2()
{
return m_val;
}
};
int main(int c, char**v){
i... |
71,151,379 | 71,151,592 | How to generate current datetime with system's regional format in C++? | I'm looking for a way to get the current system date time formatted in a manner consistent with the system's region.
For example, a system in the US would have something like:
01-31-2022 1:59:00 PM
And a system in Europe would have something like:
31-01-2022 13:59:00
I've experimented a bit with using Boost but can't s... | First, we configure the locale for the user's default by imbuing the output stream with the empty-name locale (locale("")). Then we use the locale-dependent date and time formats with std::put_time. For example: Live On Coliru
#include <ctime>
#include <iomanip>
#include <iostream>
int main() {
std::time_t raw_now... |
71,151,613 | 71,152,639 | how does python package links to dll (.so) files | I am creating a python package based on this repo. The package has few cpp files which are compiled when I build the package using setup.py and running pip install . This generates _C.cpython-36m-x86_64-linux-gnu.so file in my package installation directory. To import this dll (.so) file all I have to do is
from . impo... | No. The mechanism for handling the C++ library loading is done by pybind. In the documentation (https://pybind11.readthedocs.io/en/stable/basics.html), you will see that in order to import a C++ library built with the pybind API, the correct syntax in your .py file is to import the prefix of the library. Thus, when you... |
71,151,900 | 71,152,071 | Segmentation fault in static member function c++ | class Adder {
public:
static int Solve(int a, int b) {return a + b;}
};
class Substructor {
public:
static int Solve(int a, int b) {return a - b;}
};
class Comparer {
public:
static bool Solve(int a, int b) {return a < b;}
};
class If {
public:
static int Solve(bool term, int a, int b) {return term ?... | The problem arises here:
class Fibo {
public:
static int Solve(int num) {
int res =
If::Solve(
Comparer::Solve(num, 2),
1,
Adder::Solve(
Fibo::Solve(Substructor::Solve(num, 1)),
Fibo::Solve(Substructor::Solve(num, 2))
)
);
return res... |
71,152,918 | 71,152,972 | About increment/decrement operators | Here is the code snippet:
#include <iostream>
#include <iterator>
#include <algorithm>
#include <functional>
#include <vector>
std::vector<int> vec(5);
int produce_seq()
{
static int value = 0;
return (value*value++);
}
int main()
{
std::generate_n(vec.begin(),5, produce_seq);
for(auto val:vec)
{... | Your program has undefined behavior.
The order in which operands are evaluated is generally unspecified in C++. The only thing we can say in your example is that the value computation of value++ happens before its side effect on value and that the value computations of both the left-hand side and the right-hand side of... |
71,152,949 | 71,153,020 | In C++, How a std::thread can call a member function without creating an object? | If we have a class H with some operator() overloaded. How it is possible to create a thread from these member functions without instantiating an object from class H. Consider the following code
#include<iostream>
#include<thread>
class H {
public:
void operator()(){
printf("This is H(), I take ... |
how td_1 and td_2 called the member function operator() of class H without an object of class H?
td_1 and td_2 does create objects of type H. Those objects are temporaries. Next, those supplied function object(which are temporaries in this case) are moved/copied into the storage belonging to the newly created thread ... |
71,153,181 | 71,153,435 | Sort Integers by The Number of 1 Bits . I used one sort function to sort the vector ? But why sort is not working? | Sort Integers by The Number of 1 Bits
Leetcode : Problem Link
Example Testcase :
Example 1:
Input: arr = [0,1,2,3,4,5,6,7,8]
Output: [0,1,2,4,8,3,5,6,7]
Explantion: [0] is the only integer with 0 bits.
[1,2,4,8] all have 1 bit.
[3,5,6] have 2 bits.
[7] has 3 bits.
The sorted array by bits is [0,1,2,4,8,3,5,6,7]\
Examp... | As your iteration in //This sort function ...
refers to mp as the copy of the value inside the map, sort function will not sort the vector inside it, but the copy of it. Which does not affecting the original vector<int> inside the mp. Therefore, no effect occurs. You should refer the vector inside the map as a referen... |
71,153,486 | 71,153,688 | Send data with libcurl to .php in c++ | I use libcurl to send request to my site for fetching some info.
But I don't know how to get data from user (c++) and send that to .php file.
It's my c++ source which get name from user :
std::string userUname;
std::cout << "[?] Enter Your Username: ";
std::cin >> userUname;
CURL* curl;
... | You have to send the userUname in the body : curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "name=" + userUname );
And in PHP change $_GET by $_POST OR $_REQUEST
|
71,154,459 | 71,154,695 | C++: GetTempPath() without tilde (~) | I need to get temp path. So I tried GetTempPath() and std::getenv("TEMP"). The problem is that the result contains ~ symbol, for example C:\Users\OLEKSI~1.ALE\AppData\Local\Temp.
Is it possible to get full temp path like C:\Users\Oleksii\AppData\Local\Temp?
| GetLongPathName function:
Converts the specified path to its long form.
DWORD GetLongPathNameW(
[in] LPCWSTR lpszShortPath,
[out] LPWSTR lpszLongPath,
[in] DWORD cchBuffer
);
DWORD GetLongPathNameA(
[in] LPCSTR lpszShortPath,
[out] LPSTR lpszLongPath,
[in] DWORD cchBuffer
);
Set lpszShortPath =... |
71,154,815 | 71,154,961 | Should we use delete[] or delete on function that return allocated memory pointer? | Should i use delete[] or delete for Register() example below? We hit some memory leak issue and legacy code which is not allow to change the return type and input of the function. I understand that new[] should use delete[]. new should use delete. However for case below, which method is correct?
UINT Register(UINT rega... |
I understand that new[] should use delete[]. new should use delete.
unsigned char *buffer = new unsigned char[4];
...
delete buffer;
The program is wrong, and against your understanding. When a dynamic array is allocated dynamically with new[], delete[] must be used to deallocate it. If you use delete, then the beha... |
71,154,952 | 71,155,552 | Controlled access to private member | I have a class that contains a private std::vector and a flag. Every time an Object inside the vector is modified I want to set that flag.
This is what I came up with..
struct Object
{
float f;
int i;
}
class SomeClass
{
private:
std::vector<Object> Data;
bool Updated;
public:
inline const std::ve... | Your solution fails to achieve what you want.
SomeClass has an Update method that does some stuff and sets Updated to true. Data is used inside a couple of big functions, and first thing they do is to check Updated and call Update when it's false. Again this is just the best I could come up with and I always feel nake... |
71,155,502 | 71,333,674 | Display runtime error message in gRPC server side and pass it to the client | I am using gRPC in a project where I have to set and get values from some separate/outside functions. Some functions has case that if they get unwanted value they will throw runtime error. By following this I have got an idea to catch a error_state from inside of the gRPC function.
I am giving here some of my approach.... | Found the solution.
In server side I have missed to use the try ... catch in a right way.
server.cpp
try
{
Check_Value(request);
}
catch(const std::exception& e)
{
std::cout << e.what() << std::endl; // This will display the error message in server console
return grpc::Status(grpc::StatusCode::INVALID_ARGUM... |
71,156,078 | 71,156,293 | Will friend injections be ill-formed? | There used to be a paragraph in the standard which stated that
the names of a namespace-scope friend functions of a class template specialization are not visible during an ordinary lookup unless explicitly declared at namespace scope. Such names may be found under for associated classes.
template <typename T> struct ... | From P1787R6:
Merged [temp.inject] into [temp.friend]
(Adopted in N4885 in March 2021)
The current draft (N4901) reads ([temp.friend]p2):
Friend classes, class templates, functions, or function templates can be declared within a class template.
When a template is instantiated, its friend declarations are found by na... |
71,156,246 | 71,156,623 | How to propagate conan's compiler.cppstd setting to the compiler when building a library with CMake? | If you build a library with conan and set compiler.cppstd setting to e.g. 20 and call conan install, the libraries are still built with the default standard for the given compiler.
The docs say:
The value of compiler.cppstd provided by the consumer is used by the build helpers:
The CMake build helper will set the CON... | Avoid patching, it's ugly and fragile, for each new release you will need an update due upstream's changes.
The main approach is a CMakeLists.txt as wrapper, as real example: https://github.com/conan-io/conan-center-index/blob/5f77986125ee05c4833b0946589b03b751bf634a/recipes/proposal/all/CMakeLists.txt and there many o... |
71,156,692 | 71,156,881 | Will std::lower_bound be logarithmic for list<>? | Suppose I have a list<int> and maintaining it in ordered state. Can I isert new values into it with logarithmic complexity with code like this
#include <iostream>
#include <random>
#include <list>
#include <algorithm>
using namespace std;
ostream& operator<<(ostream& out, const list<int> data) {
for(auto it=data.... |
Will std::lower_bound be logarithmic for list<>?
No. Quote from documentation:
for non-LegacyRandomAccessIterators, the number of iterator increments is linear.
Which containers this function is inteded to use then?
std::lower_bound is intended for any container that is - or can be - ordered, and doesn't have fa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.