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 |
|---|---|---|---|---|
64,019,793 | 64,019,834 | Really weird if statement behavior in C++ | Only the first statement is printed even though both if expressions should evaluate the same. Why?
map <int, int> elem;
vector <int> nums(2);
int x = 1;
elem[x]=-1;
int val = elem[x];
if(val>nums.size()/3) {cout << "First";} // as you can see, vals is -1 and nums.size() is 2
i... | They are not the same.
if(val > nums.size() / 3) {
The problem is that num.size() has type of size_t which is unsigned. When you compare signed to unsigned type, you get undefined behaviour.
If you really want to make it the same, then you need to do a cast:
if (val > static_cast<int>(nums.size()) / 3)
now it would b... |
64,019,911 | 64,019,974 | What are the key differences between a generic lambda, a template function and a template member operator() during argument deduction? | I am confused about the following differences when using with algorithms.
First of all, algorithms work with lambda, functions and functors without any issue. For example,
bool comp (int t1, int t2) {
return t1 > t2;
}
std::array<int, 10> myArray{5, -10, 3, 2, 7, 8, 9, -4, 3, 4};
std::sort(myArray.begin(), myArray.... | A template is a language construct of C++ which generates other constructs: classes, functions, or variables (in C++14). The name of a template, without its template parameters, can only be used in very limited ways.
comp1 names a template, not a function. That's the important point. A function template is a construct ... |
64,020,177 | 64,032,677 | clang::ast_matchers::thisPointerType ambiguous call to overloaded function | I am working on a project involving Clang AST matchers. This is one such AST matcher that I'm having.
StatementMatcher getNumUses_matcher1 = binaryOperator(
hasOperatorName(">"),
hasLHS(ignoringParenImpCasts(
cxxMemberCallExpr(
thisPointerType(hasDeclaration(cxxRecordDecl(isSameOrDerivedFrom... | I'm not sure why clang-query accepts the AST matcher above, while both clang++ and Microsoft Visual Studio cl compiler mark it as a syntax error. I found a solution though.
I restructured my AST matcher. I used a slightly different syntax for it. Now this one compiles, and also clang-query accepts it, generating the sa... |
64,020,800 | 64,021,265 | Getline always ignoring first word of input c++ | I'm having trouble with this code. I want it to take 2 words and it's always ignoring the first word and then taking the 2nd word. If I put in 3 words, it works perfectly and picks up the final 2 words.
The prompt for this is these bullet points.
Prompt the user to enter his/her first and last name.
Read the name from... | cin >> fullName;
reads the first word of the full name.
getline(cin, fullName);
reads the rest of the name over top of the first word. Computer programs do exactly what you tell them to do and show somewhat less than zero mercy if that's the wrong thing to do.
So given John Jacob Jingleheimer Schmidt
cin >> fullName;... |
64,021,115 | 64,021,148 | How to use C++ regex to find characters between square brackets | I have a C++ regex to search for characters inside square brackets, for instance if the string is x[7:0], I want to return 7:0. This is what my regex looks like -
std::regex reg("\[(.*?)\]");
When I compile (g++) I get the following warning -
../fixedPointFormatter.cc:30:18: warning: unknown escape sequence: ']'
std::... | The regex needs the [ and the ] to be escaped using \. However, to provide that to the regex, you need to escape the \s in the string.
std::regex reg("\\[(.*?)\\]");
|
64,021,156 | 64,021,186 | How to make a list of stacks in C++? | I'm trying to make a list of stacks in C++ using the code below , but I'm getting the error
main.cpp:17:13: error: ‘__gnu_cxx::__alloc_traits > >::value_type {aka class std::stack}’ has no member named ‘push_back’
vs[i-1].push_back(s);
Code:
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<stack<int... | you can't use this line:-
vs[i-1].push_back(s);
Either define the size of the list earlier.
For Eg
vector<stack<int> > vs(100);
else only write
vs.push_back(s);
Updated Solution
#include <iostream>
#include<stack>
#include<vector>
using namespace std;
int main()
{
vector< stack<int> > vs;
for(int i=1; i<4; i... |
64,021,292 | 64,021,501 | How can I replace every alphabetical lower case letter in a string with its opposite alphabetical lower case letter in C++? | I would like to find the opposite letter using for loop. Also, I would like to note that I am trying to find the opposite letter. For example, replacing "a" with "z", "b" with "y"...
For example, the user inputs this: "3 feg", and the output from this program will be: "uvt". Also, my constraint is 1<=n<=100. The input ... | Here is one solution using ASCII arithmetic:
string s = "abc";
for(int i = 0; i < s.length(); i++){
s[i] = 219 - s[i];
}
cout << s; // "zyx"
The reason it works is that all ASCII characters are between 0 and 127, and this way the values loop back around
|
64,021,641 | 64,027,834 | Trying to decipher from a file using RSA on C++ with GMP yields unpredictable results | I'm trying to implement the RSA algorithm with the GMP library. When I try to decipher a ciphered value read from a file, the end result is a value several times greater than the original cipher text.
Here's the problematic part of my code:
void cipher_file(mpz_t E, mpz_t N, string Filename){
// getting the file c... | Your N does not have two distinct prime factors:
4648032597737790824232209858880409 = 68176481265446597^2
This means you have chosen p = q. Besides the obvious security issues (n can be easily factorized by taking the square root), this will cause problems when computing the Carmichael totient function of N (reference... |
64,021,938 | 64,022,037 | Implicitly converting an object of one class to another | I have the following working example, where I am passing an object of type Derived to a constructor that expects an object of type Bridge:
#include <iostream>
class Base {
public:
Base() {};
virtual Base* clone() const = 0;
virtual ~Base() {};
};
class Derived : public Base {
public:
Derived() {};
... | Almost.
Test expects Bridge and there is a Bridge constructor which accepts Base and Derived publically inherits from Base. So a temporary object of type Bridge is created using d and this is used to construct t.
But this happens in main not in the Test constructor. Further this temporary object is destroyed at the end... |
64,022,232 | 64,203,114 | Cannot apply tensorflow model in OpenCV | Hello I have problem with applying tensorflow model in OpenCV. The code below properly load model, but when calling forward method Assertion error is thrown. Do you have any ideas where is the problem? Or how to debug/find it?
cv::dnn::Net net;
string path;
path = "graph.pb";
net = cv::dnn::readNetFromTensorflow(path);... | I have to admit that I didn't try the posted minimal code. It was part of a little bigger code. The minimal code works also on my machine. Knowing that I found out that I was calling the forward method on uninitialized network which caused the error. I initialized local net variable in init method in a class instead of... |
64,022,609 | 64,022,854 | Is there a way to make selecting a specific variable more efficient? | So I'm writing a program that has 9 different mazes in it stored in 2d arrays all filled with hard coded values. When the player chooses the maze, I want to copy the hard coded values from the maze selected into the 2d array of the active maze. When I wrote it out I did it in the most straightforward way possible as yo... | So your question is lacking in detail, but lets assume you have this
int maze[11][11], maze1[11][11]; // etc
Then the first thing to say is that
maze[11][11] = maze1[11][11];
does not copy your maze. It's a very common beginner misunderstanding that you can refer to a whole array this way, but maze1[11][11] just refe... |
64,023,075 | 64,023,228 | How to make any integer positive in c++? | I take 2 values a and b from user and perform a-b but if the answer of the user is -ve then i want to convert it into postive.
int main(int argc, char const *argv[])
{
int a,b;
cin>>a>>b;
cout<<(a-b);
return 0;
}
How to do that ?
| There are multiple ways to return only positive integers. The easiest way is to use std::abs
cout << std::abs(a-b) << "\n";
|
64,023,098 | 64,023,356 | Meaning of adding 1 on socket file descriptor in select function when using linux socket | What is the meaning of adding 1 on socket file descriptor when using in select function?
I create socket file descriptor like below,
int sock_file_descriptor;
sock_file_descriptor = socket(AF_INET, SOCK_DGRAM, 0);
and use it in select function like below,
result = select(sock_file_descriptor+1, &readfd, NULL, NULL, 0)... | RTFM! The first parameter of select is the number of file descriptors to considere:
The nfds argument specifies the range of descriptors to be tested. The first nfds descriptors shall be checked in each set; that is, the descriptors from zero through nfds-1 in the descriptor sets shall be examined.
Here is an example... |
64,023,321 | 64,023,878 | Mandelbrot's algorithm not giving the desired result without using complex numbers | when i use the following algorithm for using the mandelbrot algorithm i get the a image similar to the image i want but it looks more like an outline of the final image and when i use the algorithm with complex numbers it gives a proper sharp image
the code is written in c++
//pseudocode
//z=x+yi //x=0,y=0
//c=x0+y... | The problem is that you're not calculating both new values from the old values.
Here,
x = x2 + x0 - y2; y = 2 * x * y + y0;
you're using the new x for the new y.
You need a couple of variables for temporary storage of the updated values.
double new_x = x2 - y2 + x0;
double new_y = 2 * x * y + y0;
x = new_x... |
64,023,350 | 64,793,325 | gcovr/SonarQube saying simple C++ function is only half covered | We are running gcovr on our codebase which is (FTR) then fed into SonarQube (cxx-plugin). There are many places where there is a report of less than 100% coverage, even though there are no obvious branches so it should be surely 0 or 100%. Take for example the following:
std::string quote(const std::string& str, const ... | I did write an earlier comment that it is perhaps sonarqube but I've had another look:)
I think your comments about the possible values is flawed because these are standard C++ strings (not C ones) so effectively can't be NULL as such. However there is a possible OOM exception on the add - you are probably right that t... |
64,023,653 | 64,024,091 | C++ std::atomic for user defined data types | I am unable to understand and write up a code related to below Atomic Library functionality for user defined data type:
std::atomic::compare_exchange_weak,
std::atomic::compare_exchange_strong
bool compare_exchange_weak( T& expected, T desired,
std::memory_order success,
... | Your class has no data, hence there is no need to use std::atomic<A>. If you want to know how to use std::atomic with UDT, You may add a member data and then use the following code
#include <iostream>
#include <atomic>
class A
{
public:
int a;
void Show()
{
std::cout << a << "\n";
}
};
int mai... |
64,023,902 | 64,024,013 | attempt to reference a deleted function _ gmock | I'm working for the first time with GMock, I'm mocking a class with pure virtual methods,
I created an instance from the Mock class
MockInterface mockIntr;
Then I need to pass this mock as a parameter to another function
func->action(std::make_shared<MockInterface>(mockIntr);
in this case I got the error :
"C2280 : M... | You're not passing that mock, you're trying to copy it and pass the copy.
(make_shared<T>(x) means "create a new T from x that we can share", not "let's share x".)
Create a shared object immediately:
auto mockIntr = std::make_shared<MockInterface>();
func->action(mockIntr);
|
64,024,106 | 64,027,034 | If a lambda function is used in one place but multiple times, should it be made local or global | The criteria to delete an element from the vector is defined as a lambda function as its not used anywhere else. Now if delete_data is executed periodically, it must be creating new instances of lambda every time. How can we make its performance better:
Instead of defining criteria as lambda, defining it as inline fun... | Your first two options are not correct, and the last option is not necessary. let us analyze them step by step.
Instead of defining criteria as lambda, defining it as inline function outside the delete_data().
The third parameter of find_if is required to be a callable object which has only one parameter that accepts... |
64,025,287 | 64,025,447 | Pass Interface object to constructor c++? | Say i have an interace like
#include<iostream>
struct Interface
{
virtual void fun() = 0;
};
struct IType : Interface
{
void fun() override
{
std::cout<<"non const fun()";
}
};
class Type
{
private:
Interface &intr; // I can't declare intr as const i need to ascess non const fun()
public:
... | Reference as class member is rarely a good idea. You need an object, passed from the outside, that will outlive your class object. You cannot use default argument and you cannot use a temporary for initialization. Typically, if you need to pass different types that inherit from an interface, this is solved with (smart)... |
64,025,304 | 64,025,591 | Arduino CSS RGB hex color parsing in C++ | I'm using ESP8266 to run my smart room over MQTT.
I'm struggling with converting a string to separated RGB integer values.
The string I get looks like this: #953f4f
I've already tried toInt(), atoi(), atol(), casting, etc.
Here is the code:
mqtt.subscribe("light/rgb", [] (const String &payload) {
char msg[p... | If Arduino has strtol then you can do it like this:
mqtt.subscribe("light/rgb", [] (const String &payload) {
if (payload.length() != 7) {
Serial.printf("invalid payload: '%s'\n", payload.c_str());
return;
}
long rgb = strtol(payload.c_str() + 1, 0, 16); // parse as Hex, skipping the leading ... |
64,025,657 | 64,025,982 | storing 0 in a unsigned char array | I have a unsigned char array like this:
unsigned char myArr[] = {100, 128, 0, 32, 2, 9};
I am using reinterpret_cast to covert it to const char* as I have to pass a const char* to a method. This information is then sent over grpc and the other application (erlang based recieves it and stores it in a erlang Bin). But ... |
What could be causing this? Is it the 0 in the character array that is the problem here?
Most likely, yes.
Probably one of the functions that the pointer is passed to is specified to accept an argument which points to a null terminated string. Your array happens to incidentally be null terminated by containing null c... |
64,026,618 | 64,026,908 | using Gmock to call a member function | This is the first time I'm working with gmock and have this exemple of Mock class
class MockInterface : public ExpInterface
{
public:
MockInterface() : ExpInterface()
{
ON_CALL(*this, func(testing::_)).WillByDefault(testing::Invoke([this]() {
// I need to fill the testVec with the vector pa... | You can use SaveArg action instead:
ON_CALL(*this, func(::testing::_)).WillByDefault(
::testing::DoAll(
::testing::SaveArg<0>(&_testVec),
::testing::Return(false)));
If you want to call a member function, you can use a lambda or pointer-to-member syntax.
ON_CALL(*this, func(::testing::_)).WillByDef... |
64,026,865 | 64,028,827 | How can i find the coordinates that i used to draw the pixels on screen and return them on mouse click | sorry for the bad phrasing of the question, i don't know what i'm talking about..
i'm making a project for my graphics class and i'm kinda stuck with an issue.
#include <GL/glut.h>
#include <iostream>
void display();
void init();
void reshape(int, int);
void mouseFunc(int, int, int, int);
const int XMAX = 600;
... | Compute the normalized device space coordinate of the mouse in range [-1, 1]:
double ndc_x = (double)mouse_x / XMAX * 2.0 - 1.0;
double ndc_y = 1.0 - (double)mouse_y / YMAX * 2.0;
Map the result to the range to the grid range:
int x = (int)(ndc_x * GRID_SIZE + GRID_SIZE + 0.5) - GRID_SIZE;
int y = (int)(ndc_y * GRID_S... |
64,027,284 | 64,052,713 | How to select base token in CreateRestrictedToken to sandbox SYSTEM level services | I am trying to sandbox SYSTEM level Win service in C++. In order to create the sandbox process, we first need to create a restricted token through CreateRestrictedToken which is then passed through CreateProcessAsUser.
CreateRestrictedToken needs a token of an existing process in input. At present, I was using the toke... |
its not recommended to use SYSTEM level token as base token.
for be more exactly its not recommended to use token with AuthenticationId == SYSTEM_LUID
(SYSTEM_LUID defined in winnt.h and ntifs.h as { 0x3e7, 0x0 } )
for get token with another (not 0x3e7 = 999) AuthenticationId you can simply call
LogonUserW(L"*", L"*"... |
64,027,380 | 64,027,499 | Overload operator* without allocating new memory | I have class foo that manages a vector of floats of fixed length and some metadata. I have implemented a naive overload for operator*:
constexpr int numOfElements = 9;
class foo {
public:
foo()
: x(0), y(0), data(numOfElements)
{}
foo operator*(float value) {
foo result;
for (size_t... | Write a operator*= that multiplies the elements in place:
foo& operator*=(float value) {
for (size_t k = 0; k < this->data.size(); ++k)
this->data[k] *= value;
return *this;
}
If later you realize that you do need also operator* you can implement it in terms of operator*=:
foo operator*(float value) co... |
64,027,533 | 64,027,619 | std::this_thread::sleep_for() vs sleep() in main() | std::this_thread::sleep_for() Or usleep()
What would be better to be used in main()? This may be very silly but i am new to C++11 features.
| The former is actually a portable C++ function. The latter is an obsolete, non-portable POSIX function (replaced by nanosleep, which remains non-portable). Use std::this_thread::sleep_for(), which will likely be implemented in terms of nanosleep when available/appropriate, or whatever other function the system provides... |
64,027,710 | 64,028,029 | error: expected unqualified-id before 'switch' | I'm making a code where the users input date, month, year and the program can identify if its a leap year or not but i ran into trouble with the error saying "expected unqualified-id before 'switch' ". What is happening with my code? I can't figure out the issue. this is the line im having problems with "switch(Month)"... | A switch statement can't be in the global scope. You need to put it inside a function, like the main() function. Right after cin >> Year; seems to be the correct place for it.
Also, the range comparisons you do are not valid C++:
case 1:
if (Day == 1 ... 31) // ERROR
cout << "January... |
64,027,843 | 64,027,978 | By changing the value from int to float the total value gets changed Can anyone explain why? plz | I have tried several to identify why, but I could not do so, so if anyone get identified please let me know..
#include <stdio.h>
int main()
{
int i,n=1;
float div=0,sum=0,j=1;
for(i=1;i<=7;i++)
{
j=1;
for(n=1;n<=i;n++)
{
j=j*n;
}
div=i/j+div;
}
... | It makes a difference here:
div=i/j+div;
When the / operator is evaluated in the second piece of code, both operands have type int so integer division is performed which truncates any fractional part. When j is declared as type double, floating point division is performed and no truncation occurs.
|
64,028,803 | 64,029,017 | Bound member-function pointer | I was wondering why there is no concept like "bound member-function pointer", i.e. a member function pointer that is bound to a specific object and can therefore can be treated like a normal function pointer, e.g.
#include <functional>
struct Foo {
void foo() {}
};
void foo() {}
void call(void(*)()) {}
templat... | Yes. Use lambda's
class Foo {
public:
void Bar() const {}
};
#include <functional>
void Baz(std::function<void()> const& fun) {
fun();
}
int main() {
Foo foo;
std::function<void()> fooBar = [&foo]() { foo.Bar(); };
Baz(fooBar);
}
edit: more reading here
edit 2: using std::bind for this has ma... |
64,028,942 | 64,029,271 | Why can I not access this array whilst implementing an initializer list constructor for a Matrix class? | I'm working with an old code base that implements a matrix. I'm trying to add a method to enable construction from an initializer list. I'm quite confused because this was working yesterday. I'm not sure what I've changed by this code crashes and burns when it gets to _Array[row * col + col] = r.begin()[col];. Why can ... | You initialize everything to an invalid state
_Array = nullptr
_Rows = matrix.size();
_Cols = (*matrix.begin()).size();
This is incorrect because your code assumes that _Rows and _Cols are accurate metadata about _Array.
You then ask resize to do nothing
resize(_Rows, _Cols);
void resize(unsigned int rows, unsigned i... |
64,029,445 | 64,030,013 | How can I restrict lambda signatures in C++17 template arguments? | Suppose I have two functions that receive different lambda types as arguments:
template<typename F>
void func1(F&& lambda) {
// lambda must be [](unsigned int) -> short
}
template<typename F>
void func2(F&& lambda) {
// lambda must be [](const vector<string>&) -> void
}
How can I restrict these lambda signatu... | A way that immediately pops to mind is to leverage std::function and its deduction guides. Using CTAD, the signature can be deduced automatically for certain types of functors (non-generic lambdas among them). It will look like this
template<typename F>
auto func1(F&& lambda)
-> std::enable_if_t<std::is_same_v<declt... |
64,029,553 | 64,029,673 | Does the C++ Standard specify that every thread has its own stack? | From this question I learned that each thread has its own stack (which makes sense to me). To my understanding, each thread needs to store the "process-pointer", as well as for example some variables like the return adress, or when passing parameters.
I'd however like to know wether this implementation of the c++ codes... | The standard does not specify the existence of anything as low-level as a "stack" (though it does have a concept named "stack unwinding", so there's a clear expectation of how some things get implemented).
What the standard does is specify the behavior of functions. When you call one function, it specifies that the loc... |
64,030,141 | 64,030,301 | Store entered values in an array in cpp | Sry for asking such a "dumb" question, but for some reason my solutions does not work.
I simply want to write a code where the user enters a positive integer n. Afterwards the user must enter n random integers numbers that are stored in a vector.
My solution:
#include <iostream>
#include <vector>
int main()
{
i... | With the following initialization
std::vector<int> vec(n);
you are declaring a vector with a size from [0..n]
with this
for(int i = 0; i<n; i++)
{
std::cin>>m;
vec.push_back(m);
}
it will allocate more space to the end of the vector and what you will have is [0..n+n]
to solve this change that loop to
for(int ... |
64,030,177 | 64,036,518 | ASIO proper handling of multiple threads + strand + socket + timer | I'm using the latest ASIO version(as of this time 1.18.0). Currently designing a multithreaded asynchronous TCP server with timers(for timeouts). I have a single io_context with multiple threads calling its run() function. I accept new connections like this:
void Server::AcceptConnection()
{
acceptor_.async_accept(... | Yes, this is the way I write the things as well, using the new interfaces.
I remember having the same concerns when I started out using the new interface, and ended up checking that the various completion handlers do run on the expected strand, which they do.
All in all, these result in significant simplifications in l... |
64,030,408 | 64,030,457 | Basic dynamic memory allocation and delete triggers an asssertion failed | I am doing some reviewing of the basics of C++, and I have some troubles understanding why my code is triggering an assertion failed.
void fonctionPointeur(int a)
{
int* p = new int;
p = &a;
std::cout << p << "----" << *p << std::endl;
delete p;
}
int main()
{
std::cout << "Hello World!" << st... | In this expression
int* p = new int;
you are assigning to p a memory block allocated by new.
In this expression
p = &a;
you are assigning to p the address of mere temporary, a copy of the original variable a (as you pass it by copy in fonctionPointeur), that temporary cannot be deleted.
This is to be specific, even ... |
64,031,193 | 64,031,257 | Strange behaviour of m.erase() function in c++? | int main(){
map<int, int> m;
m.insert({1,2});
m.insert({2,3});
m.insert({5,10});
m.erase(m.find(3));
for(auto &x: m){
cout<<x.first<<" "<<x.second<<nl;
}
}
Output:
1 2
5 10
As far as I know m.find(3) returns iterator to the m.end() if key is not found. Then why pair {2,3} is delete... | The pair is deleted because you violated a pre-condition of std::map::erase
iterator erase( const_iterator pos );
iterator erase( iterator pos );
The iterator pos must be valid and dereferenceable. Thus the end()
iterator (which is valid, but is not dereferenceable) cannot be used
as a value for pos.
Violating a pre... |
64,031,477 | 64,031,520 | Non-template container iterators | Let's suppose we have a class Container without a template, and the functions begin() and end(), witch returns a class Container_iterator. The Container class has a map in it:
class Container
{
Container_iterator begin();
Container_iterator end();
};
class Container_iterator
{
Container operator*();
}
Now,... | You can just make Container_iterator a nested type member of Container, and it'll work:
class Container
{
class Container_iterator
{
Container operator*();
};
Container_iterator begin();
Container_iterator end();
};
Also, it seems odd that an iterator would return a Container instead of an element of t... |
64,031,647 | 64,031,789 | Why can I not access private members when overloading c++ | The following is some class declarations for a point and vector
#ifndef VECTOR_H
#define VECTOR_H
class Point {
private:
float x;
float y;
public:
Point();
Point(float x, float y);
float get_x() const;
float get_y() const;
void set_x(float x);
vo... | If you want to enable derivatives to get access to private members of the base class, you can make them protected.
UPDATE: But beware, you are using private inheritance, when subclassing the Point with the Vec. If you really want to use Point's public functions as interface, you should use public inheritance. Otherwise... |
64,032,383 | 64,032,807 | Cannot create FisherFaceRecognizer with OpenCV 4 (C++) | I'm following an older tutorial on face recognition based on OpenCV in C++ and have an error I can't resolve. The relevant code snippet:
#include "opencv2/core/core.hpp"
#include "opencv2/face.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/objdetect/objdetect.hpp"
.... | According to the official document,
Ptr<FaceRecognizer> createFisherFaceRecognizer(int num_components=0, double threshold=DBL_MAX)
is used openCV2. Since you use openCV 4, you have to follow the documentation that works with openCV 4.
Try this:
static Ptr<FisherFaceRecognizer> cv::face::FisherFaceRecognizer::create (i... |
64,032,399 | 64,032,839 | C++ Vector in Heap Memory results in Segmentation Fault | I am new to C++, and I'm sure this question must be easy to handle but I think I miss some main concepts. In the code, a Binary Tree is implemented, and we are asked to determine the number of nodes in that Binary Tree. As you can see in Node class, a Node has two member pointers: left that points to the Node at left, ... | The problem with your Node class is that it doesn't follow the rule of 3/5/0 and whenever you make a copy of a Node, and you are making a lot of copies, you have a trouble, because the left right nodes will be deleted once the copied object goes out of scope, and then again when you call delete yourself.
Short summary ... |
64,032,506 | 64,032,844 | Extract characters from special input | In an exercise the input is given in the following format:
{a, b, a, d, e} // some random example
The input starts with the character { and ends with }.
I want to refer to each small English letter in the standard way "x = above_input, x[0] = a, x[1] = b,...,x[4] = e".
Is there an efficient way to this?
For example i ... | Use a good old for loop to recognise the characters you want and put them in a string instead of vector:
#include <iostream>
#include <string>
int main() {
std::string ip;
std::getline(std::cin, ip);
std::string str;
for (const char& character : ip) {
if (character >= 'a' && character <= 'z') {... |
64,032,582 | 64,033,117 | How to do a partial prefix search in c++? | I'm trying to create a Phonebook program that I can search through with a partial prefix. The program goes through a .txt file and asks the user who they want to search for. Example of .txt file:
Captain-Crunch 123-456-7890
Silly-Goose 234-456-7891
Some-Dude 890-234-5679
etc
I want to be able to search 'S' and it will... | Right now, you're searching for name.find(search) != string::npos which means "is name in search".
According to this site string::find "returns the position of the first character of the found substring or npos if no such substring is found". What does that mean? Basicly it returns the offset of the substring in the st... |
64,032,633 | 64,032,876 | Replacement-List Macro Function [Question] | Replacement-List Macro Function
I'm attempting to create a quick macro which will allow me to simply get a class pointer and name the setup module based from the class pointer name like so:
#define dll_import(...) dll_module->__VA_ARGS__= \
GetModuleHandleW(L#__VA_ARGS__.dll) // Note: This is where I'm confused.
Whe... | It looks like you're trying to simply concatenate strings together. If that's the case, the solution should just be to make sure that the .dll portion is a string literal as well:
#define dll_import(...) dll_module->__VA_ARGS__= \
GetModuleHandleW(L#__VA_ARGS__ L".dll")
This would convert an input of dll_import(ve... |
64,032,828 | 64,038,137 | Snooping on pseudo terminal | I want to write a program that can capture the input/output of a pseudo terminal without it affecting the original terminal. It can be likened to pointing script to a /dev/pts/<n>.
Use Case: A user ssh's into my machine and runs an interactive tool. With audit, I can see commands running but I need to see the output al... | That's solvable by using ptrace(2) on the ssh server process which handles to master end of the pseudo-terminal (which is usually the parent process of the shell running in the terminal).
You can start with strace which is itself using ptrace(2), e.g.
strace -p <pid> -e trace=read,write \
-e read=<fds opened to /dev/... |
64,032,985 | 64,033,255 | What is the cross-platform way to handle compound literals in C++? | What is the way to use compound literals in C++ in a cross-platform way? I know it's an extension and not 'official' C++, but there must be a way, right?
My struct is:
struct v2 {
int x, y;
};
I want to:
change all struct values in one go when a struct is already initialised.
create an object inline, so I can pa... | Regardless if v2 is defined like this (with all public member variables):
struct v2 {
int x, y;
};
or like this (with a converting constructor):
class v2 {
public:
v2(int X, int Y) : x(X), y(Y) {}
private:
int x, y;
};
... you can use it like this if you use C++11 or later (clang++ -std=c++11 ...):
vo... |
64,033,399 | 64,033,669 | C++ prints "once *some number* is *another number* " multiple times while I don't print anything in the code (I need an answer in next half an hour) | I try to fill two-dimensional array with random values:
for(int i = 0; i < size; i++)
{
for(int j = 0; j < size; j++)
{
int temp = rand();
*(array + i * size + j) = &temp;
}
}
The size variable is set earlier in the code. Array initialization:
int** array = new int * [5];
for(int i = 0; i ... | Ahah, pointers :D
For arrays, you can use the [] operator to access an element by it's index.
That would change your:
int temp = rand();
*(array + i * size + j) = &temp;
into (note that the two have the exact same effect):
int temp = rand();
array[i * size + j] = &temp;
Which is way cleaner! But also false. Right now... |
64,033,464 | 64,073,218 | How to produce codes that always trigger signal SIGFPE(div by zero)? | I need to code a unit-test that should always trigger a divied by zero signal(SIGFPE), so I can test and compare what would happen with/without my signal catching module.
My Linux signal catching/resuming module has been developed, and worked as expecting.
When I'm coding the unit-test for the module, I encounter a sma... | I think that ChrisDodd's answer is the most precise one.
I.e. the return value of do_div_by_0 is ignored, so that the compiler optimizes out the division operation.
We need to use the return value when we call do_div_by_0, like follows:
TEST_F( SignalsHandling_F, divByZeroDying ) {
ASSERT_EXIT( {
std::cerr << ... |
64,033,513 | 64,035,533 | Can not pass values inside a struct, when use the struct pointer as an argument to a thread function correctly? | I wrote a very simply code to use C++11 thread. I found that if I use struct pointer as an argument for the threaded function, the value inside the struct can not be passed correctly.
Please tell me where I did wrong. Thanks.
#include<iostream>
#include<thread>
#include<mutex>
using namespace std;
typedef struct {
... | Inside of your loop, you are passing a pointer to a local arguments variable that goes out of scope right after the std::thread constructor exits, so the memory is likely to be invalid by the time blahblah() tries to access it.
You would have to declare the arguments memory outside of the loop so it stays around long e... |
64,033,696 | 64,035,657 | Are move semantics implied immediately before an rvalue is destroyed? | In the following function:
void SetObject(Object object)
{
m_Object = object;
}
The SetObject would receive a copy of object, which is an rvalue that is assigned to m_Object and immediately goes out of scope.
Would move semantics be implied so that a second copy of object isn't created unnecessarily? Seems like m... | The object parameter of SetObject() may or may not have been initialized from an rvalue at the call site, but inside of SetObject() it is certainly not an rvalue, it is an lvalue (as it has a name).
As such:
void SetObject(Object object)
{
m_Object = object;
}
will perform a copy into m_Object, not a move.
You ne... |
64,033,938 | 64,034,055 | Get n-th character of string : AddressSanitizer: stack-use-after-scope | I am trying to implement my own string_view. Here is an example of class:
class Example {
public:
Example(const std::string& s) : data_(s.data()) {}
char operator[](size_t pos) const {
return data_[pos];
}
private:
const char* data_;
};
Test:
Example e("hello");
char t = e[1];
REQUIRE(t == 'e'... |
Why do I have this error
Because you point to the contents of a temporary std::string object that no longer exists and attempt to access the content that no longer exists.
how can I fix it?
A string view can remain valid only as long as the string is valid. Do not let the std::string be destroyed before you are don... |
64,034,725 | 64,042,597 | This code is not working properly and it doesn't make any sense why it isn't to me. Does anyone have a guess what the problem might be? | This is the link to the hangman game in C++ I am making. It works perfectly fine on repl, but it doesn't work when I try to build and run it. It shoes letters have been guessed at the very start of the game, when which, obviously you haven't guessed any. The letters are also rather random having nothing to do with the ... | You still do not include all relevant code in your question.
It shoes letters have been guessed at the very start of the game, when which, obviously you haven't guessed any.
The problem is at this point of your code:
array<bool, 26> guessed;
This does not set the elements of the array to false, and they have an inde... |
64,035,110 | 64,035,332 | What is the expected effect of using IAudioClient2::SetClientProperties on a capture client in Windows 10? | The specification of IAudioClient2::SetClientProperties contains only one parameter but is it not clear to me what to expect from the API given the existing documentation. The parameter is given by:
typedef struct AudioClientProperties {
UINT32 cbSize;
BOOL bIsOffload;
AUDIO_STREAM... | The eCategory has behavioral implications that go beyond audio effects. For example, if you have a VOIP app and you start an AudioCategory_Communications stream, that will cause movie apps to pause or be ducked, whether or not you use AUDCLNT_STREAMOPTIONS_RAW.
If your capture client is for VOIP, you want AudioCategory... |
64,035,131 | 64,035,288 | Linux gcc linking issues | I have two libraries , named ( lib1 and lib2) , both are not dependent on each other. I do not have control over how these libraries are built. When I try to link them the order of linking dictates on different behaviors within the final executable,
For example:
If I link them as [1]
gcc $(CC_FLAGS) -o app.out -llib1 -... | Is it possible that there resides a symbol (same name) in both of those libs?
Which one the linker will use to resolve an usage of such a symbol depends on the order (not sure where I've read this).
(HINT: This is just a guess)
So lets assume lib1 defines this function:
void foo( int, char* );
And lib2 defines:
void f... |
64,035,199 | 64,039,340 | Is it dangerous, that ___tls_get_addr called in 32bit environment? | We have x86_64 system, but all libraries and applications are built for i386 and we run them in i386 mode.
gdb (and ltrace too) tell us, that ___tls_get_addr is used, that was designed for x86_64 as far, as I can see (___tls_get_addr gnu) and also we have glibc version 2.19-18 (looks like issue was fixed only in glibc-... | The GCC bug in __tls_get_addr stack alignment you reference is specific to x86-64. It does not exist on i386. I'll assume you swapped i386 and x86-64 in your question.
In general, the distribution toolchains are consistent and well-tested. If you compile your programs with the system compiler and use the system glibc v... |
64,035,284 | 64,065,357 | Date validation not working consistantly in c++ | Heyyy, I made this program to add user defined number of days to a given date. In here I added code for date validation to make sure that user enters the correct date in the first place, my problem is the validation is not working consistently, some times it gets stuck in an infinite loop while taking the day of the mo... | After all the feedback from the community, this is the final program that seems to be working perfectly in my testing. Thank you soo much you all :)
#include <iostream>
#include<conio.h>
using namespace std;
class calendar
{
public:
int d,m,y;
calendar(int day, int month, int year)
{
d=day;
... |
64,035,517 | 64,035,563 | Stringstream & char*[] segmentation fault | On my computer (Win10, WSL 1, Ubuntu 20.04)
This code would compile and run correctly,
#include <iostream>
#include <cstring>
#include <sstream>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
char *test[30];
string a;
cin >> a;
// stringstream ss;
strcpy(test[0], a.c_str());
... | char *test[30] defines an array of 30 pointers to char. test[0] is not initialized before being used in strcpy. The resulting behavior is not defined by the C++ standard.
You must provide memory for the copy of the string and assign test[0] to point to that memory.
Any effects due to the presence or absence of stringst... |
64,035,637 | 64,072,041 | How do i assert, compile time, that the nth element of a tuple is an optional of some type? | I need to check if the nth element of a tuple is an optional of some type.
It has to be an std::optional and not a std::variant (which could have made the code simpler).
My first instinct is the following. But this throws a compiler error.
template<int N, typename TupleToCheck>
void StaticCheck() {
using NthType = ... | Answering my own question for the sake of closure.
The issue with my code was syntax, as @DanielLangr pointed out in the comments.
It works for me (no compilation errors) if I correct syntax errors: godbolt.org/z/dxndEx. Added std::, typename , and ::value.
The fixed code is as below
template<int N, typename TupleToC... |
64,035,815 | 64,038,269 | Equivalent of 1D numpy.interp in C++ Cuda (Lerp in CUDA) | I have two vectors 'xp' and 'fp' which correspond to the x and y values respectively of the data. A third vector 'x' which is the x coordinates at which I would like to evaluate the interpolated values. My results in python using NumPy's interp function was as expected.
import numpy as np
xp = np.array([1.0, 1.5, 2.0... | To mimic the behavior of numpy.interp will require several steps. We'll make at least one simplifying assumption: the numpy.interp function expects your xp array to be increasing (we could probably also say "sorted"). Otherwise it specifically mentions a need to do an (internal) sorting. We'll skip that case and ass... |
64,035,840 | 64,035,932 | If I treat my C code like C++ code, will it run like normal? | It's what I believe to be a very simple question.
Context: I'm following a tutorial that allows me to run C++ code in Visual Studio Code, but I'm trying to run C code, not C++ code. The program I'm trying to run is a simple Hello World program (shown below), but this question applies to all C code.
#include <stdio.h>
... | C and C++ are different languages. And even though they share a similar syntax, the semantic meaning of certain constructs are different.
C++ incorporates a large part of C, but it also diverges. You cannot just assume that C code compiled as C++ will give the same result.
You can write code that is both valid C and va... |
64,036,497 | 64,036,765 | How to cast from `std::vector<uint8_t>` to `std::vector<int8_t>`? | I need to fill data into SetByteArrayRegion:
void JNIEnv::SetByteArrayRegion(jbyteArray array, jsize start, jsize len, const jbyte *buf)
where jbyte is simply int8_t. I have a vector of uint8_t. Why I cannot cast it to a vector of int8_t? uint8_t and int8_t have the same size so they could be casted easily.
std::vecto... | You can't cast a vector<uint8_t> to a vector<int8_t>, they are completely separately and unrelated types. But, you can cast the data instead, eg:
std::vector<uint8_t> messageResponseVector_ = //...
jbyte *data = reinterpret_cast<jbyte*>(messageResponseVector_.data());
env->SetByteArrayRegion(array, 0, messageResponseV... |
64,036,592 | 64,036,911 | Size_t variable as loop counter causing segmentation fault. Why does the loop not exit once i = 0? | The code causing the problem in question is shown below:
for(size_t i = 10; i >= 0; i--){
cout << i << ", ";
}
this outputs:
4, 3, 2, 1, 0, 18446744073709551615,
and then the program returns a segmentation fault for the obvious reason that it attempts to access my the items at a ridiculous index.
why does the coun... | size_t is an unsigned integral. This means that i can never be negative. When i is equal to 0, and you subtract 1, it will become a very large number, not -1.
The condition i >=0 basically says keep running this loop until i is less than zero. Because of the type of i, this condition is never met.
This is something you... |
64,036,740 | 64,092,929 | io.h not found CLion in Ubuntu 20.04 | I am trying to run a c++ code however, io.h is not found.
'io.h' file not found
It is shown as
#include <io.h>
Additionally, I am getting a bunch of weird problems (for a code that is rather > 16 years old):
Use of undeclared identifier '_read'
or
Unknown type name '__int64'; did you mean '__int64_t'?
or
Use of u... | Add compiler directives to manage multi-os compilation.
//old line: #include<io.h>
#ifdef _WIN32
#include <io.h>
#elif __linux__
#include <inttypes.h>
#include <unistd.h>
#define __int64 int64_t
#define _close close
#define _read read
#define _lseek64 lseek64
#define _O_RDONLY O_RDONLY
... |
64,036,830 | 64,037,321 | Create span of string_views from C string array | Given some function void func(std::span<std::string_view>), how does one feed this function a raw array of C-strings const char** in the most efficient manner?
As far as I understood this should be possible as without any copying as std::string_view can be constructed from a C string and std::span can be constructed fr... | If you think about it, to do what you are asking the compiler needs to find somewhere to store 3 std::string_views and there is no such place since std::span doesn't actually allocate any storage for the elements it references.
So, AFAICS, there's no direct way to do this.
Edit: this, I think, is the cheapest way to d... |
64,037,163 | 64,037,351 | Overloading a function to use an rvalue reference instead of an lvalue reference | I am creating a doubly linked list template and I have to write 2 constructors where we pass in a linked list, and then construct a new list that has the same number of nodes as well as the same numbers in those nodes. The memory locations of the nodes will be the only difference between the two.
I have two constructor... |
the code is the same for both since it's not a shallow copy, right?
The List(const List &rhs) copy constructor is expected to deep copy (not shallow copy) the data (not the nodes themselves) from rhs to this, but otherwise leave rhs intact and untouched.
The List(List &&rhs) move constructor is expected to move (stea... |
64,037,824 | 64,037,889 | block a function when argument type does not belong to a set of types | In a specific requirement I need to allow instantiation of a template function func only for a specific set of allowed types.
Therefore I tried to use already available std::type_traits and then used std::enable_if to block instantiation. Here is my implementation.
// C++17
#include <vector>
#include <cstdint>
#include... | You can write isCompatible like this:
template<typename T, typename ...Ts>
using isCompatible = std::bool_constant<(std::is_same_v<T,Ts> || ...)>;
There's not much you can do for CompatibleTypeCheck since you need to specify all the allowed types somewhere.
Here's a demo.
Note that enable_if is usually used when you... |
64,037,882 | 64,037,935 | Lottery ticket matching numbers system but spamming you lost | #include <iostream>
#include <vector>
using namespace std;
int main () {
std::vector<int> winning_numbers {13579,26791,26792,33445,55555,62483,77777,79422,85647,93121};
std::cout <<"Please Enter Your Numbers: ";
int users_numbers;
std::cin >> users_numbers;
int size = winning_numbers.size... | Very simple mistake. While the indentation would make you think everything is fine, your matching curly bracket is in the incorrect location for the while loop. Currently, it spams the "You Lost" at the completion of every index that it scans because it is being told to. I would suggest the following changes:
while(ind... |
64,038,144 | 64,038,268 | getaddrinfo, bind, localhost and INADDR_ANY | I'm learning socket programing and pretty new to this...
My question is, I want to write a UDP server that is able to receive packets from both remote server and local host via a OS-assigned socket.
I know I should somehow pass INADDR_ANY to bind() to let it accept packet from both. and I guess I need to pass char *ser... | It is not getaddrinfo() that assigns a random available port. It is bind() that does so when port 0 is requested.
The getaddrinfo() man page is correct. The node and service parameters cannot both be NULL at the same time. You can set node to NULL to get INADDR_ANY - or - you can set service to NULL to get port 0. ... |
64,038,281 | 64,038,326 | Why is this vector of vectors out of scope? | I've written the code below to add/multiply a vector of vectors (a multidimensional array, essentially):
int matrix_numbers[] = { 1, 2 };
// get rows and columns from user (omitted)
for each (int matrix in matrix_numbers) {
if (matrix == 1) {
vector<vector<int>> first_matrix(rows, vector<int>(columns));
... | Because you are declaring them within the if statement inside the for loop.
This means you can only access them within that if statement.
See this tutorial on variable scope
You can fix them by rewriting them to have a scope equal to the function.
Your iterator also looks wrong, you should rewrite this also.
const int ... |
64,038,549 | 64,038,597 | Is this algorithm for BTree Construction, O(n) time complexity? | Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr... | There's not only for loop in the given code, there are recursions, which may make your code O(n * log n). Master theorem will be helpful if you'd like to strictly prove the complexity of your algorithm.
|
64,039,164 | 64,039,489 | Can't I call rand() multy times in a line? | for (int i = 0; i < 12; i++) {
Vertex v;
v.pos = (glm::vec3)((GLfloat)(rand() % 100) / 50 - 1, (GLfloat)(rand() % 100) / 50 - 1, (GLfloat)(rand() % 100) / 50 - 1);
v.col = (glm::vec3)((GLfloat)(rand() % 100) / 100, (GLfloat)(rand() % 100) / 100, (GLfloat)(rand() % 100) / 100);
tri4.objDa... | The reason it isn't working for you is that you are using
v.pos = (glm::vec3)(...)
which is casting the stuff denoted by ... into a vec3.
But the ... is three comma separated GLfloat values. The comma operator discards the first two and the third one is casted into a vec3 using the single argument constructor and that... |
64,039,374 | 64,039,488 | c++ terminate called after throwing an instance of 'std::system_error' what(): Resource deadlock avoided when join thread | I'm writing a simple test code for signal handle. I produce a SIGSEGV in a child thread, and handle the signal.
But the error std::system_error' what(): Resource deadlock avoided makes me so confused. Why there is resource deadlock?
struct TestSignal{
static TestSignal& GetInstance(){
static TestSignal t;
... | The signal handler is called in the context of the thread t. You can't call t.join() in the thread routing, it would cause deadlock, thus you get program terminate, this way the deadlock is avoided.
|
64,039,449 | 64,039,745 | Matrix multiplication using multiple threads | So I am trying to compute (M by N matrix) times (N by 1 vector) operations with threads into a resulting vector. The question in my book says that I should think about how many threads to use, and I assume since the result matrix should be M by 1 then I should use M threads, one for each set of operations.
M is height,... |
What I am having trouble figuring out is how should I sum up all the
resulting values in the correct order.
They can be summed out-of-order, which is why this is a good problem to solve with multi-threading. If ordering matters to a specific problem, you can't improve it with multithreading (to be clear, if any sub-p... |
64,039,938 | 64,039,995 | What is the meaning of std::stack<int,std::vector<int>> s1; | What is the meaning of std::stack<int,std::vector<int>> s1; in C++.
Can anyone clearly explain to me what is the meaning of the above statement...
Is it a stack of vectors?
Why are we adding a stack inside a vector?
It would be really helpful if anyone could answer at the earliest.
| The type:
std::stack<int,std::vector<int>>
means that we wish to construct a stack of integers, with the container for the stack implemented as a vector of integers. More detail, in the unlikely event you need it, can be found here.
In other words, create a vector of integers, then wrap the stack type around that.
A s... |
64,040,343 | 64,040,407 | Getting Segmentation fault while trying to initialise a 3 dimensional vector dynamically in a loop | I am creating a vector<vector<vector>> called points_in_clusters.
The purpose is to store the lines of a csv file(points) into a 3D vector. The first dimension of the vector is the cluster number and the rest (vector<vector>) is the set of points belonging to the corresponding cluster.
So for example, after reading the... | Your vector is empty, just change this
for(int numCluster = 0 ; numCluster < k ; ++numCluster){
read_initial_clusters(k , fileName , step , numCluster ,points_in_clusters);
}
to this
for(int numCluster = 0 ; numCluster < k ; ++numCluster){
points_in_clusters.push_back({});
read_initial_clusters(k , fileNa... |
64,040,944 | 64,041,219 | Can I reinterpret_cast the parameter of a constexpr function? | I want to write a function evaluated at compile time, it takes a pointer to 4 bytes array, and outputs an int that has the same bit pattern as that array.
So I came up with:
constexpr int f(const char* p) {
return *reinterpret_cast<int*>(p);
}
Then, I want to use f() like this:
switch(x) {
case f("GOOG"):
// d... | Congratulations, you have activated the strict aliasing trap card and your code has undefined behaviour (if it would compile).
There are few errors in your code, the "correct" version is:
constexpr int f(const char* p) {
return *reinterpret_cast<const int*>(p);
}
reinterpret_cast cannot cast away const.... |
64,041,512 | 64,120,546 | UWP App Crash at Class1 c1 = new Class1(); saying - The specified module could not be found. (Exception from HRESULT: 0x8007007E | I am trying to create a library of fftool so that the uwp app doesn't have to launch a process to run FFmpeg exe out of the environment and yet able to run all command of fftool. so, for that
first, I created a static lib compiling fftool c code adding all the necessary linking and include
then I created a WinRT compon... | ok so it looks like my app is unable to find FFmpeg core dll as avcodec, avfilter, etc so now I added them to exe location and it worked ok
|
64,041,834 | 64,042,161 | How to make an array/vector of pairs of 2 corresponding integers from 2 different user input lines in C++? | How to pair up corresponding elements from two different input lines, to form one array of pairs in C++ ?
Eg. input :
0 1 2 3 4
5 6 7 8 9
output = [{0,5} {1,6} {2,7} {3,8} {4,9}]
Edit :
Input is given by the user through stdin and not in the form of 2 different arrays.
I want to store this input directly in the form ... | Revising your attempt, you should update the pair in the second loop rather than replacing it.
vector<pair<int, int>> pairs;
for (int i = 0; i < n; i++) {
cin >> k;
pairs.emplace_back(k, 0);
}
for (int i = 0; i < n; i++) {
cin >> pairs[i].second;
}
|
64,041,869 | 64,047,929 | What is the reason for std::memcpy not being constexpr even in C++20? | I understand that copying arbitrary chunks of memory is not always possible to do at compile time but since we are getting constexpr constainers, virtual methods and also algorithms, why not memcpy too? It is too a kind of algorithm.
Furthemore,
C++20 std::bit_cast seems a lot like std::memcpy workaround reinterpret_c... | The C++ object model in runtime code is generally treated somewhat loosely. It has fairly strict rules, but there are a bunch of backdoors that are either allowed or declared UB. The latter means that you can still write code to do it, but C++ guarantees nothing about the behavior of that code.
Within constant evaluati... |
64,041,982 | 64,042,074 | Having trouble converting a string to a linked character list in C++ | I have been working on this for a while and am currently stumped. The starting requirement for the program is to accept a string, create an object for the class, and convert it to a linked list of characters. I'm having trouble with the whole class since when I try to predefine a new object in the Main function before ... | You're missing linkedChar no arguments ctor (it's declared but not defined) and you're missing return statement in strToLinkedChar.
|
64,042,174 | 64,042,527 | std::map::operator[] is more efficient than std::map::insert? | I've learnt that operator[] is equivalent to
(*((this->insert(make_pair(k,mapped_type()))).first)).second
So if a key doesn't exist in the map, using operator[] is less efficient than using insert, right? Because there's one more step, default construct.
So I wrote a demo to test, like this.
#include <iostream>
#incl... | The expression make_pair(1, f) has type std::pair<int, Foo>, which isn't your maps value_type, which is std::pair<const int, Foo>, so there is a copy in the arguments of insert. There then are 2 copies within map, that would be moves if all your special members didn't suppress the generation of move construction.
If yo... |
64,042,278 | 64,043,638 | How to center text in QGraphicsSimpleTextItem? | Sorry for my English, it's not my native language.
I have a problem - I need to center text in my QGraphicsSimpleTextItem. I inherited my class from QGraphicsSimpleTextItem. Do I need to override the paint() method or what should I do?
I've read about tightBoundingRect() in QFontMetrics. Can I set position of tight bou... | Maybe something like this could work.
void MySimpleTextItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
QFont numberFont = QFont("Helvetica [Cronyx]", 20);
painter->setFont(numberFont);
painter->drawText(boundingRect(), Qt::AlignCenter, QString::number(it... |
64,042,324 | 64,143,879 | Cannot run class with template from different .cpp file | I have a class using templates, when I write it using just one .cpp file it works fine, but when I try to the class into its own .cpp and .hpp file I get an error message: The preLaunchTask "C/C++: g++ build active file" terminated with exit code 1, but when I click on "show errors" it tells me that no problems have be... | Your implementation should look like this
untested code ahead
#include"myArray.hpp"
template<typename T, size_t S>
constexpr int myArray::arraySize() const {return S; }
template<typename T, size_t S>
T& myArray::operator[](size_t index) {return m_Data[index]; }
template<typename T, size_t S>
T* myArray::arrayData() ... |
64,042,418 | 64,042,546 | Advancing multiple iterators into the same stringstream | Please check out this code snippet
std::istringstream s("abc");
std::istreambuf_iterator<char> i1(s), i2(s);
std::cout<< "i1 returns "<<*i1<<'\n'
<< "i2 returns "<<*i2<<'\n';
++i1;
std::cout<<"after incrementing i1, but not i2\n"
<<"i1 returns "<<*i1<<'\n'
<<"i2 returns "<<*i2... | From cppreference:
std::istreambuf_iterator is a single-pass input iterator that reads successive characters from the std::basic_streambuf object for which it was constructed.
The important part here is the single-pass characteristics: once a value has been read, you cannot go back and read it again. Recall that you ... |
64,042,721 | 64,053,296 | std:: has no member "filesystem" in C++/17 | I'm trying to include <filesystem>, but when I use a namespace, it shows this error:
std:: has no member "filesystem"
I know in older times it is <experimental/filesystem> and namespace is std::experimental::filesystem;
but, when i does this, it also give error like that:
#error The <experimental/filesystem> header... | After Struggling 10 hours, I got the answer. I'll post it for who'll get same problem with me in the future;
in my case, Visual Studio Configuration settings are only set in x86 configuration, so set configurations to all configurations, than use these steps:
1- Project properties -> configuration properties -> general... |
64,042,894 | 64,043,735 | CHAR Compare is right, even when it's wrong | first im new at c++ programming and at the moment im stuck in a maybe very easy problem.
I thought, after get the other stuff working and in my oppinion, much harder, i will implement a little string compare and im are ready, ha ha...
I tryed to figure out what is the problem and working on it since hours...
I try to m... | strcmp is only for const char *, not a single char like you are using it.
I don't remember if Arduino permits you to use the std::string but in case just use it.
It introduce you lot more methods for string handling. Like s.find(c) that return directly the position of the char in the string.
By the way, to compare 2 ch... |
64,043,769 | 64,043,987 | two default Constructor, one in public and one in private | My question is about constructors in OOP(C++). When I define default constructor in a class as private and when I initialize an object of that class in main as default then error occurs that default constructor is inaccessible. It's fine. But then I also make default argument constructor in Public section and when I in... | For Example take a class
#include "iostream"
class Type
{
private:
Type()
{
std::cout<<"Private Default";
}
public:
Type()
{
std::cout<<"Public Default";
}
};
int main()
{
Type obj;
}
Here both default constructor is in scope Type::Type() You can't overload like thi... |
64,044,036 | 64,044,893 | C++ - union with nontrivial class member type? | I'm working with a union which has a member that is a class that uses diamond inheritance, but the program encounters a segmentation fault upon assignment to this member.
My suspicion is that I need to add some copy constructors, but after multiple attempts, the correct way to do this still evades me.
I've included a m... | Since the Base class is virtual, most likely there are some internal control structures, which become destroyed, when you assign
example.i = -1;
When you recreate value, e.g.
new(&example.value) Final();
example.value = Final();
before the assignment, the segmentation fault goes away. Although, I wouldn't recommend t... |
64,044,195 | 64,044,397 | How can i decide the datatype Boost Property Tree uses? | I am using the Boost Property Tree for a Project and came across a problem. I'm using it like this:
using Namespace boost::property_tree;
ptree proot;
int myInt = 5;
proot.put("Number", myInt);
write_json("myjson.json", proot);
If I use it like this, the data type that is safed is a string, not an int. An example o... | No you cannot change this behavior, as the string value type is pretty muched baked into boost::property_tree. While you could technically use different template type parameters than the default ones, you loose much of the conversion logic that went into that library.
As a somewhat wanky alternative, consider the follo... |
64,044,469 | 64,044,733 | C++ class functions compared to C# | I am learning C++ at the moment, and I came across a lot of examples where classes are declared differently than I'm used to in for example C# or Java. The following thing isn't clear to me:
When defining a class in C#, you code the methods that you are going to use entirely within the class, like so:
public class exam... | For this issue you need to learn a few new concepts...
The first is about how C++ programs are built. A C++ program can contain many independent source files. Each source file is compiled independently of each other, into object files. Then all the object files are linked into the final executable program file.
Then th... |
64,044,725 | 64,045,070 | Problem related to points on a plane and some technical errors [C++] | Statement of the problem: Given n points on a plane (n is even). Find the number of pair of points such that there is an equal number of points on both sides of the line passing through them.
I'm trying by brute-force (~O(n^3)), any suggestion on improving the solution is greatly appreciated. I have also found this ans... | I think you don't need to brute force it, at least n^2logn should be better than n^3. I won't write out the code in c++, but I'll explain the algo:
Think of each point as the centre of a hub, connected to all the other points by lines. Then each pair of points with that centre makes a certain angle with the x-axis, wh... |
64,046,223 | 65,496,681 | VS Code cant run C/C++ in integrated Terminal | So I am trying to Setup C/C++ in VS Code.
I installed mingw, the C/C++ Extension in VSCode and Code Runner
Code Runner has the following Setting turned on:
RunInTerminal
This is the Code I try to run:
#include<stdio.h>
int main()
{
int age;
printf("Enter age\n");
scanf("%d", &age);
printf("Age is %d", ... | This can be an issue with code-runner extension I have similar like Issue but sometimes my code executable runs and then it crashes . So i try to run them in terminal
If the terminal option still Dosen't work , This can be your antivirus causing the issue . Your antivirus treats the C/C++ executable file as malware a... |
64,046,258 | 64,047,074 | How to lazily initialize a template tuple of unique_ptrs? | I need to write a class that creates snapshots of data based on asyncronous callbacks. For example, if I have an integer stream and a double stream, I have to push the data into a queue and process the data once there's a value for both of them. My class looks like this atm:
template<typename... Types>
class Dataholder... | I am immensely surprised by the difficulty involved in doing something so simple. This is the implementation where you have a tuple of deques, which ends up being exactly as efficient as you could do by hand, ie you don't loop through the queue looking for an empty entry.
template<typename>
void get(); // for ADL
tem... |
64,046,912 | 64,052,963 | C++ sum of digits of each element in a column | I am new to C++, trying to import dates into a program, adding up digits of day, month, year resp and writing back to txt.
input data
sl.no name day month year
1 Rob 15 05 2019
2 Tim 12 06 2002
Desired output data in txt
sl.no name day month year
1 Rob 6... | I am no expert . but have been in your spot a few months ago.. break down the problem into smaller steps..
My approach..
Pseudo Code:
Ditch the header
Create a function for adding the digits
Read data from file
Use a loop to run through each element of the every column and use the function created
Store results in a v... |
64,048,013 | 64,064,075 | OpenCV FFMPEG RTSP Camera Feed Errors | I'm getting these errors at random times when saving frames from an rtsp camera feed. The errors happen at different times, usually after 100-200 images have been saved, and the errors themselves are not always exactly the same. They cause the images that are saved at the time of the error to be distorted either to ... | OpenCV and RTSP streams are a little tricky. This usually happens when the frames of the stream cannot be read fast enough. In that case (somewhere) a buffer receiving RTSP frames will be filled faster than is can be emptied; when the buffer is full it will be flushed and will restart filling from the most recent frame... |
64,048,170 | 64,048,367 | when exactly the increment happens in a for loop in C++? | I have this logic that ideally should find pairs of ints in an int array, and after finding the pair, remove it from the array itself and start over.
While debugging I noticed something that, for the given sample input test case when i=0 and j=3 the if condition satisfies and the 1st pair is found then pairs value gets... | Quoting from cppreference, this for loop
for (init_statement ; condition ; iteration_expression) {
statement
}
Is equivalent to:
{
init_statement
while ( condition ) {
statement
iteration_expression ;
}
}
Your confusion is most likely caused from erasing elements while iterating. In... |
64,048,465 | 64,048,800 | I have written a code for creating a linked list. While printing the list items I am getting SIGSEV error. How do we fix it? | I know I have done a silly mistake and to not make it again in the future I want to know why this error is showing up in the following code. I have already read on the internet that it is caused when our program is trying to access memory block which is not yet created but I cannot find where it is occurring in my prog... | You have multiple parts in your code that result in undefined behavior.
You never initialize i so doing i < 5 isn't valid.
You never initialize Node *head so that one also holds an indeterminate value, that value is assigned to nodeToInsert->next in insertHeadNode.
So also cout << temp->value << "->"; would be invalid,... |
64,048,862 | 64,049,120 | Create std::u8string from std::string/char const* when the latter is already in utf-8 | I'm in the process of upgrading my code base to C++20 and would like to make use of std::u8string/char8_t. I'm using a 3rd-party library that takes and returns UTF-8 strings in its API, however it hasn't been updated to C++20 yet and thus takes and returns the UTF-8 strings as regular std::strings instead of std::u8str... | u8string u8s(s.begin(), s.end()) should work just fine. You don't need the cast. The constructor is templated, and char implicitly converts to char8_t.
The underlying type of char8_t being unsigned char is not a problem even if char is a signed type.
|
64,049,187 | 64,049,471 | priority_queue with custom comparator as value in map constructor error | I have created a priority_queue with custom comparator which stores string in lexicographically sorted order, and it works as expected.[ Ref. this] ]
Now, I want it to be value in an unordered_map, and I got error: no matching constructor for initialization ... and closest thing I found is this. I realize I need to pas... | Using a lambda was a bad idea... just provide comparison through the comparison template argument, then no constructor argument is required...
#include <iostream>
#include <vector>
#include <unordered_map>
#include <queue>
using namespace std; // Used to make code less verbose
struct Cmp {
bool operator()(const st... |
64,050,036 | 64,062,424 | C++: boost io_context/strand wrap causes segment fault on shared_ptr | Could someone help me understand why I got the following result from the code snippet? If change the lambda function to take at least 1 parameter: I got output "valid ptr" twice. This was found in a segment fault crash I had in my code.
Output:
valid ptr
nullptr
#include <iostream>
#include <memory>
#include <boo... | First you have to actually use a strand and io_context::wrap is deprecated.
So lets write
#include <iostream>
#include <memory>
#include <boost/asio.hpp>
auto getScheduleWrapper(boost::asio::io_context::strand& strand)
{
auto sharedPtr = std::make_shared<int>(0);
return [sharedPtr, &strand] () {
boost::asi... |
64,050,045 | 64,050,594 | Idiom for data aggregation and post processing in C++ | A common task in programming is to process data on the fly and, when all data are collected, do some post processing. A simple example for this would be the computation of the average (and other statistics), where you can have a class like this
class Statistic {
public:
Statistic() : nr(0), sum(0.0), avg(0.0) {}
v... | "Idiomatic average"
I don't know Ruby but you can't translate idioms directly anyhow. I know that calculating the average is just an example, so lets see what we can get from that example...
Idiomatic way to caclulate sum, and average of elements in a container is std::accumulate:
std::vector<double> data;
// ... fill ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.