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 |
|---|---|---|---|---|
63,957,051 | 63,957,254 | Adding the : in front of variable gives wrong result | I am comparing the class. For the below code
#include <string>
#include <set>
#include <tuple>
#include <cassert>
enum class e : bool
{
positive = true,
negetive = false
};
class A
{
public:
int a;
e e1 : 1;
friend bool operator==(const A&, const A&);
};
bool operator==(const A& lhs, cons... | This function:
auto tie = [](const A& a1) {
return std::tie(a1.a, a1.e1);
};
returns a std::tuple<int const&, e const &>. Even though the fields that the tuple store are references, there is a special rule for bit fields where a temporary copy of the bit field is made, and a reference is bound to that temporary. T... |
63,957,545 | 63,987,552 | How to check a variable periodically by QTimer | I have a global variable that i set on a cpp file on my qt project. I want to check this variable in every 100ms for 5 second and if the variable is 0 after 5 seconds I want to create a message box. Here is the sample of my code:
db.cpp:
if(case){
g_clickedObj.readFlag = 1 ;
}
else{
g_clickedObj.readFlag = 0 ;
}... | Option 1: Use a timer with 100ms interval to check global variable, hold a member variable for counting how many times timer slot called. When slot called 5000/100=50 times, stop timer and create message box if necessary.
void MyClass::onTimeout(){
// check variable
// increment counter
// check if counter ... |
63,957,662 | 63,958,440 | How to allow my C++ code to update variables? | I'm new to coding and C++.
The code below is meant to monitor a magswitch and a status led on another controller. The code needs to run once the magswitch pin goes high (this works).
The additional code for pulseIn, is what I hope to use to monitor different flash rates of the led when I get the code working. For now I... | Look at your conditional, with proper indentation (do get a text editor that can indent your code for you):
if ((ontime) != 0)
state = period;
else if (statuspinstate = 1)
state = 9999;
else if (statuspinstate = 0);
state = 0;
We know that ontime is zero, so the second condition is tried next.
Now, statuspinst... |
63,957,850 | 63,957,942 | C++: Extraction of template types | I am working on a compile-time wrapper library and stumbled upon a problem of extracting a template parameter type from a given type.
The situation is the following. I have an unchangeable class R:
template <class T>
class R {};
I also have an unchangeable main function:
int main()
{
auto r = new R<int>();
//... | Yes, it is possible, one way to do it:
template<typename T>
class R{};
template<typename C>
struct extract_impl{};
template<typename T>
struct extract_impl<R<T>>{
using type = T;
};
template<typename C>
using extracted_type = typename extract_impl<std::remove_pointer_t<std::decay_t<C>>>::type;
template< class ... |
63,957,943 | 63,960,700 | Boost ASIO - Unable to read packet header from body | I use Boost ASIO and I would like to separate header from body message.
Here is my opcode enum:
enum ServerOpcode : uint16_t{
SMSG_AUTH_CONNECTION_RESPONSE = 0x001,
SMSG_LOGIN_REQUEST_RESPONSE = 0x002,
SMSG_LOGIN_REQUEST_RESPONSE_TEST = 0x1A6,
};
Here... | In this line after reading:
std::cout.write(_packet.data_, _packet.header_length);
header_length is 8 = length of '1a6 I am'
Your header length should be 3 (not 8), if you want to have '1a6' only.
|
63,959,103 | 63,959,794 | A switch statement without case: or default: labels | cppreference.com stats that the form of the switch statement is:
attr switch ( condition ) statement
and that statement is any statement.
So, what will happen if I didn't put any case: or default: labels in statement, as:
switch (1) {std::cout << 'x';}
What if I wrap a statement that doesn't come after any case: or def... | Nothing happens.
[stmt.switch/5]: When the switch statement is executed, its condition is evaluated. If one of the case constants has the same value as the condition, control is passed to the statement following the matched case label. If no case constant matches the condition, and if there is a default label, control... |
63,959,152 | 63,959,393 | Expression: string subscript out of range console buffer | I am trying to make an application that just prints some numbers into the console by putting it in a buffer first. I'm just testing it right now but (seemingly when the wchar_t values get copied over to the bufferArray) it's giving me this error message: Expression: string subscript out of range
#include <Windows.h>
#i... | The error message is correct, it looks like you're reading past the end of the string. You have bufferArray[i] = intValue[i] in a loop that runs 8 times regardless of how long the intValue string is.
It kind-of looks like you're trying to detect the end of intValue (by checking to see if intValue[i] is zero) and do som... |
63,959,160 | 63,959,330 | Defining a function with two different template paramenter | I have the following code
template< typename T>
struct S{
T x,y;
S(T a, T b) : x(a) , y(b) {}
};
using Di = S<int>;
using Dd = S<double>;
auto foo(Dd d){
..........
}
Now my doubt is: suppose I am calling foo() with parameter of type Di then it's an error of incorrect reference type.
I know that ... | You can make the function a template:
template<typename T>
auto foo(S<T> d){
// ...
}
Now you can call foo with any instantiation of S.
If you want to constrain the function template to only accept instantiations of S with either int or double, you can do that check inside the function:
template<typename T>
auto f... |
63,959,305 | 63,989,920 | WritePrivateProfileString - is unpredictable | We are using a tool that uses internally the simple Win-Api call WritePrivateProfileString.
I'm aware of the define flag UNICODE to map either to WritePrivateProfileString**A** or WritePrivateProfileString**W**
I am writing something to the INI file, that file doesn't exist before.
And it behaves differently on some sy... | I found the root cause:
https://en.wikipedia.org/wiki/Unicode_in_Microsoft_Windows
In April 2018 with insider build 17035 (nominal build 17134) for Windows 10, a "Beta: Use Unicode UTF-8 for worldwide language support" checkbox appeared for setting the locale code page to UTF-8.[a] This allows for calling "narrow" fun... |
63,959,346 | 63,960,256 | Can initialization order of global variables across TUs be forced with C++17 inline members? | This is mainly a curiosity-driven question, I do not plan to write such code.
It is a followup from my answer about dynamic initialization order.
From what I presented in the answer, inline static member variables are initialized in the order their classes appear in the source code if such order is the same across all ... | Let's simplify your example somewhat to make it easier to understand:
// X.cpp
int x1 = foo();
inline int a = foo();
int x2 = foo();
// Y.cpp
int y1 = foo();
inline int a = foo();
int y2 = foo();
Your question is whether x1 is guaranteed to be initialized before y2 and y1 is guaranteed to be initialized before x2.
Th... |
63,959,480 | 63,959,566 | how can I round of the grading system using C++ | Every student receives a grade in the inclusive range from 0 to 100.
Any grade less than 40 is a failing grade.
Sam is a professor at the university and likes to round each student's grade according to these rules:
If the difference between the grade and the next multiple of 5 is less than 3, round grade up to the nex... | You break out of your loop as soon as you found a grade below 38, and don't even look at the rest of the grades.
You need to skip those elements by using continue;:
if((grades[i])<38)
continue;
Just noticed that you pass your vector<int> grades argument by value, so all changes you make to it in that funct... |
63,959,575 | 63,959,785 | split a string using multiple delimiters (including delimiters) in c++ | I have a string which I input as follows
using namespace std;
string s;
getline(cin, s);
I input
a.b~c.d
I want to split the string at . and ~ but also want to store the delimiters. The split elements will be stored in a vector.
Final output should look like this
a
.
b
~
c
.
d
I saw a solution here but it was in j... | This solution is copied verbatim from this answer except for the commented lines:
std::stringstream stringStream(inputString);
std::string line;
while(std::getline(stringStream, line))
{
std::size_t prev = 0, pos;
while ((pos = line.find_first_of(".~", prev)) != std::string::npos) // only look for . and ~
... |
63,959,868 | 63,960,176 | Why it shows error: expected expression before ‘return’? | #include<stdio.h>
int main(void)
{
int x=1,y=0;
x>y?printf("Hello World"):return x;
}
Why it shows error: expected expression before ‘return’?
What is the thing need to be changed here?
|
Why it shows error: expected expression before ‘return’?
The ternary operator is an operator, requiring three operands. The first operand must be an expression of integer type. The latter two operands must be expressions of type compatible with each other.
A return statement specifies a return value for the functio... |
63,960,908 | 63,961,123 | Fastest way to spread 4 bytes into 8 bytes (32bit -> 64bit) | Assume you have a 32-bit unsigned integer, where the bytes are organized like this: a b c d.
What is the fastest way to spread these bytes into a 64-bit unsigned integer in this fashion:
0 a 0 b 0 c 0 d? It is for the x86-64 architecture. I would like to know the fastest approach without using special intrinsics, altho... | uint64_t x = ...;
// 0 0 0 0 a b c d
x |= x << 16;
// 0 0 a b ? ? c d
x = x << 8 & 0x00ff000000ff0000 | x & 0x000000ff000000ff;
// 0 a 0 b 0 c 0 d
And for completeness, modern x86 processors can do this with one quick instruction:
x = _pdep_u64(x, 0xff00ff00ff00ff)
|
63,961,185 | 63,961,335 | C++ QT Event: Access outer class' private variables from inner nested class | Below is a working C++ QT code that simply displays an image with mouse events. To implement the events, I nested a custom QGraphicsPixmapItem class within my MainWindow class. The problem I am having is accessing and modifying the private variable a in the MainWindow outer class from within the event function of the... | You need an instance of your MainWindow class in order to reference it's non-static members. So the quick fix is to make a static:
// mainwindow.h
class MainWindow
{
private:
static int a;
}
// mainwindow.cpp
int MainWindow::a = 0;
If that doesn't work for you, then you'll probably need to pass in the MainWindow ... |
63,961,268 | 63,961,334 | How to define Static member of a class | I'm retrieve a list of paths stored in a json file, I'm not having trouble receiving the path but I get the error undefined reference to `objectFactory::objList[abi:cxx11]' When i try to add the path to a static vector of the same class.
I tried changing the types of both to see if maybe it was an issue where it was lo... | You need to define that data member. For example, at the top of your cpp file:
std::vector<std::string> objectFactory::objList;
|
63,961,401 | 64,124,258 | When I try to decompose a double number into an array as elements, why do I get an offset preventing me from getting the last digit? |
I have a problem. I want from a given number to get each digit as an element in the same array.
But when I compile, if I extend the range from one iteration above the size of the given number, I get a corrupted data exception from Visual Studio in Debug mode as an exception.
I thought first that was because the int ty... | I finally encapsulated the whole code into two functions. But I have an extra value at first and last iteration...
The answer is almost complete, just need to solve the offset from inside the main moved to it's owned function. I finally added a new array variable with the exact size I want from the two new functions, s... |
63,961,762 | 63,961,941 | What auto keyword does under the hood when used with function pointers? | While experimenting with auto and function pointers I notice a strange behavior
class Test
{
public:
void Func(){}
};
static constexpr const auto member_ptr1{ &Test::Func }; // compile fine
static constexpr const void(Test::*member_ptr2)(void) { &Test::Func }; // ERROR : cannot convert from void(Test::*)(void) to ... | This
static constexpr const auto member_ptr1{ &Test::Func };
declares a constant pointer to a member function. That is the pointer itself that is constant.
This record is equivalent to
static constexpr void(Test::* const member_ptr2)(void) { &Test::Func };
Here is a demonstrative program.
#include <iostream>
#includ... |
63,962,334 | 63,962,671 | why i take error LINK2019 when using dbghelp.h functions? | i'm using VisualStudio 2019 for development and i try to use the library dbghelp.h in a C++ program, i just see the question related to LINK2019 but set the sdk folder as other source for library doesnt't work for me.
in particular when i try to use the function SymLoadModule64 i receive :
Severity Code Description P... | thanks to drescherjm (comment below the queston), the problem has been solved by adding the library manually by Configuration Properties -> Linker -> Input and in the right grid in additional dependencies adding Dbghelp.lib or maybe in general the library that created the linker problem
|
63,962,564 | 63,962,738 | C++ Reverse order of Input and Print it out as Char* | I have to reverse the order of the input (which the user types in), and then print out that reversed order with the variable ret that I have. If you go to line 33 in my code you will see cout << "output : " << ret << endl;. This is an assignment so unfortunately I have to use ret otherwise I would just print it out usi... | You have the right idea about going over the digits of the inputted number.
The missing part is converting them to the chars that represent those digits. Luckily, all the characters representing digits are sequential, so they can all be represented as the offset of that digit from the character '0':
// Function definit... |
63,962,622 | 63,963,011 | An error, im trying to make a function that process a person's symptoms and then store it inside a vector string as "Y" or "N" and i get this | #include <iostream>
#include <vector>
using namespace std;
string disease(vector<string> symptom, vector<string> name, int patientnum){
string holder;
cout << "is " << name[patientnum] << " experiencing " << symptom[patientnum] << " Y/N";
cin >> holder;
if(holder == "Y" || holder == "y"){
re... | Change the function to void, since you don't want to return anything from it.
void disease(vector<string> symptom, vector<string> name, int patientnum){
string holder;
cout << "is " << name[patientnum] << " experiencing " << symptom[patientnum] << " Y/N";
cin >> holder;
if(holder == "Y" || holder == "... |
63,962,623 | 63,962,687 | strings in if statement | I am trying to write a code which lists all words used in a text file without repeating. I succeeded to list all the words but I always get repeating ,the if statement line 17 always gives the value of 0.I have no idea why , the words are listed properly in the vector. Any suggestion ?
#include <iostream>
#include <fst... | Inside of checkifexist(), you are creating a new reading object, whose words vector is empty, so there is nothing for the loop to do, and the function returns 0.
You need to instead pass in the reading object from main() as an input parameter, eg:
#include <iostream>
#include <fstream>
#include <vector>
using namespac... |
63,962,639 | 63,962,759 | What is the structure of a std::vector? | I have made a recursive way of printing all of the elements of a vector, but it returns nonsense! and it throws a really strange exception:
Exception thrown: read access violation.
std::vector<int,std::allocator<int> >::operator[](...) returned nullptr.
And it outputs: 12358000
This is the code. What is the mistake I ... |
What is the mistake I have made?
You are using a pointer to a single vector and treat it as if it points into an array of std::vector<int>. It is only allowed to increment pointers that point to elements in arrays (actually you are allowed to get a pointer one past an object, but not more). A single std::vector is no... |
63,962,890 | 63,963,413 | Verifying Python reference count when sending list as parameter | I have a C++ class that imports a Python module as a file and continuously calls a function for it before returning the received data:
ProgramLiveProcess::ProgramLiveProcess() {
//Start Python to run the Program Python code
Py_Initialize();
//Import the Program live processing module
program_live_proce... | In your free_intensities_list function, you may be doing double frees. Consider using the Py_XDECREF instead.
void Py_DECREF(PyObject *o)
Decrement the reference count for object o. The object must not be NULL; if you aren’t sure that it isn’t NULL, use Py_XDECREF(). If the reference count reaches zero, the object’s ty... |
63,963,686 | 64,044,019 | On which Windows versions is Cloud Files API supported? | Microsoft website says about Cloud Files API (Cloud Sync Engines):
Starting in Windows 10, version 1709, Windows provides the cloud files
API.
However, OneDrive that is built using this API can run on earlier Windows versions, including Windows 8.1. I guess that I just need to install all Windows updates or need to i... | I have tested
OneDrive on Win 8.1 x64 Version 6.3 (Build 9600)
And OneDrive on Win 10 x64 Version 1909 (Build 18363.1082)
Windows 8.1 does not support offline files in the manner Windows 10 is doing. It just synchronizes all files from the server to the client.
I have also tried calling cloud filter API - it is not sup... |
63,963,869 | 63,970,371 | Binary Calculator subtraction | I am currently doing a project for my school which is about Binary Numbers. I have already made an addition Calculator which works fine and now I'm trying to make one for subtraction. There I'm facing some problems. The biggest one is that I get negative numbers as output and when I use the binary 2's complement I don'... | About the subtraction, I can see that you're only comparing the numbers bit by bit, and if one of the bits in the 1st number is 0 and the corresponding bit in the 2nd number is 1, it will just do 0 - 1 = -1, without considering the other digits of the number.
Adding a condition that changes the other numbers when the c... |
63,963,961 | 63,964,295 | What is the correct way to call std::to_chars? | I am trying to call std::to_chars on a double. My code doesn't compile on any compiler I have (gcc 10.2, clang 10.0.1).
Minimally reproducible code (or on godbolt):
#include <charconv>
#include <string>
int main() {
std::string str;
str.resize(30);
auto[ptr, ec] = std::to_chars(str.data(), str.data() + str.... | Your use is perfectly fine, and it compiles correctly under MSVC 19. As described in the Microsoft Docs for the <charconv> functions, this requires at least C++17.
As you can see for yourself in The GNU C++ Library Manual, Chapter 1. Status, C++ 2017, the last update regarding P0067R5 (Elementary string conversions, re... |
63,963,962 | 63,964,303 | How to initialize a generic base class in c++ | I am trying to rewrite some old code to make it more Object oriented. previously I have a union of struct called, say Event
union Event {
AEvent aEvent;
BEvent bEvent;
CEvent cEvent;
}
and this Event is later used in a struct
struct EventImpl {
... //some other members
Event event();
}
now I am trying to u... | There are many different ways to do that. First of all you may use std::variant as a more OOP-aware alternative to the union:
using Event = std::variant<AEvent, BEvent, CEvent>;
Another approach is to use dynamic polymorphism: you need to define a base class for all XEvent types:
class BaseEvent {};
class AEvent : pu... |
63,964,379 | 63,964,591 | How can I get a function to read the next line of a document everytime it's called? | Really new programmer with a really bad professor here.
I have this code that is supposed to get inputs from a text document (inputsFile) using a function (get_coefficients) and do stuff with it. Currently, everything works perfectly except it reads the same line from the file every time it's executed in the while loop... | The problem here is that when you do inputsFile.open() you're opening the file from the start. You should only open the file once so each time you read from it you'll read the next line from where you were the last time. However, the ifstream will be deleted at the end of the scope if you don't save it anywhere. What y... |
63,965,807 | 63,965,993 | How do I call function(void) in gdb | I am a complete beginner to reverse engg.
In recent times I have been going through gdb and how to debug the programss.
I have a big doubt bear me if it is a simple one
#include <stdio.h>
#include <stdlib.h>
int flag(void){
puts("okay you got this");
}
int main(void){
puts("nope try again");
}
So i compiled ... | You mean how to call flag() and skip the puts in main?, in this case:
(gdb) break main
(gdb) run
(gdb) print flag()
okay you got this
(gdb) break 10
(gdb) jump 10
(gdb) quit
|
63,966,075 | 63,966,196 | two sum(brute force with c++) issues with returning my array index numbers | So I decided to give the easiest problem on Leetcode a try and since I dont data structures well enough to use maps or hashtables I knew I was gonna have to go for brute force. I am getting this error when I try to compile and it is for my return statements.
Line 9: Char 29: error: expected expression
... | Seems like you were trying to create a vector with two elements in it, i and i+1. However the syntax you were trying to use, not sure where you got that from, but it was wrong.
To create a vector with elements defined, you would do something like:
std::vector<elementType> vec {element1, element2... };
So in your case,... |
63,966,391 | 63,966,485 | Compiling Hello World C++ Code in Visual Studio Code | I have a very simple hello world code as shown below:
#include <iostream>
int main()
{
std::cout << "Hello World!";
return 0;
}
I am trying to compile it in VSCode powershell terminal of Windows 10. I am using VS Community 2019.
Here is my directory structure:
When I do a cl triplex.cpp I get this:
but then... | As suggested by @d4rk4ng31, It executed using ./triplex. Thank you so much guys.
|
63,966,820 | 63,966,879 | Reading from a file and copying it's contents through command line | I want to read a file and copy it's contents to all the files that are passed as command line arguments
for example:
main.exe file.txt todo.txt app.txt foo.txt
Read data from file1 and copy it's contens to todo, app and foo. Prompt the user if the file doesn't exist and ask for input if he wants to create file.
The R... | This
while (input.at(0) != 'Y' || input.at(0) != 'y' || input.at(0) != '1')
is always true so your program always exits, you meant to write
while (input.at(0) != 'Y' && input.at(0) != 'y' && input.at(0) != '1')
It's a common error to get the logic wrong when combining negation with and or or.
And since the body of th... |
63,967,305 | 63,968,093 | take template basis on run-time value | I have an enum:
enum operation {
plus,
delete
//...
}
There is function, which has a run-time argument.
operation_do(plus);
And inside that function, there is a template-function call, which is based on a run-time argument.
Important: I can NOT make operation_do(), as a template function. This is the condition.
vo... |
And inside that function, there is a template-function call, which is based on a real-time argument. Important: I can NOT make operation_do(), as a template function. This is the condition.
This is the problem.
In C++ a run-time value (so a function argument, that can be a run-time value) can't be used as template pa... |
63,967,550 | 63,967,667 | Modify IP header from an UDP socket before calling sendto() | Hi I am currently learning socket programming with C++ and for testing purposes I want to modify the reserved bit in the IP header of an UDP package before sending data with the socket.
My current code looks like this:
if((sock_udp = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
perror("Socket error");
ret... | First, according to RFC 791 for IPv4 flags:
Bit 0: reserved, must be zero
So you should avoid changing that.
But if your application actually requires it, than you cannot use a typical SOCK_DGRAM, but instead you have to use a SOCK_RAW, which allows build your own complete packet. The main disadvantage is that you ha... |
63,967,746 | 63,968,098 | C++ functional bind - force cast of `this` to another class possible? | class A {
public:
function<void()> myFunc = bind(&A::f, this);
void f() {
}
}
In a separate class B I can point myFunc to another function, this time in class B, e.g.
class B {
public:
B() {
A* myA = new A();
myA->myFunc = bind(&B::newFunc, (B*)myA);
}
void newFunc() {
}
}
Thi... | just create an instance of the class you desire to use or pass it as a paremeter to the function in action.
|
63,968,695 | 63,970,737 | Find all of .exe files in program files folder | I am looking for something that help with my code. I just want to analyse my program files folder on windows and print all of .exe files in this folder. I wrote something but I need some help and after that I'll make the .exe files to button but this is not my challenge right now the first part is my issue :)
int dirLi... | this is working very well
#define _CRT_SECURE_NO_WARNINGS
#include <windows.h>
#include <iostream>
#include <string>
#include <shlwapi.h>
#pragma comment(lib, "shlwapi.lib")
HANDLE hFind;
WIN32_FIND_DATAA wfd;
int counter = 0;
int counter2 = 0;
int dirListFiles(const char* startDir)
{
HANDLE hFind;
WIN32_F... |
63,968,768 | 63,968,915 | Priority Queue Sorting Objects Incorrectly (User-Defined Compare) | I have a class Customer which has a member variable arrivalTime. I have defined a getter function getArrivalTime(). I am storing Customer in a priority queue, and have defined a custom predicate as follows:
class ArrivalQueueCompare
{
public:
bool operator()(const Customer &a, const Customer &b)
{
retur... | A priority_queue doesn't store the object in a sorted fashion. It only guarantees that the first element is the largest one (depending on your compare).
So, observing the objects stored in a non-ordered fashion in the storage vector is expected.
When you start popping the objects with pop(), you'll see the remaining ob... |
63,969,063 | 63,969,096 | How to encapsulate a class that is only being used inside another class? | Shown below is a rough structure of the program.
class Room
{
private:
Node* content;
public:
void someRoomMethod();
};
void Room::someRoomMethod() {}
class Node
{
private:
Node* nextNode;
std::variant<int, float> data;
public:
void someNodeMethod();
};
void Node::someNodeMethod() {}
As I ment... | Declarations of a nested class are parsed lexically (the same as at file scope). Simply move the usage of Node after the definition:
class Room
{
private:
class Node
{
// ...
};
Room::Node* content; // fine, Node is defined already
public:
// ...
};
Since Node is only used inside... |
63,969,646 | 63,969,732 | Is there a way to iterate this so I don't have to add every each function? | Is there a way to iterate this so I don't have to add every each function?
Lets say I have 4 planets and I want to add every gforcex to planet[1].forcex.
(this is from an n-body simulation project)
planet[1].forcex =
gforcex(planet[1].posx, planet[1].posy, planet[2].posx, planet[2].posy)
+ gforcex(planet[1].pos... | This is a great spot for std::accumulate.
#include <cmath>
#include <iostream>
#include <iterator>
#include <numeric>
using position_t = double;
using force_t = double;
class Planet {
public:
Planet(position_t x, position_t y)
: posx(x)
, posy(y)
, forcex(0)
{}
position_t posx;
... |
63,969,781 | 63,969,910 | map.find() returns seemingly randomly map.end() | I am using a custom comparator in a C++ map. Unfortunately map.find() often doesn't find the desired entry in the map.
Code to reproduce this is very simple:
#include <array>
#include <iostream>
#include <map>
using namespace std;
typedef struct DATA_t {
array<int, 4> data;
} DATA_t;
struct DATA_cmp {
bool opera... | Your comparison function is not correct. Consider what happens for the following keys:
{ 1, 2, 3, 4 } // #1
{ 1, 3, 2, 4 } // #2
Now comparing #1 with #2 will return true since the 2nd index is less (2 < 3). But, comparing #2 with #1 will also return true since the 3rd index is less (2 < 3).
This violates the requir... |
63,970,088 | 63,970,129 | How to replace this memcpy by a for loop? | I asked Why take the address of an array element like `&myArray[i]`? Bidimensional array and answers pointed out that I'm not doing the same thing in my loop:
memcpy(&mData[sampleIndex],
buffer,
(numSamples * sizeof(float)));
I did this for loop to replace it:
for (int... | memcpy copies bytes, so you need to multiply numSamples by sizeof(float). In the for loop variant, since every element of the array is a float to begin with, and the assignment operator (=) assigns a float on each iteration, you don't need to multiply by sizeof(float), and just use numSamples:
for (int i = 0; i < numS... |
63,970,157 | 63,970,220 | How to actually "clear" a vector in C++? | How to clear content in a simple way?
If I use vec_vec.clear(); only, there is still something in the vector that has not been cleaned up.
#include <iostream>
#include <vector>
int main()
{
std::vector<std::vector<int>> vec_vec(10);
vec_vec[0].push_back(1);
vec_vec[0].push_back(2);
vec_vec[0].push_back... |
vec_vec.clear();
for (auto i : vec_vec[0])
After this clear, vec_vec is empty, so the expression vec_vec[0] has undefined behavior.
Undefined behavior means anything at all might happen, and it's the fault of the program, not the fault of the C++ compiler, library, etc. So it might act like an empty vector, it might... |
63,970,173 | 63,970,326 | cin.getline : no matching function for call | In many answers and questions such as this one, it is recommended to use cin.getline from <string> and not getline(cin, variable):
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
cin.getline(name);
}
But in my case I have build issue:
g++ foo.cpp
foo.cpp: In function ‘int... | From the error told by the compiler, it is evident that there is no such function overload that accepts a type reference to std::string (for cin.getline()). Rather, it accepts parameters like:
const int MAX = 100;
char input[MAX];
cin.getline(input, MAX);
// Or better
// cin.getline(input, sizeof input);
|
63,970,417 | 63,978,868 | template instantiation and specialization order with subclasses | I'm trying to wrap my head around the order of instantiation and specialization of templates, especially in cases where subclasses are involved.
Please consider the following example:
class A {
int value() { return 42; }
};
class B {
double value() { return 3.1415; }
};
class MyBase {
public:
virtual int value()... | Miscellaneous reminder for the reader:
We cannot have specialization at class scope : demo
We cannot forward declare an inner class.
We can fully specialize en inner class (see cppref 6.)
First Solution :
We specialize the whole class, so we can have a specialize inner class. Live demo
#include <iostream>
#include <... |
63,970,546 | 63,970,798 | How do I marshal a structure containing a array of int of unknown size? | I have a c-structure that I want to return from a c-function to c# and that structure contains an array of int and a length. So basically
struct MyStruct
{
int *arr;
int size;
}
How should I allocate the arr in c to ensure that it can be freed in c#. And how do I decorate the corresponding structure in c# to make the... | You can't.
You should allocate and free memory by same runtime library.
|
63,970,647 | 63,971,165 | How to tell which functions are evaluated at compilation time? | I'm developing a physics simulation program doing a lot of maths. I'd like to know exactly which functions (or code parts) are evaluated at compilation time.
It there a way to tell?
I'm using clang, usually with c++14.
| The language has precise rules about which expressions are evaluated at compile-time, and which are not. The technical term for that is constant-evaluated, and there is in fact a utility called std::is_constant_evaluated that can be used to programmatically query whether a particular evaluation of an expression must ha... |
63,970,916 | 63,970,991 | How should I dynamically allocate string pointers in C++? | Hello, everyone!
I'm trying to dynamically allocate space for a string pointer in C++, but I'm having much trouble.
The code I've written is, partially, this (it's about RadixSort-MSD):
class Radix
{
private:
int R = 256;
static const int M = 15;
std::string aux[];
int charAt(std::st... | Use a std::vector. Change this
std::string aux[];
to this
std::vector<std::string> aux;
and this
void Radix::sortR(std::string a[])
{
int N = sizeof(a)/sizeof(std::string*);
aux = new std::string[N]; //Here is the problem!
sortR(a, 0, N-1, 0);
}
to this
void Radix::sortR(const std::vector<std::string>& ... |
63,971,959 | 63,972,279 | List of object in C++ | I trying to save write a list of objects. I don't know how to check if the created object was really saved, for now I try to test it by calculating the list size
void Hash::insertTest(Customer *cl) {
int index = hashFunction(cl->code); //OK
clientes[index].push_back(*cl);
int sizetable = sizeof... | No, already you did it :) Please check my comments and This source :)
void Hash::insertTest(Customer *cl) {
int index = hashFunction(cl->code); //OK
clientes[index].push_back(*cl);
int sizetable = sizeof(clientes)/sizeof(clientes[0]); /// I Think this is wrong.
cout << "size" << sizetable << endl; //prints 0,... |
63,972,145 | 63,977,047 | Conditionally enabled member functions in C++17 | Suppose types can have Foo, Bar, Baz methods, and we have type traits to check it. E.g. for Foo we have HasFoo:
template <class Type>
constexpr bool DetectFoo (decltype (std::declval<Type> ().Foo ())*) { return true; }
template <class Type>
constexpr bool DetectFoo (...) { ... | Your code is well-formed.
The linked answer refers to [temp.res.general]/8.1:
The validity of a template may be checked prior to any instantiation. ... The program is ill-formed, no diagnostic required, if:
— no valid specialization can be generated for a template ... and the template is not instantiated, ...
Here, t... |
63,972,404 | 63,972,473 | How to access the elements of arrays in a vector in C++? | I'm trying to find a way in C++ to have a dynamic size array (vector) in which I can store arrays of strings. This concept shall be used to store data with different labels, e.g.:
{"Car", "0", "0", "400"},
{"Person", "0", "1", "320"},
{"Bicycle", "1", "0", "300"},
...
After a bit internet search, I came this far:
stru... | You can try using std::array within std::vector
vector<array<string, 4>> list = {
{"Car", "0", "0", "400"},
{"Bicycle", "1", "2", "500"}
};
Then you can access the elements you want to access just like you want:
string str = list[0][1];
|
63,972,959 | 63,972,992 | Compare arrays in C++ | I'm having some issues comparing two arrays:
int array[3] = {23, 14, 1};
if (array == {12, 43, 1}) {
// Do something
}
The error I get is:
error: expected primary-expression before '{' token
if (array == {12, 43, 1}) {
^
error: expected ')' before '{' token
I also tried this:
bo... | This declaration:
bool compareArrays(int firstArray[], int secondArray[], int length) {
accepts pointers to ints. But you can't decay a brace-init list to a pointer.
Instead, the function can accept fixed-size arrays, and compare them with an algorithm:
template<size_t N>
bool compareArrays(int (&firstArray)[N], int (... |
63,973,423 | 63,973,540 | Template with Two Types Confusion C++ | I'm trying to make a simple template of creating an array class. However, I want to use two arguments: one typename and one int variable. I'm running into two errors and I'm not sure what I'm doing wrong. Here is my source which is simple and works.
int main()
{
Array<int, 7> tArray;
std::cout << tArray.getSize... | The offending code is here:
template <typename T, int S>
int Array<T, S>::insert(T val) {
Array<T, S>* temp = new Array[S];
temp = this;
return temp[val];
}
First, you create an array of Arrays, because you wrote an expression that looks like:
Type *var = new Type[count];
Then you change the pointer to th... |
63,973,728 | 63,976,879 | Setting argument for kernel extremely slow (OpenCL) | In my OpenCL Dijkstra's algorithm implementation, the slowest part by far is writing the 1D reduced graph matrix to the kernel argument, which is global memory.
My graph is a two dimensional array; for OpenCL it gets reduced to a 1D array like so:
for (int q = 0; q < numberOfVertices; q++)
{
for (int t = 0; t < num... | The error here is that your memory allocation is way too large: 5.76M vertices need a 133TB buffer because the buffer size is quadratic in vertex number. Neither the C++ compiler nor OpenCL will report this as an error and even your kernel will appearently start and run just fine, but in reality it does not compute any... |
63,974,255 | 63,979,943 | I need help understanding what the syntax of this particular if statement accomplishes | Im trying to follow along and break down a the source code for a pacman clone. There is an if statement that im confused about.
void PacMan::queueDirection(Direction dir)
{
if (!directions.empty())
{
if (dir == -directions.front()) //this statement
{
std::queue<Direction> clear;
... | The code you have pasted seems to have the following intent:
In case the Direction instance at the head of the queue, directions, is a negative of the value supplied as the argument of this function, the queue is cleared and the supplied argument is enqueued.
The type Direction in this case is an enum as defined in the... |
63,974,455 | 63,975,485 | Possible dynamic allocation issues | Right now i'm trying to get my code(simple POD containers) running as stable as humanly possible. My main concern is memory allocation and deallocation(new[] and delete[] operators). Is it possible to get any undesired behavior out of them(like SIGSEGV or exceptions)?
Here's a little test example i wrote:
class my_vect... | A new[] expression, by default, throws an exception if it fails (e.g. if a dynamic memory allocation fails).
If the constructor of any of the objects being constructed fails by throwing an exception, then the new [] expression will have the (net) effect of throwing that exception. Some other things also happen befor... |
63,974,530 | 63,981,873 | Problem when trying to rotate a 2D shape in a 3D space | i'm working on a batch renderer and i'm having trouble implementing a rotation feature for 2D shapes like a rectangle or a triangle. I'm using a Vertex* (struct Vertex code below) to store the position and color values, which works pretty well, until i got to rotations.
struct Vertex
{
glm::vec3 position;
glm::... | First, change your rotate functions to accept a vector as an argument, rather than apply the rotations to globals (or whatever those are).
Then instead of one vector:
r = {1, 1, 1}
use two:
r = {1, 0, 0}
s = {0, 1, 0}
Rotate them both (using the same angle arguments), then construct the square. (I don't know the synt... |
63,974,599 | 64,004,589 | QTableView, strech all section but the last one resize to content | My table consists of 2 columns: the 1st one stores some strings, the other contains a checkbox only. To make my table a little bit fancy I want to stretch the whole table to the width of its view.
Using
setStretchLastSection(true);
solves the 1st problem. The table looks better, but... OK... the last column is a bit l... | Here is the solution:
Disable the stretch option for the last column
setStretchLastSection(false);
Set a fixed width for the last column
setColumnWidth(1, fixedWidth)
Stretch the first column
setSectionResizeMode(0, QHeaderView::Stretch)
a bit fancy look
|
63,974,885 | 63,974,976 | how to set multiple sliders to be the same width | Basically, I have a QVBoxLayout with multiple QHBoxLayout. Inside QHBoxLayout I have a label and a slider. my layout looks like this:
But I want my sliders to look like this:
notice how the sliders start at the same position, but the text on the left is right justified.
| You have to use QGridLayout instead of QVBoxLayout + QHBoxLayout:
#include <QtWidgets>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget w;
QSlider *angleSlider = new QSlider(Qt::Horizontal);
QLabel *angleLabel = new QLabel;
QObject::connect(angleSlider, &QSlider::valueChanged... |
63,974,896 | 63,974,897 | Create MATLAB Array in MEX C++ from a std::vector | I would like to know if there is a more elegant way to create a MATLAB array from a std::vector than what I did and wrote below.
I found a simpler implementation in a question in the following Matlab forum, but the question still persists. MathWorks: Copying std::vector contents to TypedArray
I used buffers, based on t... | I wrote the question after hours of trying to figure things out by myself. But before submitting it, I gave it another hour. And I finally managed to do it. I'm posting the solution here in case it helps anyone.
As in the example in the question, supposing we have a std::vector of doubles V.
matlab::data::ArrayFactory ... |
63,975,351 | 63,984,509 | How would you auto generate a class implementation during pre-compile? | I was looking at creating a service locator that I would also like to provide "NULL" implementations of the services it provides. How would you go about parsing the Interface and auto generating an implementation? What tools would you use - say with CMake? Basically, I am trying to avoid having to write something li... | I think I figured it out. Write a small tool to do what I want, configure CMake to compile it first, and then have CMake run the tool with add_custom_command.
|
63,975,361 | 63,975,728 | Using 4 lists, create a list of all sums | I am beginner in C++ and have been trying to get an output of all the sums from 4 different lists of numbers. I want to know all the possible sums using up to 1 from each list. Repeats can be omitted.
For example with an input of [1, 2], [1, 3], [2, 3], [2, -1] should output [-1, 0, 1, 2, 3, ... 10].
My lists are 4, 6,... | The simplest mechanism would be to create an array of all possible sums, and then remove duplicates.
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<std::vector<int>> arrs = {
{7, 14, 21, 28},
{-10, -20, -30, -40, -50, -60},
{50, 90}
};
// Let's start with 0 in th... |
63,975,387 | 63,975,493 | C++ | overload operator << | std::map | I'm trying to overload operator << of a map within a struct, but getting a compilation error:
no suitable user-defined conversion from "std::_Rb_tree_const_iterator<std::pair<const int, int>>" to "std::_Rb_tree_iterator<std::pair<const int, int>>" exists
ostream& operator<<(ostream& os, const map<int, int>& neighbors... | You have a const map, hence begin returns a const_iterator, not an iterator. There is no defined operator<< to accept stringstream as a second argument, hence use its member function str, as follows
ostream& operator<<(ostream& os, const map<int, int>& neighbors)
{
string res;
map<int, int>::const_iterator it ... |
63,975,465 | 63,975,670 | Decltype(0.5) x = 5; makes x *Double* rather than *Float*. Why? | Wouldn't it be a waste of space to always go for a double no matter the floating point? AFAIK float is using 4B or 32 bits, and a double taking up 8B or 64 bits. Why wouldn't compiler be able to tell if the float would be enough?
| The type of 0.5 in C++ is double. If you want a float you need to say 0.5f . This is part of the definition of C and C++.
Implied in your question is some desire for automatic type selection based on the number of digits in the value, e.g. we could use float for 0.5 but double for 0.123456789. This is not a tenable ... |
63,975,831 | 63,975,973 | c++ creating string using char array | currently learning strings, i have the following cases :
string s;
s[0]='a'; s[1]='b';
cout<<s;
string s; s.clear();
s+='a'; s+='b';
cout<<s;
I get empty string as output from 1st example, and the 2nd works fine.
I get that the 1st is undef behavior and that we 'push' an element the second time instead of assigning a... | The operator [] returns a reference to the character at position pos in the string, it does reading value rather than insert and resize std::string.
You cannot insert to null assigned value, thats why you get undefined behaviour. First resize the string and then try to insert using [] the operator.
|
63,975,891 | 63,976,090 | Finding kth smallest element in an array using Binary Search Tree | The question is to find the "Kth" smallest element in an array.
https://practice.geeksforgeeks.org/problems/kth-smallest-element/0
Now I did see the given techniques but cannot understand them properly. My first intuition after seeing the question was to create a BST from the given array and use the InOrder Traversal o... | You simply cannot solve this question with BST.
Question cleary states that Expected Time Complexity: O(N).
But insert operation itself takes average O(logN), worst O(N).LINKYou are doing insert operation N times. Hence,
for(int i=0;i<n;i++){
cin>>el;
root = insert(root,el);
}
This code fragment already took O(Nlo... |
63,976,044 | 63,982,753 | Create a custom lightdm greeter | I am creating a custom LightDM-Greeter using docs provided by conical. The problem is that these docs do not specify the linking procedure of the lightdm library.
I am running Arch Linux x86_64. On querying using pkg-config --cflags --libs lightdm I get no results, Package lightdm was not found in the pkg-config search... | You don't need to link it (to the display manager program), once it has become a shared executable (which is something you need to check) it is completely linked.
To link it as a shared executable you need to add the -shared parameter to the compiler (this makes it a shared executable) and include all the .o files on i... |
63,976,551 | 63,976,657 | Incorrect char array length when using reinterpret_cast to store data with struct object | I'm trying to read .txt data (formatted with spaces) into a struct object. To simplify the question, say the .txt contains one record of a student's first name, last name, campus code, and id.
Here is the struct:
struct Student {
char f_name[10]; // John, followed by 6 spaces
char l_name[20]; // Fuller, followed by 14 ... | As your char array is not nul terminated, you have to display each character instead of the (decayed) const char*:
template <std::size_t N>
void print(const char (&a)[N])
{
for (auto c : a)
std::cout << c;
}
and then
Student student;
// init student
// ...
print(student.f_name); // instead of std::cout <... |
63,977,009 | 63,977,048 | Returning const reference to temporary behaves differently than local const reference? | I'm trying to get a better grasp of how lvalues and rvalues are dealt with as references, so I created this toy example:
#include <iostream>
struct Val
{
Val(int num) : num(num){};
~Val()
{
std::cout << "Destructing with value " << num << std::endl;
}
int num;
};
const Val &test(const Val... | Given const Val &foo = test(Val(5));, the temporary Val(5) will be destroyed after the full expression immediately, its lifetime won't be extended to the lifteime of the reference foo. It's not bound to foo directly, but bound to the reference parameter of test.
In reference initialization,
(emphasis mine)
Whenever a ... |
63,977,601 | 63,978,183 | core dumped error while inputting value in 2D vector | c++ code
#include<iostream>
#include<vector>
using namespace std;
int main()
{
int N;
vector<vector<int>> arr;
cin >> N;
for(int i = 0; i < N; i++)
{
for(int j = 0; j < 2; j++)
{
int a;
cin >> a;
arr[i].push_back(a);
}
}
return 0;
}
When I input value in 2d vector, I... | [Recommended] Simply do this : Ref. Range-based for loop
#include <iostream>
#include <vector>
int main() {
int N;
std::cin >> N;
std::vector<std::vector<int>> arr(N, std::vector<int>(2));
for (auto &&row : arr)
for (auto &&ele : row)
std::cin >> i;
}
The problem with your code is... |
63,977,730 | 63,977,830 | Static member in a template class. Same counter for all types of the class | I just want to access the static member of a template class. I know how to initialize it, but my problem is printing it for all types and not just for one type at a time.
The relevant parts of my code:
#include <iostream>
using namespace std;
template <class T>
class SortArr
{
private:
T* arr;
int size;
sta... | Each instantiation of SortArr gets its own set of static members, they are completely different types. If you want to have one counter for different types you can use a common base class:
struct Counter {
static int count;
};
int Counter::count = 0;
template <typename T>
class SortArr : Counter {
// ...
};
... |
63,978,029 | 64,667,546 | setup lldb debugging with cpp extension in vscode linux | I mostly use gdb for debugging c++ single files in vscode but now want to try lldb but i am facing issues while setting it up for vscode.
I first create default launch.json form debug tab selecting cpp gdb/lldb then clang++ for configuration.
When the debugging starts.. it shows following error:
then in launch.json I ... | lldb-mi is not part of the LLDB project. see lists.llvm.org
you can still build it yourself from the project's github repo. you will need to build LLDB/Clang/LLVM first, since lldb-micompilation requires headers and compiled libraries for the build to work as per information stated in the README.
|
63,978,071 | 63,978,314 | Linux API and C++ STD vector | How safe and correct is it to use a vector (vector unsigned char) instead of a character array (char []) when interacting with the file system using linux api (read,write)? Constructive criticism is needed. Are there any other alternatives?
I want to use this technique when writing a wrapper library (using classes).
Co... | Regarding your doubts and questions
How safe and correct is it to use a vector (vector unsigned char) instead of a character array (char []) when interacting with the file system using linux api (read,write)?
It's totally safe to use std::vector<uint8_t>, std::array<uint8_t,const_size>, std::string with API functions... |
63,978,326 | 63,978,513 | C++ Can you refer to the this pointer in a constructor or a destructor? | This is honestly just a general question, I have no code that requires fixing. I'm just curious as to whether or not you can refer to the this pointer in a constructor or a destructor.
A small example code would also be appreciated so I may follow along.
| Constructors and destructors both have access to the this pointer as do all other methods, except if they are static, (the methods I mean).
Example:
#include <iostream>
class C {
public:
int *a;
C() {
std::cout << "calling constructor\n";
this->a = new int(5);
}
~C() {
std::co... |
63,978,329 | 63,978,482 | Unable to assign a class member pointer variable | So I'm just playing around and created a simple class:
class C {
public:
C() {
}
void assign() {
*a = 10;
}
int * get() {
return a;
}
private:
int *a;
};
Then I create an instance of the class as follows:
C c{};
c.assign();
For some reason, the method assign doesn'... | You are causing an undefined behaviour by derefercing unallocated memory , You should add this to your class
C()
{
a=new int;
}
and
~C()
{
delete a;
}
|
63,978,470 | 63,978,684 | When creating a constructor in a derived class | When creating a constructor in a derived class,
Using the base class's private member variable,
Can it be given as an initial value for a derived class's constructor parameter?
class Base{
private: int m_Par;
protected: int m_Pro;
public:int m_Pub;
};
class Derived :public Base{
public:Derived(int m_Par... | Parameter is not the field. When you write parameter names to your derived classes constructor like Derived(int m_Par=1,int m_Pro=2,int m_Pub=3) it doesn't match with the fields. You are matching fields with the parameters in the function body if you want so.
If you want to initialize a private field in base class you ... |
63,978,501 | 63,979,017 | Why does my code enter into an infinite loop at the initial nested for loop on execution? | This code I am trying to right is for the Attribute parser question for the C++ program on Hackerrank.
The code is not complete yet as I am passing into this dreadful infinite loop again and again as im not able to solve it.
The code:
struct tag{
char name[100];
char att[100][100];
char val[100][100];
};
i... | In this condition:
line[j]!=' ' || line[j]!='>'
for any value of line[j], one of the conditions of the disjunction will be true. This leads to an infinite loop.
You are looking for:
line[j]!=' ' && line[j]!='>'
|
63,979,026 | 63,981,433 | C++ atomic acquire / release operations what it actually means | I was going thru this page and trying to understand Memory model synchronization modes. In below example extracted from there:
-Thread 1- -Thread 2-
y = 1 if (x.load() == 2)
x.store (2); assert (y == 1)
to which states that the store to 'y' happens-before the store to x in thread 1. Is 'y' v... | -Thread 1- -Thread 2-
y = 1 if (x.load() == 2)
x.store (2); assert (y == 1)
Naturally, compiler may change order of operations that are not dependent to boost performance.
But when std::memory_order_seq_cst is in action, any atomic operator works as memory barrier.
This does not mean variab... |
63,979,128 | 63,979,244 | How to include different number of objects at compile time with variadic arguments in the initializer list? | This is an extension of previous question (Link)
I need to include a different number of objects depending on the provided 'define' and with different ctor parameters. First parameter is an 'index' of object from zero and to (NUMBER-1), other parameters are optional.
So far I don't have issues when only single 'index' ... | It's difficult to give a full answer without a full example but... I see some problems in MakeArrayHelper()
First of all, the variadic pack of parameter has to be in last position, or the deduction fails.
So, instead of
template<typename T, typename... Args, typename TInts, TInts... I>
constexpr auto MakeArrayHelper(Ar... |
63,979,324 | 63,979,481 | Problem with setting values in my class's pointers array | I have created 2 classes ("MainWindow" and "przycisk"). In one of them (MainWindow) I have second class pointers array (przycisk *tab[33][33]). The problem is that when I want to change any value of this array, the program crashes). What am I doing wrong?
"Main Window" class:
class MainWindow : public QMainWindow
{
... | To allocate memory for tab array elements ;
for(int i = 0; i<33; ++i)
for(int j = 0; j<33; ++j)
tab[i][j] = new przycisk;
You can do this allocation in the constructor.
And also, do not forget the edit the destructor since you are using heap allocated data members.
|
63,980,002 | 63,980,048 | Why is my output in the form of 1.79214e-307 instead of a normal floating point number? | The sample output for member which is, works fine:
Please input a one if you are a member of the dental plan
Input any other number if you are not
1
Please input the service charge
7.89
Please input the test charges
89.56
The total bill is $97.45.
Whereas the sample output for non-member, gives me an output of 1.7921... | You are printing the wrong variable.
notmemtot = totalnot(servcharge, testcharge, medcharge);
cout << "The total bill is $" << membertot;
should be
notmemtot = totalnot(servcharge, testcharge, medcharge);
cout << "The total bill is $" << notmemtot;
But even easier (so you can't make the mistake you ma... |
63,980,141 | 63,980,384 | how to Pass start pointer of linked list as pointer in C++ | In C++ programming I was observing how pointers are passed in linked list implementation
here is my code:
#include<iostream>
using namespace std;
class Node {
public:
int data;
Node *next;
Node(int x) {
data = x;
next = NULL;
}
};
void traverse(Node *root) {
Node *ptr = root;
w... | To emphesis perrel answer you could do it like this:
void insert(Node** root) {
Node *ptr = new Node(10);
ptr->next = *root;
*root = ptr;
}
int main(void) {
Node *start = new Node(3);
start->next = new Node(4);
start->next->next = new Node(5);
traverse(start); // prints 3 4 5
alter(sta... |
63,980,146 | 69,317,775 | Can't choose C++ language standard in Visual studio 2019 | For some reason I cannot choose C++ language standard in Visual Studio. By saying that I mean next thing:
I can go to the properties and choose the language standard but Visual Studio doesnt see that. How did I came to that: I tried to include filesystem header with setting the C++17 standard set but then I saw that f... | I am simply adding the answer from the comments above since this helped me as well. Credit goes to Ted Lyngmo.
When changing properties, make sure either that the properties editing window is set to all configurations, or at least matches your current configuration (i. e., if you are on Debug x64, make sure those are t... |
63,980,892 | 63,980,943 | Why std::string seem to do something that std::is_convertible says isn't possible? | Why does std::to_string allow you to convert a double to std::string when std::is_convertible_v<double,std::string> is false? For example:
#include<iostream>
#include<type_traits>
#include<string>
int main()
{
std::cout << "If double is "
<< (std::is_convertible_v<double,std::string> ? "" : "not ")
<< ... | is_convertible is asking a very specific question about the language relationship between two types: can the source type undergo implicit conversion to the destination type? And std::string as a type has no implicit conversion into double, so the answer is no.
std::to_string is just a regular old function. It does not ... |
63,981,153 | 64,028,645 | `GLIBCXX_3.4.15' not found but it is there | I got the error
/usr/lib64/libstdc++.so.6: version `GLIBCXX_3.4.15' not found
/usr/lib64/libstdc++.so.6: version `GLIBCXX_3.4.14' not found
I have installed the following rpm file: https://centos.pkgs.org/6/nux-dextop-i386/chrome-deps-stable-3.11-1.i386.rpm because there are GLIBCXX_3.4.14 and GLIBCXX_3.4.15 versions ... | LD_LIBRARY_PATH should point to a path, not a library.
This should work for you:
LD_LIBRARY_PATH=/opt/google/chrome/lib:$LD_LIBRARY_PATH ./myFile.out -h
Alternatively,
export LD_LIBRARY_PATH=/opt/google/chrome/lib:$LD_LIBRARY_PATH
./myFile.out -h
Note this does not involve any symlinking nor replacing system librarie... |
63,981,325 | 63,981,338 | type deduction of function template in C++ | This is an example from C++ Primer. Chapter 16. Templates and Generics Programming
There's an example of nontype template parameters.
template<unsigned N, unsigned M>
int compare(const char (&p1)[N], const char (&p2)[M])
{
return strcmp(p1, p2);
}
compare("hi", "mom");
The author stated that
the compiler will use t... | "hi" is not a string, but a string literal, with the type char const [3]. Similarly, "mom" has the type char const [4].
The compiler simply uses this type information when doing function template argument deduction to deduce the array bounds of these string literal.
|
63,981,352 | 63,981,402 | How to return 2 indexes of a vector? | I'm writing this program to find 2 numbers in a vector (the vector isn't sorted), so that its sum equal to the target sum. This is my program:
#include <vector>
#include <algorithm>
using namespace std;
vector<size_t> find_numbers(const vector<int>& nums, int target)
{
sort(nums.begin(), nums.end()); // Sort the ... | std::binary_search simply returns a bool indicating whether the element you're looking for exists. There is no information returned about the location of this element.
Instead, the appropriate algorithm would be std::lower_bound which does a binary search, and returns the location of where the element you're looking fo... |
63,981,727 | 64,024,691 | No sound generated by SDL Audio Callback | I am trying to get a simple sinewave sound generation example working using SDL 2.0.12 on Windows 10, but no sound is being output.
I have no idea if it is a problem with the code or with the output device or the audio drivers.
I'd really appreciate suggestions of how I can debug the problem further.
#include <iostream... | It turns out there were two things I needed to do to solve this problem.
For a float type the sound wave can only take values from -1 to 1, whilst I was using a much greater volume boost. I needed to change
float audio_volume = 1.0f;
For Windows, the direct sound and winmm drivers give better sample lengths than wasap... |
63,982,548 | 63,982,665 | Writing a PGM file from a vector<unsigned char> | I am writing a program to manipulate PGM files by taking an input PGM, storing the data in a vector<unsigned char>, using the vector of data to create a new vector and so on and so forth until I use the last vector to create an output PGM file.
I've been taking it one step at a time, and I started with taking the input... | The input code looks wrong
int length = img.tellg();
char* buffer = new char [length];
img.read (buffer, length);
tellg is the current position in the file. That has no relation to the amount of data left to be read. Just read your data directly into your vector
vector<unsigned char> original(original_rows*original_co... |
63,982,989 | 63,983,024 | Easy way to iterate over a vector of pair of pair | Is there an easy way to iterate over a vector of pair of pair using auto?
I have a vector<pair<pair<int,int>, int>> vec and want to iterate something like.
for(auto [x, y,z] : vec)
but I am getting an error. Is there an easy way to do so?
for(auto [[x,y],z] : vec)
also gives an error.
| You can try something like shown below.
for (auto& it: vec) {
auto[x, y, z] = tie(it.first.first, it.first.second, it.second);
}
|
63,983,399 | 63,984,042 | How a double pointer fetch the value from a single poiner | An array is right now pointed by a single pointer. And a double pointer is pointing to the single pointer. I am trying to fetch the value of the array using this double pointer. As far I have only fetched the first index value of the array by the double pointer.
I know that if I dereference (*ptr2) a double pointer the... | Your reasoning is close, but you did not apply it well.
I know that if I dereference (*ptr2) a double pointer then it will give the address where the first pointer is pointed (ptr1)
In other words, *ptr2 is a synonym for ptr1. So any place you see ptr1 (after assigning ptr2 = &ptr1) you can substitute in *ptr2. Even ... |
63,983,592 | 63,983,840 | Changes in header files (C++) are ignored? | So recently I was working on my header files in C++ and something very strange came up. In my header files, I have my classes defined, here e.g. an audio player which uses an array of filenames to load sound samples:
#define NUM_WAVEFORMS 19
class AudioPlayer {
private:
const char _waveFileNames[NUM_WAVEFORMS][40]... | I think, the reason why cmake does not monitor changes of your file is that the file is not added to the target as dependency. You defined source_fles as a single cpp file. Add your header file to the source_file variable and any changes in the file will trigger recompiling.
|
63,983,852 | 63,984,218 | How do I create a vector in c++ with different row size? | For example, if I take n=9 inputs from the user.
inputs are = {2 3 1 1 2 5 2 7 8}
My vector should look like this:-
2 3 1 1 2
2 7 8
that is, a vector with 2 rows with different no. of elements in the rows. I want to skip adding 5 to my vector.
How can this be done?
Ideally it should not have any empty row. Eve... | Here are two solutions.
The first checks for the 5 and adds a row if certain criteria is met to determine if a new row is to be added.
The second solution adds a row if 5 is found, and at the end of the processing loop, erases all the blank rows.
Solution 1:
#include <iostream>
#include <vector>
int main()
{
std::ve... |
63,983,982 | 63,985,917 | How to automatically determine the CUDA block size and grid size for a 2D array? | how to determine block size and grid size automatically for 2D array (e.g. image processing) in CUDA?
CUDA has cudaOccupancyMaxPotentialBlockSize() function to calculate block size for cuda kernel functions automatically. see here. In this case, it works well for 1D array.
For my case, I have a 640x480 image.
How to de... |
Question 1 Can I calculate block/grid size using this method?
No.
It is important to remember than these API calls provide the occupancy maximizing number of threads per block and not the block dimensions. If you run the API twice in each direction, you will likely get an illegal block size when the two values are co... |
63,984,027 | 63,998,558 | How to search a linked list for a structure object | for this program I am not allowed to use vectors or std::.
I have a program called StudentList.cpp that uses a linked list class and a structure that stores the students' info from a file. The removeStudent function asks the user to enter a student ID number. I build a temporary Student object and search the linked lis... | Thank you for the update. You are calling a function which expects one data type, but passing it a different datatype. The compiler correctly rejects this because you gave it the wrong data type.
template<class TYPE>
class LinkedList {
public:
bool remove(TYPE& x);
};
template <class TYPE>
bool LinkedList<TYPE>::r... |
63,984,128 | 63,984,195 | C++: Why must I order my declaration as a double in this manner? | so one of my assignments was to make a program that converts currencies, this one below converts U.S. dollars to certain south american dollars.
I'm not sure why I can't declare a variable for US dollars along with the variable for the other currencies. I did it this way, and the program screwed up the conversion:
doub... | Expression in declarations are calculated immediately
The following statements initialize variables using an expression calculated immediately with dollars as it is know at that exact moment:
double pesos = dollars * 26;
double reais = dollars * 5.9;
double soles = dollars * 3.53;
It's not like Excel formulas that wou... |
63,984,163 | 63,984,373 | Getting an exception when try to use NTPClient in a custom class (ESP8266) | I'm getting an exception (see below) when I try to use NTPClient in my custom class RealTimeService. Please advise why and how to fix it. Thank you.
File RealTimeService.h:
#ifndef RealTimeLib
#define RealTimeLib
#include <NTPClient.h>
#include <WiFiUdp.h>
class RealTimeService {
private:
NTPClient _ntp;
NT... | You define udp in RealTimeService::_createNtpClient() and pass it to NTPClient. NTPClient will continue to need it after RealTimeService::_createNtpClient() returns, but udp will become invalid. Even if NTPClient copies it, its destructor is called, invalidating the resources it used.
You need to change udp to be an in... |
63,984,508 | 63,984,638 | Why does my code mess up with i++ and numsWon++ when the '++' operators are after? | I struggled with problem 1535 (Find the Winner of an Array Game) on LeetCode. I decided to use the top solution, which looked like this:
int getWinner(vector<int>& A, int k) {
int cur = A[0], win = 0;
for (int i = 1; i < A.size(); ++i) {
if (A[i] > cur) {
cur = A[i];
win = 0;
... | for:
if (++win == k) break;
The value of win is incremented by 1 first, and then is put though the comparison operator. It is the same as doing.
win = win + 1;
if(win == k) break;
where as when the ++ is after the win, it increments the value of win after the comparison like:
if(win == k){
win = win + 1... |
63,985,496 | 63,989,898 | 'CryptQueryObject' was not declared in this scope | #include <wincrypt.h> has already been added, so why does the GCC-mingw32 compiler report this error?
'CryptQueryObject' was not declared in this scope
I'm working on Window 10.
Here is my code:
#include <iostream>
#include <wincrypt.h>
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
//#pragma comment(lib,... |
Including wincrypt.h after windows.h otherwise it also report errors when compiling with Visual Studio.
Link crypt32.lib
Compile command like this:
i686-w64-mingw32-g++ test.cpp -lcrypt32
Edited code as below:
#include <iostream>
#include <windows.h>
#include <wincrypt.h>
#include <tchar.h>
#include <stdio.h>
//#pra... |
63,986,207 | 63,986,260 | Interpretation of '\0' in C++ | #include<iostream>
#include<string>
using namespace std;
int main(){
string i = "abc\0defg";
cout<<i<<endl;
// This prints "abc"
string x = "abcdefg";
x[3]='\0';
cout << x << endl;
// This prints "abcefg"
}
I know that the instance i of the C++ String class doesn't interpret \0 as the end ... | The string literal "abc\0defg" is a char const [9]. std::string doesn't have a constructor that takes an array, but it can accept a char const *. So when i is used with that constructor, it thinks that the \0 inside the string indicates the end of the string (which is in fact how the end of a char const * string is usu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.