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 |
|---|---|---|---|---|
65,610,662 | 65,612,034 | C++ Search value through array of struct | im new to C++
i would like to search a variable entered through an array. the struct looks like this..
struct Person
{
string name;
string phone;
Person()
{
name = "";
phone = "";
}
bool Matches(string x)
{
return (name.find(x) != string::npos);
}
};
how... | Here is a little code snipped that illustrates how to search a struct. It contains a custom search function and also a solution using std::find_if from algorithm.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
struct Person
{
std::string name;
Person(const std::string &name) : na... |
65,611,069 | 65,611,728 | How to return return pointer from C++ dll function to C# | I have two extern function that one of them is return C++ pointer another is print ip and port, when i want to use on C# , parameters pass' successfully than print port and ip after that when i called second function,it dont print address correctly.
Cpp
Obj* x_create_obj_ip_port(const char* ip, int port) {
Obj* obj... | I think I figured your problem.
In x_create_obj_ip_port, you set obj->ip with a pointer on the parameter ip. I'm no expert in C# but I'm pretty sure the string "10.6.35.228" gets deleted right after the call, meaning now obj->ip points on nothing, explaining why print_ip prints garbage.
If you want to keep the content ... |
65,611,484 | 65,611,591 | How do I correctly find a string in a 2D char array? | The following code wants the user to input 3 words which will then be searched in the char array mrx.txt(found below for reference).
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
const int anz=20;
char mrx [anz][anz]; // memory for char array
for (int i=... | string str = mrx[a];
mrx is a char [][], so mrx[a] is a char []. This decays to a char *, and this statement uses std::string's assignment operator overload that initializes the std::string from a char *.
As you know, this char * is interpreted as a C-style string that's terminated by a null byte. Your 2D matrix has n... |
65,611,882 | 65,612,579 | How can i include iostream in tinkercad | When I write #include iostream in tinkercad, an error shows up saying "fatal error: iostream: No such file or directory"
How can I fix this?
full code
| Arduino environments generally do not support normal C++ headers like iostream (or e.g. vector). I.e., they do generally not offer support for standard library headers, though some may have been ported.
You may want to try basic Arduino tutorials and the "Blink" sketch as well as basic "Serial" examples (e.g. how to us... |
65,611,924 | 65,612,543 | Why window name changes window size on creation? | I create a window by using the OpenCV library, where I show images from a folder. (Images are changed by clicking the space bar).
In the window name, I want to show the count of images which were already shown, e.g. "10 out of 20 images".
The problem appears, when I click the space bar and the new window with another i... | You simply need resizeWindow and moveWindow to achieve that.
Here's some sample code:
#include <opencv.hpp>
int main()
{
std::vector<cv::Mat> images;
/* Feed some images here ... */
int width = 640;
int height = 480;
int x = 100;
int y = 100;
for (int i = 0; i < images.size(); i++) {
... |
65,612,229 | 65,612,806 | Flip 4x4 bit-grid horizontally/vertically/diagonally | I am programming a board game with ab board of 4x4 squares and use a unsigned short to save whether a stone is on each square. 0 := empty square and 1 := stone on square
A board with 8 stones like this:
1111
0000
0101
1010
is saved line by line like this:
unsigned short board = 0b1111000001011010 // = 61530
I need t... | All three operations can be expressed using bitwise operations like this:
uint16_t vert_flip_board(uint16_t x) {
return ((x & 0b0000'0000'0000'1111) << 12) |
((x & 0b0000'0000'1111'0000) << 4) |
((x & 0b0000'1111'0000'0000) >> 4) |
((x & 0b1111'0000'0000'0000) >> 12);
}
uint16_t ... |
65,612,418 | 65,612,764 | Why memory profiler doesn't show all the used memory? | When I am starting my application under valgrind with massif option I see 52.6 MiB peak usage.
But htop says the process took 875MB of RES memory.
The same behavior has heaptrack. Does anyone know why profiler doesn't report where 800+MB gone?
| Massif by default measures only the heap managed by malloc and friends. It doesn't attempt to track pages mapped by other means (for example with mmap).
In order to account for all pages, one needs to run massif with --pages-as-heap=yes.
Source: Massif manual.
|
65,612,815 | 65,613,899 | Cross multiply non-type variadic templates | My goal is to make this template work:
template <size_t... Ns>
struct mult
{
using cross = ?; // variadic size_t
static_assert(sizeof...(cross) + 1 == sizeof...(Ns), "");
};
So I can use it like this:
mult<2,3,5>::cross // 6,15 // because 2*3=6, 3*5=15
mult<3,5,7,11>::cross // 15,35,77 // because 3*5=15, 5*7=3... | If you want compile time computation, write constexpr functions
template<typename... SizeT>
constexpr auto cross(size_t x, SizeT... xs)
{
std::array tmp = {x, xs...};
std::array ret = {xs...};
for(size_t i = 0; i < ret.size(); i++)
ret[i] *= tmp[i];
return ret;
}
template<size_t... xs, size_t..... |
65,613,231 | 65,632,835 | Compiler segfault during explicit template instantiation on clang 11 | The following explicit template instantiation results in compiler frontend segfault under LLVM clang++ 11.0 on x86_64-pc-windows-msvc, using the clang-cl interface with -std=c++17, regardless of optimization level.
A.h
template <typename T>
class A
{
public:
T value;
static constexpr auto address = &A<T>::val... | Your example class A
// A.h
#pragma once
template <typename T>
class A {
public:
T value;
static constexpr auto address = &A<T>::value;
};
extern template class A<float>;
// A.cpp
#include "A.h"
template class A<float>;
used e.g. as in the following example (full demo here)
#include <iostream>
#include "... |
65,613,516 | 65,613,669 | How to check whether a class is stateless? | I'm writing a container, and want to only allow stateless allocators for it. From various sources I figured that such allocator should be an empty class, and should be trivially constructible, copyable and destructible. However, std::allocator has user-provided default constructor (though, with empty body) and thus fai... | You can use std::is_empty to check if a type has no non-static data members and no virtual functions, which would mean it has no state.
|
65,613,583 | 65,615,467 | wxWidgets app hanging when using modal dialog | I have a simple wxWidgets application where I create a wxMessageDialog and then show it.
For some reason when I return from the startup method the app will then hang.
Here is the code:
bool App::OnInit()
{
wxMessageDialog* dialog = new wxMessageDialog(NULL, "Message", wxMessageBoxCaptionStr, wxOK | wxCENTER | wxDIA... | You have to create the application main window in App::OnInit() and you don't do that. If you don't create the main window, you must return false, not true.
The main window is usually a class derived from wxFrame. You can also use SetTopWindow() to let wxWidgets know what the main window is.
bool App::OnInit()
{
if (... |
65,614,206 | 65,614,301 | c++ Getting wrong calculation from a function | This is my code of a function. In main i check if temperature is in kelvin or fahrenheit. When I get temp_enota = 'F' from main ( I do because I checked with debugging), and temp = 116 for some reason function returns 0 when it should be around 46. Any ideas why? It works fine for kelvins.
float pretvorbaTemp(char temp... | The reason you get 0 is because the expression
5/9
will evaluate to 0 as these are two integer values, thus the compiler generates the code to do an integer division.
Just change to
5./9
to force floating point.
|
65,614,257 | 65,619,135 | How do I declare a vector of sparse matrix in Eigen | To declare a vector of dense matrix in Eigen I am using the following format
std::vector<Eigen::MatrixXd> AMAT(idx, Eigen::MatrixXd::Zero(1000,1000));
where idx is the vector size. Is there an equivalent declaration to define a sparse matrix? I am currently declaring a sparse matrix as
Eigen::SparseMatrix<double> BMA... | Seeing you want the matrices in the vector to have differen sizes, you should probably not use that initialization constructor for std::vector.
Instead just build-up the vector element by element:
#include <Eigen/Sparse>
#include <vector>
#include <algorithm>
int main() {
auto sizes = { 100, 200, 300 };
std::... |
65,614,978 | 65,615,403 | C++: properly freeing a pointer to a struct | So I am trying to learn C++ (and a little bit of C) and was wondering if there is a truly proper way to free a pointer to a struct. There is an example of what I am talking about below.
#include <iostream>
struct guy {
int the_data;
};
int main() {
guy the_guy, *ptr;
ptr = &the_guy;
ptr->the_data = 3;
ptr ... | guy the_guy here is a local variable which lifetime is defined by its scope!
Free memory of local variable is just Undefined Behavior and you are lucky that it crashes.
free can be used only on memory which was allocated by malloc (or calloc or realloc).
In all other cases it will lead to undefined behavior, so do not ... |
65,615,662 | 65,618,125 | Program terminated with signal SIGABRT, Aborted. terminate called after throwing an instance of 'std::out_of_range' | The question is : Consider an array of numeric strings where each string is a positive number with anywhere from 1 to 10^6 digits. Sort the array's elements in non-decreasing, or ascending order of their integer values and return the sorted array.
vector<string> bigSorting(vector<string> unsorted) {
for(int i=0 ; i... | As pointed out in the comments, your error originates form your attempt to read a number with many digits (up to a million) into a 64bit number, which can hold all numbers up to 1<<64=18446744073709551616, i.e. no numbers with more than 20 digits.
Hence you must find another way to compare those strings. The question i... |
65,616,270 | 65,621,348 | New line with ncurses in c++ | #include <ncurses.h>
int main(int argc, char ** argv)
{
initscr();
while(1){
int c = getch();
if(c == 'q'){
break;
}
}
return 0;
}
Ok, sorry for bad formatting but that is the code.
It's work fine, the terminal catch any character I press but when I press ENTER i ca... | curses has a function for this:
nl/nonl
The nl and nonl routines control whether the underlying display device
translates the return key into newline on input.
The source-code comment mentions ICRNL:
/*
* Simulate ICRNL mode
*/
if ((ch == '\r') && sp->_nl)
ch = '\n';
which is a POSIX termios feature:
CR
Sp... |
65,616,376 | 65,616,401 | How to get input to vector of class? | I have a class POINT which consists of x and y coordinates. And I have a vector of this class. How can I get the coordinates from input? I tried P.x.push_back(x) but obviously it doesn't work. I am wondering how I can achieve this?
I want to get something like
{{1, 3}, {5, 2}, {7, 2}} as a vector.
class POINT {
public:... | If you are using C++11 or later, you can use initializer list.
for(int i = 0; i < n; i++) {
cin >> x >> y;
P.push_back({x, y});
}
Alternative way is to create a temporary structure and push (copy of) that. This way is available also in C++03.
for(int i = 0; i < n; i++) {
cin >> x >>... |
65,616,875 | 65,616,952 | C++ help to understand syntax of low level code | I was reading some code and found really hard to understand this:
extern "C" NTSYSAPI NTSTATUS NTAPI ObReferenceObjectByName
Here some real code:
extern "C" NTSYSAPI NTSTATUS NTAPI ObReferenceObjectByName(
PUNICODE_STRING ObjectName,
ULONG Attributes,
PACCESS_STATE AccessState,
... | There's only one return type, NTSTATUS, which is an enumeration. The others are modifiers on the function call, for example NTAPI resolves to __stdcall, which modifies how the function is called by the compiler, and NTSYSAPI resolves to declspec(dllimport), which marks the function as a library import.
Also this has no... |
65,617,293 | 65,617,419 | Qt Slot and signal are not connected: No such signal | I am trying to deal with slots and signals in Qt, for this I am trying to do the following:
The MyTestClass class should send a signal to the ReceiverClass class, the code:
mytestclass.h
class MyTestClass : public QObject
{
Q_OBJECT
public:
MyTestClass();
void makeSignal();
signals:
void sendSignal();
}... | QObject::connect(&testObj, SIGNAL(&testObj::sendSignal()), &receiverObj, SLOT(&receiverObj::receiverSlot));
You are mixing the syntax of the 2 methods for connecting signal and slots in Qt, either use :
QObject::connect(&testObj, SIGNAL(sendSignal()), &receiverObj, SLOT(receiverSlot()));
or
QObject::connect(&testObj,... |
65,617,373 | 65,617,479 | Why output of boost::adaptors::filtered has no member named size? | The following dummy program compiles and runs
#include <boost/range/adaptor/filtered.hpp>
#include <boost/range/adaptor/transformed.hpp>
#include <functional>
#include <utility>
#include <vector>
using boost::adaptors::filtered;
using boost::adaptors::transformed;
auto whatever = [](auto&& x){ return std::forward<decl... | When you transform a range, the size doesn't change. That means transform can known what the size will be, as it's the same as the input.
When you filter a range, you may or may not be removing elements from the range. This is done lazily, so you can't know until you go through the filtered range how large it will be... |
65,617,900 | 65,635,327 | What is the established way to export a cmake project with external dependencies? | I have a project that I am building with Cmake. It has the following directory structure:
Project
|
CMakeLists.txt
src
|
MyLib.h
|
MyLib.cpp
|
CMakeLists.txt
|
third_party
|
abseil-cpp
Since abseil-cpp is a third-party dependency that builds with Cmake, I add it as a subdirectory in my top level CMakeLi... | I suggest that instead of adding it as a subdirectory, install and use it through find_package. Looks like the find_package support was implemented.
In your CMakeLists.txt:
find_package(absl REQUIRED)
target_link_library(MyLib PUBLIC absl::base absl::optional)
Notice the PUBLIC, it is important.
Then define your depe... |
65,617,974 | 65,618,041 | C++ save pointer members with class when writing to file | I have a simple binary tree implementation in C++. I'm saving it to a file via std::ofstream::write((char*)&myTree, sizeof(mytree));.
However, the class is defined with pointers for the left and right nodes because of incomplete types.
class Node
{
public:
int value;
Node(int _value)
{
value = _valu... | Pointers refer to a specific location in memory. They can't be persisted to disk. When you start a new process and read them back, your process's memory layout will be different. So, what you're doing will not work.
You're going to have to write a custom serializer for your class, to handle its structure.
boost::ser... |
65,618,108 | 65,618,263 | c++ explicit specialization can not access primay template member but can access partial specialization member? | #include <iostream>
using namespace std;
template<class T, int I> // primary template
struct A {
void f(); // member declaration
};
template<class T, int I>
void A<T,I>::f() { } // primary template member definition
// partial specialization
template<class T>
struct A<T,2> {
void f();
void g();
vo... | It is important to realize that a class template is not a class, but only a blueprint for one.
A<char,2> matches the specialized blueprint, so it has f,g,h member functions. Contents of the primary template are completely ignored.
Because A is a template class, its methods are instantiated only when actually called and... |
65,618,221 | 65,618,546 | What does platform independent languages really mean? | Why isn't C/C++ called platform independent like java when the same source code written in C/C++ can be made to run on different operating systems by different compilers, just like JVM is used in java.
Isn't different compilers and JVM doing same thing and achieving platform independence.
|
Isn't different compilers and JVM doing same thing and achieving platform independence.
Not really. Your Java program is running within the JVM, which acts as a translation layer between the Java byte code and the native machine code. It hides the platform-specific details from the Java application code.
This is no... |
65,618,280 | 65,618,667 | How to have a function pointer to a generic lambda? | As the title says, how can I have the following intent expressed in code ? The requirements being the function pointer takes any type of arguments. Variadic doesn't work because of std::string.
https://godbolt.org/z/1E1szT
Note that I cannot directly use auto fp = <the lambda> because fp is a class member variable.
#in... | A variable template is perfectly fine.
Even the way you initialize them is fine.
Just be aware it is a template for variables, not a variable storing a template (which cannot exist).
Thus when finally using it, things fall apart:
How should the compiler know which of the myriad potential instances you mean?
Simple, you... |
65,618,281 | 65,618,350 | C++ function template overload: empty braces vs explicit int | There is some very basic example of C++ function template overloading resolution below (minimized from actual code)
struct S {
S() {}
S(int) {}
};
template <typename T = S>
void foo(T x) { std::cout << "S" << std::endl; }
template <>
void foo<S>(S x) { std::cout << "S spc" << std::endl; }
int main() {
fo... | There's only a single candidate that participates in overload resolution:
template <typename T=S> void foo(T);
The selection of function template specializations happens afterwards. In this case, we have:
foo({}) can't deduce T (because {} has no type), so instead we fall back to using the default argument for T, whi... |
65,618,369 | 65,618,589 | Using member-function-pointer with parameter-pack | template<typename Callback, typename Callee, typename... Args>
std::function<void(Args...)> safe_bind(Callback callback, std::shared_ptr<Callee> shared) {
std::weak_ptr<Callee> weak = shared;
return std::function<void(Args...)>([callback, weak](Args... args){
if(auto shared_ptr = weak.lock()) {
... | Just don't wrap the lambda in a std::function and use perfect forwarding of any argument types. You can also deal with other callables by using std::invoke which automatically deals with pointer-to-member(-functions), functions, and objects with an operator():
template<typename Callback, typename Callee>
auto safe_bind... |
65,618,471 | 65,618,515 | Can I use a scoped enum for C++ tag dispatch with templates? | Template newbie here. I'm experimenting with the following code:
#include <type_traits>
enum class Thread
{
MAIN, HELPER
};
template<typename T>
int f()
{
static_assert(std::is_same_v<T, Thread::MAIN>);
return 3;
}
int main()
{
f<Thread::MAIN>();
}
In words, I want to raise a compile-time assert if ... | Your existing code is close. Instead of using typename, you can just use the enum class name directly, as a non-type template parameter, like this:
template<Thread T>
int f()
{
static_assert(T == Thread::MAIN);
return 3;
}
You have to change the static_assert as well.
|
65,618,791 | 65,620,079 | I have a picture with a black part that I want to be cut out in c++(example below) | considering the variable result is the picture i want to be cropped without the black part
this is my code
cv::Mat result;
result = img1.clone();
cv::warpPerspective(img1, result, H, cv::Size(img1.cols + img2.cols, img1.rows));
Mat gray;
cv::cvtColor(result, gray, COLOR_BGR2GRAY);
Mat thresh;
threshold(result, thresh,... | Here's the general idea:
Convert the image to grayscale
Threshold everything that is above 0 using a simple binary threshold
Clean the binary image with morphology
Use the binary mask to get the largest contour on the image
Use the largest contour to get a bounding rectangle
Use the bounding rectangle to crop the imag... |
65,618,947 | 65,634,706 | computing points by determine the neighbors algorithm | I am doing a coding challenge in c++ regarding checking the values of a vector.
I have been stuck on this challenge for hours and I can't think of a proper solution.
I have a vector which is called values that looks like this :
std::vector <char > values {a,b,a,b,b,b,a,a,a,a,b,b,a};
Then after three values a column is... | Flood fill is an N-dimensional array region filling algorithm. It's used by e.g. bucket fill tools in image editing software to fill regions of similar color with a new color. It can be implemented with just about any graph search algorithm (DFS, BFS, etc.). It is also very similar to the types of array searching algor... |
65,619,562 | 65,619,680 | TCP server hangs, not responding to SYN | I have a strange issue with a TCP server that sometimes hangs. The weird issue is that when it hangs it does not receive any new connection, i.e. doesn't respond to the initial TCP SYN packet. I was pretty sure that since TCP handshakes are handled by the kernel, even when a program hangs clients should still at the ve... | Most likely, the listen queue is full. Not responding to the initial SYN causes the other side to try another SYN a bit later. With luck, the listen queue won't be full at that time. The program is probably not calling accept (or some similar function) often enough.
It's also possible that the program is using the sel... |
65,619,713 | 65,620,705 | In a template argument, what rules allow the compiler to infer the number of items of an array? | Given the two programs bellow -- identical except for the definition of the template function len():
// ================================
// a.cc
// ================================
#include <iostream>
template<class T, std::size_t n>
std::size_t len(T (&v)[n]) { return n; }
int main()
{
int arr[] = { 1,2,3 };
... | Template argument deduction is covered by [temp.deduct] [emphasis mine]:
/1 When a function template specialization is referenced, all of the
template arguments shall have values. The values can be explicitly
specified or, in some cases, be deduced from the use or obtained
from default template-arguments.
/2 (... rega... |
65,619,847 | 65,619,948 | Why is the output different from what I expected for a degree to radian conversion? | I'll start off with the code.
#include <iostream>
using namespace std;
//Set Default Precision
int precision = 10;
int pi = 3.14159265358979323846264338327950288419716;
int angle, degOrRad;
int angleP;
//Menu
int menu()
{
cout << endl;
cout << "--- Trigonometry Calculator ---" << endl;
cout << "Please en... | Your formula is wrong:
To convert degrees to radians, its: radians = degrees * pi / 180.
Your variables have the wrong type:
Any variables that have a decimal component (pi, angleP, probably angle as well), should be doubles or floats, not ints.
Misleading indentation
C does not use leading whitespace (like python) for... |
65,619,875 | 65,620,094 | C++ Handling error/exception that comes in multiple forms | Is there a better way to do this? I feel like this will be horrible to maintain.
const unsigned int set_max {32};
std::vector<unsigned int> base;
base.reserve(argc-1);
for (int i = 1; i < argc; ++i) {
unsigned long tmp;
try { tmp = std::stoul(argv[i], nullptr, 10); }
catch (std::invalid_argument) { std::cerr << "... | I would suggest splitting out the logic into utility functions to make each operation easier to manage, eg:
enum class eConvFailure {NoError, ConvFailed, OutOfRange, TooSmall, TooLarge};
std::pair<unsigned int, eConvFailure> my_stoui(const std::string &s)
{
unsigned long tmp;
try
{
tmp = std::stoul(s, nullp... |
65,619,933 | 65,619,980 | C++ - How am I able to call a copy constructor for std::thread? | So according to https://en.cppreference.com/w/cpp/thread/thread/thread: the copy constructor for std::thread is deleted and is the reason I cannot do (results in a compilation error):
std::thread t1;
std::thread t2 = t1;
However I am somehow able to do:
std::thread t1;
t1 = std::thread();
I was under the impression t... | The second one uses move assignment. std::thread can be moved, but not copied.
This should also work: std::thread t2 = std::move(t1); , which will leave t2 managing whatever thread t1 was managing , and t1 will be empty.
|
65,620,179 | 65,660,089 | How to perform an elementwise addition in an Eigen sparse matrix | I have the following code where AMAT is currrently a dense matrix. However most of the elements are zero such that essentially it is a sparse matrix. I understand block operations are not supported in Eigen sparse matrix. Wondering how I can rewrite this code if I replace AMAT as a sparse matrix. BMAT is a 9x9 dense ma... | This could work (untested, and I don't know the actual types of your matrices). The idea is to write a custom iterator which provides the indices and values of every entry of AMAT and pass that to setFromTriplets (duplicate entries will be summed together). This will iterate twice through your index list, but unfortuna... |
65,620,262 | 65,620,424 | Static struct initialization without designated initializers? | The following designated initializer example is valid in Visual Studio 2019 with /std:c++latest, but I'm wondering how to accomplish the same thing without designated initializers in Visual Studio 2017.
I am using C++ and I realize there is an object-oriented way to do this but I am NOT asking how to recreate this in C... |
struct Foo
{
void *(Bar)();
};
Foo::Bar is a member function that returns void*. C doesn't have member functions, so this would be ill-formed in C.
{
.Bar = Bar;
}
This is ill-formed in both languages. You may not put semicolon there. Solution: Remove the semicolon. Optionally replace with a comma.
Beside... |
65,620,758 | 65,620,954 | C++ Check if class derived from template base class; which has integral template parameters | Is there a way in which I can test that the Derived class is derived from BaseInterface where the template parameters for the BaseInterface are unsigned integral values?
I'm wanting to perform this check as part of a template std::enable_if.
The BaseInterface has a method that takes in a reference to a block of bytes, ... | It's actually easy to detect the base class template, provided that it is unambiguous and accessible, for example:
template <size_t BlockSize, size_t OutputSize>
size_t get_block_size(const BaseInterface<BlockSize, OutputSize>&) {
return BlockSize;
}
get_block_size(Derived{}); // returns 64
This is because while... |
65,620,831 | 65,620,872 | Why this statement comes to output? | I have a question about this code:
class A
{
public:
A(){cout<<"A no parameter ";}
A(string s){cout<<"A string parameter";}
A(A &a){cout<<"A object A parameter";}
};
class B:public A
{
public:
B(){cout<<"B no parameters";}
B(string s){cout<< "B strig parameter";}
B(int s){cout<<"B int para... | Your issue is that in
B(string s) /*...*/ {cout<< "B strig parameter";}
//and
B(int s) /*...*/ {cout<<"B int parameter";}
that in the /*...*/ part you have an empty member initialization list. That means the compiler will insert one for you for the base class. Because of that the constructors actually become
B(stri... |
65,620,874 | 65,620,967 | OpenGL reverse movement | I'm trying to decrease the values of 'left_eye_b' and 'left_eye_b'and then increase the values again to simulate wink on a human I made on OpenGL.
Here I created the eye:
left_eye_b=10.0;
left_eye_s=10.0;
glColor3f(1.0f, 1.0f, 0.0f);
glBegin(GL_POLYGON);
for (float i = 0; i <= (2 * p); i += 0.001) { ... | Add a variable that indicates whether the eye will be opened or closed. The value of the variable is 1.0 to open and -1.0 to close:
double eye_change = -1.0;
Change the sign of the variable when the exe has opened or closed:
void timer(int a) {
left_eye_b += 0.1 * eye_change;
left_eye_s += 0.1 * eye_change; ... |
65,621,088 | 65,621,168 | no matching function for call to Employee::Employee() error | i think that i doing something wrong when i declare the constructor in the subclass "Manager".
i didn't understand if it's an inheritance problem between the two classes.
employee.h
#ifndef EMP_IMP_H_INCLUDED
#define EMP_IMP_H_INCLUDED
#include<string>
using namespace std;
class Employee
{... | Constructor of class Manager must pass n and s arguments to the base class constructor instead of initializing base class data members directly. Also, while assigning bonus = b; in the constructor body is valid, it is better to put it in the initializer list, too:
Manager(string n,int s,int b) : Employee(n,s), bonus(b)... |
65,621,617 | 65,641,245 | Huge memory consumption during compilation when passing constexpr by const reference | Compilation of the following code with g++ consumes a surprisingly big amount of memory (over 5gb).
#include <iostream>
#define N 100000
struct A {
int tab[N];
constexpr A(): tab{} {
for (size_t i = 0; i < N; ++i) tab[i] = i;
}
};
struct B {
int tab[N];
constexpr B(const A& a): tab{} {
... | Seems to be fixed in versions 10.3 and 11.
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=96197
|
65,621,893 | 65,624,715 | Create an OpenGL 2D view camera but using model view projection cameras | I am trying to create a 2D, top down, style camera in OpenGL. I would like to stick to the convention of using model-view-projection matrices, this is so I can switch between a 3D view and a top down view while the application runs. I am actually using the glm::lookAt method to create the view matrix.
However there is ... | The vertex coordinates are in the range [-0.5, 0.5], but the orthographic projection projects the cuboid volume with the left, bottom, near point _(0, 0, 0.1) and the right, top, far point (800.0 * 2, 600.0 * 2, 100) of the viewport.
Therefore, the triangle mesh just covers one fragment in the lower left of the viewpor... |
65,623,001 | 65,623,130 | How to pass numeric operator as a parameter? | In C++, we can do something like the following,
template <class OP>
int f(OP op){
return op(1,2);
}
int main(){
int res1 = f(std::plus<int>{});
int res2 = f(std::multiplies<int>{});
}
How could I do the same thing with simple numeric operator,
int main(){
int res1 = f(+);
int res2 = f(*);
}
Exactl... |
How could I do the same thing with simple numeric operator,
You cannot; not using a function template. Operators are not something that can be passed as arguments or stored in objects.
what I want to know is how to write the line of 'return' in function f.
There is no way you can write f as a function template that... |
65,623,430 | 65,623,965 | How to make a class with 'dynamic' data types? | In the C++ standard library, there is std::vector, and you can specify the type you want to put into a vector while declaring it.
I want to create a class which would contain a vector of either strings, or ints, or whatever I would ever need. Is it possible to do this in an easy way, or would I have to write thousands ... | If you put the data type in the declaration, you can instantiate different kinds of vectors: vector<int> myint_v; vector<string> mystring_v; etc.... but I think your asking about how to make a Generic class and GeeksForGeeks has a really good article on this.
#include <iostream>
using namespace std;
template <typena... |
65,624,411 | 65,624,443 | rt_SATURATE Macro definition in Qt | Anyone knows below macro? I googled it but cant find anything useful. What does it do?
#define rt_SATURATE(sig,ll,ul) (((sig) >= (ul)) ? (ul) : (((sig) <= (ll)) ? (ll) : (sig)) )
| It does what std::clamp does.
It "returns" sig restricted to a range given by ll (lower limit) and ul (upper limit).
As the question is tagged with qt another alternative doing the same thing but with different order to the parameters is qBound
|
65,624,432 | 65,624,492 | I have entered a word in character array and want to find out the length of the word | #include<iostream>
#include<cstring>
#include<cstdlib>
#include<cmath>
using namespace std;
int main(){
char arr[100]="apple";
int i=0;
while(arr[i]!='/0'){
i++;
}
cout<<i;
return 0;
}
After running it I didn't get output. What's the mistake?
I have just started C++... | The null character is denoted by a backslash not a slash. I am guessing that in your case, you get an infinite loop. '/0' is a multicharacter literal while '\0' is the null character. In your case, the correct code will be the following :
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cmath>
using name... |
65,624,597 | 65,624,709 | Initializing C array in C++ class | I have a C++ class that contains a private C array as follows,
class DataObject {
private:
double* data_array_;
};
Due to restrictions from other parts in the program that are not shown, I can't use a std::vector<double>, can't use the DataObject constructor to initialize the array (initializer list?), and... |
I have a C++ class that contains a private C array as follows,
double* data_array_;
That is not an array. That is a pointer. As such, your class doesn't and cannot "contain" an array at all. It can only point to (element of) an array that is contained somewhere else.
If you want to point to an automatic array, th... |
65,624,632 | 65,625,037 | CRTP with dependent type, type name lookup | There are many discussion about how nested type in derived class should not be used in CRTP. However, some of the cases below actually work fine:
template <class T>
class Base {
public:
int value = T().value;
};
template <class T>
class B {
public:
// case 1: ok, as long as class C does not instantiate;
class... | When your compiler sees class D : public B<D>, it tries to instantiate B<D>. At this point, D is still an incomplete type and I is not known yet. However due to "deferred instantiation" the nested class is not instantiated until its first use. From this answer:
...instantiation of its member definitions are deferred u... |
65,624,671 | 65,624,690 | not " using namespace std; " gives me an unexpected error (C++) | This Is my first post here. I have a question about "using namespace std;". I hope I'm posting this right, but please do tell me If I did something wrong!
**Problem: ** So the problem that occurs Is that when I remove 'using namespace std;' I get an unexpected error which gives me the following error: "identifier 'to_s... | you need to use
std::to_string()
std:: means standard namespace
|
65,624,858 | 65,625,269 | How do I rotate photos in QPixmap? |
Marked a needle on the speedometer.
// 이미지 출력
QPixmap pix("C:\\Users\\WORK002\\Desktop\\speedmeter.png");
QPixmap pix2("C:\\Users\\WORK002\\Desktop\\pointer.png");
QPixmap pointer = pix2.scaled(300, 300);
scene.addPixmap(pix);
scene.addPixmap(pointer);
ui-> graphicsView ->setScene(&scene);
ui-> graphicsView ->show(... | You don't have to mess with the QPixmap, you can manipulate the QGraphicsPixmapItem returned by QGraphicsScene::addPixmap:
QGraphicsPixmapItem *pixmap_item = scene.addPixmap(pix);
To set the position, you can use QGraphicsItem::setPos.
To set the rotation, first set the transform origin point with QGraphicsItem::setT... |
65,625,052 | 65,625,139 | Return value of function when return path not specified | int foo(int i)
{
if(i != 0)
foo(i - 1);
else
return i;
}
GCC warns control reaches end of non-void function [-Wreturn-type].
Since the last return statement that set eax to 0, upon return from any other path, it returns 0. Also, compiler explorer produces the exact same code whether I wrote ret... |
Could one treat this as guaranteed behavior?
Simple answer: No. You must have the return.
Also, compiler explorer produces the exact same code...
In C and C++ you can't rely on compiler output to figure out whether you're doing something correctly. Any time you invoke undefined behavior it's possible for the compil... |
65,625,215 | 65,625,324 | I don't understand why it won't connect | int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget w;
QPushButton *trankil = new QPushButton("Clique&&Release", &w);
QVBoxLayout *layoutrkl = new QVBoxLayout;
layoutrkl->addWidget(trankil);
//trankil->move(10,10);
int resultat = 2;
QLCDNumber *lcd = new QLCDNumber(&... | If you debug it.
QObject::connect: No such slot QLCDNumber::display(resultat)
display(resultat) is not a slot function.
You can try the following:
QObject::connect(trankil, &QPushButton::clicked, lcd, [&](){
lcd->display(QString::number(resultat));
});
|
65,625,605 | 65,625,759 | c++ Inheritance same ouput | An unexpected problem occurred while studying inheritance.
I don't know why the output is the same.
specified default values for each class.
#include <iostream>
#include <string>
using namespace std;
class Drink{
private:
string kind;
public:
Drink(string k="drink")
{
kind=k;
}
void print() ... | You're replacing the values of the derived constructors' arguments.
Default values belong in the parameter list, not the initializer list.
There is also no point in a member function that just calls an inherited member function and does nothing else.
Try this:
class Coffee : public Drink {
public:
Coffee(string k="... |
65,625,911 | 65,632,924 | Qt - How can I connect a signal to a QGroupBox each time the show() function is called on it? | I have two classes that are interacting with each other, let's call them for the sake of simplicity ClassA and ClassB. In ClassA, I would like to emit a signal when a specific QGroupBox is shown that triggers a slot in ClassB to set the given channel's checkbox.
I have a code that consists of several thousand lines, so... | You will need to subclass QGroupBox to achieve the functionality you require.
Override QWidget::showEvent(QShowEvent*) in your QGroupBox subclass and do the work there.
Please see the documentation for QWidget.
|
65,625,992 | 65,626,302 | What is the difference between ios_base::sync_with_stdio(0); and ios::sync_with_stdio(0); in C++? | My mentors in CP recommended me to use ios_base::sync_with_stdio(0); since it increases the speed of program execution. While going through some videos on YouTube, I came across ios::sync_with_stdio(0); also.
So, What difference does adding or deleting _base make?
Which is better, ios_base::sync_with_stdio(0); or ios::... |
What is the difference between ios_base::sync_with_stdio(0); and ios::sync_with_stdio(0); in C++?
One takes 5 characters more _base to type. There are no other differences.
The function is defined as a static public member function in ios_base class. ios is really typedef basic_ios<char> ios; and basic_ios inherits ... |
65,626,040 | 65,626,145 | Why is the time complexity for insertion of a string into an unordered_map, constant on average? | If we have a string of length n, then shouldn't the time for inserting it into an unordered_map (C++) be O(n)? But in the cplusplus.com website:
The following is written:
So, what is the correct time complexity? Thank you!
| In this context, constant time refers to the number of elements in the map, not anything about those elements.
If you have a string of size n, and insert it into a map of size m, O(n) insertion is constant in m.
|
65,626,326 | 65,626,673 | Printing the key value pairs of a map where the key is a vector in C++ | I have a 2d vector that represents the points on a graph. I'm trying to find the Euclidean distance between these points from the origin.
Here is my code:
My idea is to map the points as a vector as a key to its Euclidean distance as a value. I was able to do it but I'm unable to print the map with key value pair. How ... | First, there is no hash function for std::vector key so you need to use std::unordered_map other way around:
std::unordered_map<double, std::vector<int>> mp;
and you could have a separate function for printing out elements of std::vector since operator<< is not overloaded for std::vector type:
template <typename T>
vo... |
65,626,606 | 65,628,919 | Esp32 read lines from text file as strings get wrong worder | I have a text file test1.txt:
aaa|aaa|aaa
bbb|bbb|bbb
ccc|ccc|ccc
ddd|ddd|ddd
File has 4 rows as you can see. I use this code to read the content of the file and get each line as a separated string:
#include "SPIFFS.h"
String file_content = "";
char VALUE [1024] = {'\0'};
void setup() {
S... | Try this:
#include <SPIFFS.h>
using namespace std;
void setup() {
Serial.begin(115200);
if (!SPIFFS.begin(true)) {
Serial.println("An Error has occurred while mounting SPIFFS");
return;
}
File file = SPIFFS.open("/test1.txt");
if (!file) {
Serial.println("Failed to open file for reading");
... |
65,626,676 | 65,626,864 | Multiplications with doubles c++ | I'm new to C++ and I wanted to code the mandelbrot set in it to get some practise and compare the speed to Python. My function to iterate to see if the complex number blows up to infinity looks like this:
int iterate(double ir, double ii, int iterations){
double sr = 0.0;
double si = 0.0;
unsigned int steps... | I would write your function like this, using std::complex:
template <class T>
std::size_t iterate(std::complex<T> c, std::size_t max_iterations) {
std::complex<T> z = 0;
std::size_t steps = 0;
while (std::norm(z) <= 4 && steps < max_iterations) {
z = z * z + c;
++steps;
}
return st... |
65,626,894 | 65,628,083 | How to read the state of "switch case" outside in the next function? | I am trying to figure it out that how to to read the state of the switch case in the ReSults function as shown in the code... The result function should read the switch state from calculation function and process it.
Code:
void CalCulation()
{
cout << "Choice: "; char UserChoice; cin>>UserChoice;
double vAdd1, ... | #include <iostream>
#include <string>
#include <limits>
using namespace std;
//Calculator
void MainMenu();
void CalCulation();
void ReSults(double , double, double , double, double , double, double , double, char);
bool isValid(string err_msg)
{
if(cin.rdstate())
{
cin.clear();
cin.ignore(numeri... |
65,627,276 | 65,627,630 | What is the difference between this two notations? | So, basically I want to know what is the difference (if there is any) between these two notations:
First example:
struct Node{
int data;
Node* next;
};
Node* head;
Second example:
struct Node{
int data;
struct Node* next;
}
struct Node* head;
I just want to know what's the difference between these two notations, and ... |
I want to know what is the difference (if there is any) between these two notations
Node is a type name of a class. It can be used only if the class has been declared. Example:
Node* ptr; // won't work without prior declaration
struct Node;
struct Node;
Node* ptr; // works because of prior declaration
struct Node i... |
65,627,398 | 65,630,900 | How to maximize application performance for ARM little.big architecture - MPI | I am writing an MPI application to speedup a math algorithm with ARM cored device. The device has a S922X CPU which integrates a quad-core ARM Cortex-A73 cpu and a two core Cortex-A53 CPU.
I am wondering, with tuning of the compiler, or selecting a different compiler, can I expect more speedup for my application?
I was... | Your problem is twofold.
First, there are cores with varying instruction sets. Most MPI implementations provide an easy solution for that by allowing you to run jobs from more than one executable. You simply need to compile the code twice with core-specific optimisations in order to produce two executable files. Let's ... |
65,627,410 | 65,628,397 | How to run vulkan example code in windows by mingw-w64? | everyone.
I begin learn vulkan sdk programing in my window laptop rencently. I download the VulkanSDK-1.2.162.0, x86_64-8.1.0-release-win32-seh-rt_v6-rev0 and glfw-3.3.2.bin.WIN64, Unzip them and set the windows path, all is done and test resualt show in cmd like this:
C:\Users\Administrator>g++ --version
g++ (x86_64-w... | Seems like you have specified library folders but not actually linked the libraries. Have you tried adding -lglfw3 -lvulkan-1 to your compile command?
|
65,627,695 | 65,628,052 | Can I capture by reference a returned value? | If a lambda captures by reference a value that will be returned along with the lambda. Does the reference holds when calling the lambda?
#include <memory>
#include <functional>
struct context_with_callback {
bool flag = false;
std::function<void()> callback;
};
std::unique_ptr<context_with_callback> make_cont... | You "can" capture an automatic variable by reference, but that won't be useful if you return the lambda because the reference will dangling as soon as the function returns.
return ctx_with_callback; // am I allowed to do that?
Technically yes, but it won't be useful.
ctx->callback(); // will this be always valid?
... |
65,627,751 | 65,628,574 | C++ performance degradation (or code must be improved ?) | I am developping a simple program that copies the same string into another one in a loop. I use Visual Studio C++ 2019 Community Edition, and the project type is "Command line".
If I run it for 3,42 seconds then the calculated number of copies per second is 130 601 397, but if I run it for 77,97 seconds then the number... | This could be caused by integer overflow. unsigned long is at least 32 bit and on on some platforms it is equal to unsigned int. unsigned long long partially alleviates the issue, but technically the loop should have some kind of defense against that, albeit it adds to the cost of loop.
There are two problems with co... |
65,628,902 | 65,629,000 | C++: Problems of file write using FILE Library when file beat process is running | I have a code for file write using FILE Library, and usually works, but I found a case where doesn't work: When the code runs concurrently with filebeat process.
I don't know this cause of the problem because my c++ project does not support debugging mode.
I am participating in an open source project developed by someo... | Your code have broken-pipe exception when you try to write a file.
This exception occurs when a c++ code try to write a log file while the filebeat software is reading the log file.
So, I recommend using this C++ code:
#include <fstream>
#include <iostream>
logFilePath = "this is path string of log file";
log = "this ... |
65,629,058 | 65,629,649 | C++ program not returning a Value (Functions) | I want to write a program, to create a function that concatenates two strings to form a single string. However, my program is not returning any value.
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
char* my_str_cat( char* s1, char* s2, char* combined ){
for(int i = 0;i<strlen(s1);i++... | This declaration
char** combined = new char*;
declares a pointer of the type char ** that points to an allocated memory for an object of the type char *.
Dereferencing this pointer in this call
my_str_cat(s1,s2,*combined);
passes an uninitialized pointer of the type char * to the function my_str_cat.
And within the f... |
65,629,552 | 65,630,729 | XISelectEvent throws X Error: BadValue (integer out of range for operation) | I'm trying to read events from X11, here's my minimal repro:
#include <X11/Xlib.h>
#include <X11/extensions/XInput2.h>
#include <dlfcn.h>
#include <stdlib.h>
#include <iostream>
#include <string.h>
int main() {
if (getenv("DISPLAY") == NULL) return 1;
void *x11 = dlopen("libX11.so.6", RTLD_GLOBAL | RTLD_LAZY)... | I feel dumb now, I forgot that the array allocated in the heap using the new keyword has garbage in it.
I had to use the
memset(xiMask->mask, 0, xiMask->mask_len);
to set all the values in the array to 0, then start setting the value of each element as needed.
Update:
We can just use less-known feature of C++ to direc... |
65,629,579 | 65,629,650 | Why this function not printing all substrings of string s? | I am trying to print all substring of string but this function not printing all substring can you explain whats wrong?
require o/p= >
a
ab
abc
b
bc
c
curr o/p=>
a
ab
abc
b
void subString(string s, int n)
{
for (int i = 0; i < n; i++) {
for (int len = 1; len <= n - i; len++) {
string str;
... | k is initialized with i (trying to use index in overall string), but the loop condition is compared to len (trying to use index in current substring). This is contradiction. Use either one index.
Use index in overall string:
for (int k = i; k < i + len; k++) {
str += s[k];
}
Use... |
65,629,944 | 65,631,161 | How to convert element of variant to std::string ( c++ ) | How to convert element of variant to std::string??
void Function(const std::string str)
{
~~
}
std::variant<std::string, int, float> a{ 32 };
i should pass element of a to Function.
i can't change argument of Function. and i don't wanna add any helper function.
i just wanna convert element of a to string.
i tried man... | You can use std::visit with some if constexprs. If the variant holds a string, no conversion required; just call Function. Otherwise use std::to_string to convert a numeric argument:
#include <iostream>
#include <string>
#include <variant>
template<class> inline constexpr bool always_false_v = false;
void Function(co... |
65,629,986 | 65,631,248 | Is there a limit on the number of values added to a boost::accumulator? | Is there a limit on how many values that can be added to a boost::accumulator? If a large number of entries were added, is there any point in which the accumulator would cease to work properly or is the internal algorithm robust enough to account for a set of values approaching infinity?
#include <iostream>
#include <b... | If your int is a 32 bit integer, you'll get a signed integer overflow at 46341 * 46341 when calculating moment<2> and your program therefore has undefined behavior.
To avoid that, cast i to the type you're using in the accumulator:
acc(static_cast<double>(i));
This will now have the same limits as a normal double. You... |
65,630,128 | 65,630,263 | C++ default behavior for arrays - shallow copies? | As the title says - I need the content of the v array not to change outside of the function.
I thought that it would not happen (because AFAIK the default behavior of arrays is to deep copy - but it looks like it is not).
#include <iostream>
using namespace std;
void testModif(int *v)
{
for (int i = 0; i < 5; i++... | First you can enlist the compilers help by declaring as
void testModif(const int *v);
I.e. as v being a non-const pointer to const int. I.e. you can e.g. increment the copy of the pointer, but not change what the pointer points to.
With that change the shown code will get errors/warnings, which at least tell you that... |
65,630,855 | 65,631,409 | Understanding the size of virtual derived class | #include <iostream>
using namespace std;
class A {
int a;
};
class B1 : virtual public A {
int b1;
};
class B2 : virtual public A {
int b2;
};
class C : public B1, public B2 {
int c;
};
int main() {
A obj1; B1 obj2; B2 obj3; C obj4;
cout << sizeof(obj1) << endl;
cout << sizeof(obj2) << endl;
cout << si... | The result may differ depending on the compiler you are using and the system architecture. For example, msvc 19.28 x64 gives this self-explanatory result (use the option /d1reportAllClassLayout to get it):
class C size(44):
+---
0 | +--- (base class B1)
0 | | {vbptr}
8 | | b1
| | <alignment member> (size=... |
65,631,513 | 65,633,379 | gmock ElementsAreArray() function not found | I am trying to call the function ElementsAreArray() inside another function. I was using it normally inside my tests, but I wanted to make the tests reports better and organize it on a function. So I created the following files:
gUnitTest_Test_Array.cpp where I have my function definition:
#include "gUnitTest_Test_Arra... | The comments above were right about arrayA and arrayB not being arrays itself. I knew it, but I thought that ElementsAreArray() would be happy receiving the address from the pointers.
It turns out, as also commented above, that it converts it to std::vectors, so the workaround I found was to create a local copy of my v... |
65,631,763 | 65,631,821 | Why isn't OpenGL drawing a rectangle? | I am currently working on a small OpenGL-Game.
I tried to make a renderer, which renders a simple rectangle, but I doesn't render anything.
I am quite sure that the shaders work, so I think the problem is in the code of the renderer.
I think the problem is in this code:
#include "Renderer.h"
#include <game/Game.h>
#in... | The mistake is in the line:
glDrawArrays(GL_VERTEX_ARRAY, 0, 6);
The first argument of glDrawArrays is the primitive type. GL_VERTEX_ARRAY is not a valid primitive type and will cause an INVALID_ENUM error. You have to draw 2 tringles with the Triangle primitive type GL_TRIANGLES:
glDrawArrays(GL_TRIANGLES, 0, 6);
|
65,632,067 | 65,632,153 | How to use overloaded operator== to check if 2d point and 3d point are identical in C++? | I would like to check wether my 2d point and 3d points are identical using operator== that returns true if they are.
How can I implement that?
Do I need to add overloaded operator into both classes or what?
How to compare 2 arguments x and y?
My code:
#include <iostream>
using namespace std;
class Point2D {
public:
... | First, you probably want public inheritance:
class Point3D : public Point2D {
// ~~~~~~~~~~~~~^
Once you have that, you can rely on polymorphism to handle things for you and only implement comparison operator for Point2D:
// the arguments should be const, but your classes are not const correct
bool operator== (/*const... |
65,632,162 | 68,925,218 | Enforce OpenSSL to pad/unpad data in stream mode encryption/decryption(like AES-CFG, AES-OFB, etc) | I'm currently writing a C++ software which have to be compatible with a legacy network service. The encryption/decryption which is used by that service is AES-128-OFB-PKCS#7(yes, it pads the data in OFB mode). Because OFB mode does not require padding OpenSSL does not apply or remove such padding which gives me the tro... | Just wanted to get back to this and notify everyone that there is no way to do that with OpenSSL directly. I've ended up manually adding/removing the padding.
|
65,632,178 | 65,632,330 | Converting code written with delay to millis() instead | I have a basic code I wrote on Arduino, however, I need to change the delay to Millis instead.
Whatever I do I can't get it to work, it's always getting stuck at a red light and won't ever turn green.
I'm posting the original delay code as code I wrote using Millis seems useless and may confuse what I'm trying to do.
c... |
Save the time when it started waiting.
If the difference of current time and the start time become the time to wait, proceed to the next status.
const int redPin = 2;
const int yellowPin = 3;
const int greenPin = 4;
int redDuration = 10000;
int greenDuration = 5000;
unsigned long startTime;
int status = 0; // using... |
65,632,736 | 65,633,041 | C++ shadowing parent constructor | Is there any harm in shadowing a parent constructor? It doesn't seem like anything is wrong, but my IDE is indicating and not warning me about it. Quick example
#include <iostream>
#include <string>
namespace NS1 {
class A {
public:
A(){std::cout<<"I am A\n";}
virtual ~A(){}
};
}
namespace NS2 {
class A... | There's nothing wrong with this code, except that it could possibly be improved by following the Rule Of Zero:
namespace NS2 {
class A : public NS1::A {
public:
// Has implicitly declared default constructor, copy constructor,
// move constructor, copy assignment, move assignment, and destructor.
};
}
In... |
65,632,744 | 65,632,887 | Variable not declared in scope and a defined function cannot be used as a function | This is how the code currently looks like.
#include <iostream>
#include <iomanip>
using namespace std;
int cos(angle)
{
float rad = angle;
float radPh = 1;
float facto = 1;
float tOld = 1;
float tNew = 0;
float tPh = 1;
float tDiff = 1;
float cosAns;
precision = precision + 1;
... | In the function definition/declaration you must mention the argument data type.
int cos(float angle, int precision)
#include <iostream>
#include <iomanip>
using namespace std;
int cos(float angle, int precision)
{
float rad = angle;
float radPh = 1;
float facto = 1;
float tOld = 1;
float tNew = 0... |
65,633,348 | 65,633,496 | How to make a comparator function inside any class just like we make in a priority_queue in c++ STL | Just like in a priority_queue in STL we can give our custom compare function like this:
class comp
{
bool operator()(int a, int b)
{
return a>b? 1:0;
}
};
priority_queue<int, vector<int>, comp> pq;
How can I do this for any class? I tried doing this to compare my person class object using class c:
... | You need to create an instance of the functor you want to compare with, and then call that instance's operator().
This:
if(comparator comp( p1, p2))
does not do that. You seem to be trying to just construct a comparator called comp in the if condition - which can't be done - and then made no effort actually to call s... |
65,633,596 | 65,724,125 | How to prevent to break line in C at the end of for loop before ; | Actually my options are : "C_Cpp.clang_format_fallbackStyle": "{ BreakBeforeBraces: Linux, IndentWidth: 4, ColumnLimit: 80, UseTab: Never, SortIncludes: false, AlignAfterOpenBracket: DontAlign }"
I have:
for (int i = 0; i < 5; i++)
;
I want:
for (int i = 0; i < 5; i++);
| This is a known issue and it make a warning. The only way is to write this:
for (int i = 0; i < 5; i++) {}
|
65,633,849 | 65,660,417 | How to open the cmd console inside Visual Studio Community for outputs while on debugger mode? | I'm recently learning how to use Visual Studio Community.
When i start the debugger, a cmd console with the output of my .cpp opens on another window, but i want it to open inside the Visual Studio as a window, like the developer powershell window.
Can anyone help me out with this one?
Thanks
| There are two methods to meet your needs.
I suggest you to download a VS extension named Open Command Line. The Open Command Line extension supports all types of consoles like cmd, PowerShell, Bash and more. You can easily configure which to use by setting the paths and arguments in the Options.
You could add the fol... |
65,633,934 | 65,634,130 | Acessing memory referenced by void pointer | I am getting my head around void pointers in C++ and as an exercise have written the following code:
void* routine(void* number){
int n = (int)number;
int* np = (int*)number;
cout<<"void pointer: "<<number<<endl;
cout<<"casted int pointer: "<<np<<endl;
cout<<"int pointer content: "<<*np<<endl;
... | The usual &num will do.
routine(&num);
Any object pointer implicitly converts to void*. On the callback function you'll have to convert it back to the correct pointer type (use static_cast not C-style cast, that will prevent you from accidentally mixing up pointers containing addresses with integer values that are no... |
65,634,118 | 65,634,930 | Eigen templated function that accepts both Matrix col and vector | I can't understand how to write templated function that accepts both vector and matrix column?
For example:
template<typename T>
void foo(
const Eigen::MatrixX<T>& M){
}
int main(){
Eigen::VectorX<double> v(3);
Eigen::MatrixX<double> m(4,3);
foo(m); // fine
foo(m.col(0)); // broken
foo(m.row(0)); // br... | I could get this to work using MatrixBase:
#include <Eigen/Dense>
template<typename T>
void foo(const Eigen::MatrixBase<T>& M){}
int main(){
Eigen::Vector3d v(3);
Eigen::Matrix<double,4,3> m(4,3);
Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> q(5,6);
foo(m);
foo(m.col(0));
foo(m.row(0))... |
65,634,265 | 65,634,617 | What to give a function that expects a raw pointer? | I'm using a library that, in order to construct some object that I use, expects a raw pointer to an object. I'm not sure what it will do with the pointer, to make my code as safe as possible, what should I pass to this function?
Use a unique pointer - if they decide to delete the pointer, I will do a double-delete
Kee... | You cannot solve this problem with the information you have. All choices produce garbage.
You have to read the documentation of the API you are using.
Doing any of your 4 answers without knowing if they take ownership of the pointer will result problems.
Life sometimes sucks.
If you have a corrupt or hostile API, the ... |
65,634,284 | 65,634,991 | Import External Symbol with Clang and WebAssembly | When compiling C(++) code that has extern function declarations to WebAssembly with Clang, it gives undefined reference errors rather than importing the symbol. What option will make the linker add those as imports to the WebAssembly module instead of trying to resolve them?
#ifdef __cplusplus
extern "C" {
#endif
... | You can use the import_module and import_name clang attributes to mark the function as imported. e.g.:
__attribute__((import_module("env"), import_name("externalFunction"))) void externalFunction(void);
Or you can pass --allow-undefined to the linker. See https://lld.llvm.org/WebAssembly.html#imports.
|
65,634,770 | 65,635,677 | Does istream::ignore discard more than n characters? | (this is possibly a duplicate of Why does std::basic_istream::ignore() extract more characters than specified?, however my specific case doesn't deal with the delim)
From cppreference, the description of istream::ignore is the following:
Extracts and discards characters from the input stream until and including delim.... | After a lot of back and forth in the comments (and reproducing the problem myself), it's clear the problem is that:
You enter p<Enter>, which isn't parsable
You try to discard exactly two characters with ignore
You output the underscores
You prompt for the next input
but in fact things seem to stop at step 2 until yo... |
65,635,084 | 65,635,114 | Why use the keyword 'const' twice in a class member function C++ | I keep running across function definitions inside classes that look like this:
//Accessor function
const string getName() const {
return name;
}
My question is: why does the word 'const' appear twice. I know the 'const' at the end of the definition helps protect the original member information, but what does the f... | The first const qualifies the returned value as non-modifiable; the second const specifies that the function does not modify the class instance (or any member of it) on which it was called.
The first is more often used when the function returns a reference to a member, to prevent that returned reference from being used... |
65,635,110 | 65,635,499 | How can one protect a register from being overwritten during a function call? | I am trying to write assembly code for the following function:
#include <iostream>
void f(int x) {
if (x > 0) {
std::cout << x << std::endl;
f(x-1);
std::cout << x << std::endl;
}
}
int main() {
f(1);
}
The output of this function script is 1 1. I try to write the assembly code for ... | Commonly, a computing platform includes an Application Binary Interface (ABI) that specifies, among other things, protocols for function calls. The ABI specifies that certain processor registers are used for passing arguments or return results, certain registers may be freely used by the called routine (scratch or vola... |
65,635,258 | 65,635,893 | difficulty configuring Bazel target includes and deps | I'm trying to add some Bazel rules for building pre-processed data for build releases of the ICU library. Currently, I have a very basic set of BUILD files (still work-in-progress) to help complete the gennorm2 target.
icu4c/source/common/BUILD looks something like:
cc_library(
name = "headers",
hdrs = glob([
... | includes is relative to the package (folder where the BUILD file is). You want includes = ["."] here.
If there are header files at icu4c/source/*.h, you will need to create a icu4c/source/BUILD with a cc_library for them.
Also, for debugging, bazelisk build //icu4c/source/tools/gennorm2 --verbose_failures --sandbox_deb... |
65,635,538 | 65,635,717 | How to find the frequency of digits in a number using a switch statement? | For my college intro to computer science class we must write a program which outputs frequency of digits in a given integer. For example, if the number is 124243294 the output is:
Number Frequency
1 1
2 3
3 1
4 2
9 1
You must use the switch statement to obtain the frequency of the digits.
| You could do something like this:
int number;
std::cin >> number;
std::string s = std::to_string(number);
int freq[10] = {};
for(char ch : s)
{
switch (ch)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
... |
65,635,581 | 65,635,762 | Why is the pipe operator not working when I use ranges in C++20? | I am currently working through examples from the book Expert C++.
In chapter 7, they offer the following code for mapping a function to a matrix:
#include <vector>
#include <ranges>
#include <iostream>
using IntMatrix = std::vector<std::vector<int>>;
int count_evens(const std::vector<int>& number_line) {
return s... | std::vector<int> count_all_evens(const IntMatrix& numbers)
{
auto view = numbers | std::ranges::views::transform(count_evens);
return {view.begin(), view.end()};
}
there is a proposal to make this suck less.
std::vector<int> count_all_evens(const IntMatrix& numbers)
{
auto view = numbers | std::ranges::views::tr... |
65,635,619 | 65,636,194 | How to use Caffe library in C++ project with CMakeLists.txt | I'm trying to use Caffe in my C++ project which I compile with CMakeLists.txt, but it doesn't want to work. My only line in the code is
#include <caffe/caffe.hpp>
I compiled Caffe myself, it is installed in the directory "/home/tamas/caffe". My CMakeLists.txt looks like this so far:
cmake_minimum_required (VERSION 3.5... | To fix this issue you may do the following:
Download this FindCAFFE.cmake file
Create cmake dir in your repo root directory and put the downloaded file there.
Modify your CMake file:
add set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${PROJECT_SOURCE_DIR}/cmake")
change set (Caffe_DIR "/home/tamas/caffe") to set (CAFFE_... |
65,635,810 | 65,636,220 | Proper way to use predicate in conditional variable | I want to know if I need to reset the predicate boolean variable inside the scope of the locked mutex. Right now, I have a std::unique_lock with a lambda function as the predicate parameter - The lambda function returns a boolean flag. Does this mean I need to set the boolean flag back to false inside the scope of the ... | Firstly, the Reader never acquires a lock to synchronize its access to the shared data (in this case the processed boolean and the data variable, whatever it is) with the Worker. As such, the Reader can modify processed while the Worker is reading from it, and the Reader can read from data while the Worker is writing t... |
65,635,842 | 65,637,746 | Correct way to draw a QGraphicsItem on QGraphicsScene | I checked a couple of resources on qt's website and here but I could not solve my problem.
I'm trying to draw a rectangle on QGraphicsScene on mouse click and I want the new rectangle to be centered exactly where the user clicked but this does not work until the scene is big enough.
Here's what I tried
In MainWindow.cp... | You are combining the boundingRect coordinates that are relative to the item with the coordinates relative to the scene. On the other hand, don't complicate creating a custom item, instead use a custom QGraphicsRectItem. Finally it is recommended that you establish a sceneRect.
component.h
#ifndef COMPONENT_H
#define C... |
65,636,064 | 65,645,585 | What is the crux of std::reference_wrapper implementation for the only purpose of makin std::ref work? | The example on the page of std::ref/std::cref shows the use of std::ref/std::cref to pass arguments to std::bind in a way that looks like std::bind is taking arguments by reference, when in reality it takes the all by value.
Looking at that example only, I could also be ignorant about the existence of std::reference_wr... | The logic that you're talking about is implemented entirely within std::bind itself. The main functionality it needs from std::reference_wrapper is the fact that it can be "unwrapped" (i.e., you can call .get() on it in order to retrieve the underlying reference). When the call wrapper (i.e. object returned from std::b... |
65,636,503 | 65,636,626 | Using the template only if the method exits | Can someone help me complete this code if a indexed container(map,set) calls tool::exists_in and has the find metod it will call the first method. if not, call the second method.
namespace tools {
template<class TSource, class Ty>
auto exists_in(const TSource &source, const Ty &item)
->decltype(source->... | To begin, first function should be
template<class TSource, class Ty>
auto exists_in(const TSource &source, const Ty &item)
-> decltype(source.find() != source.end())
// ^^^^^^^^^^^^^^^^
{
return source.find() != source.end();
}
to have correct return type.
Then you might use some "priority" ... |
65,636,928 | 65,637,054 | Functions should be correct, but why is the final output 0 here? | #include <iostream>
#include <iomanip>
using namespace std;
//Power function
float power (float base, int exp)
{
if (exp < 0)
{
if (base == 0)
{
cout << "Base cannot be 0.";
return -1;
}
}
if (exp == 0)
return 1;
if (exp == 1... | Your cosin and sine function return a float, but in order to get that result you still have to store it in a variable.
So instead of:
cosCalc (rad);
Do:
rad = cosCalc (rad);
and the same for your sine function.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.