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 |
|---|---|---|---|---|
61,726,808 | 61,728,246 | How to Populate the structure using a file(code attached below)? | I am trying to populate the structure using the file given at the bottom,please suggest some edits in the code so that I can print the structure as I have tried it in the main() function and this is my first time on stackoverflow,so pardon me for some errors I have made during posting this Question..
the file contents ... | Two things:
You need to actually call the table() function from your main() to invoke it before trying to print the contents of the structure. Otherwise, the structure (and any other variables in C) is initially populated with garbage values.
The printf() statements in your main() are not using the correct format spec... |
61,727,049 | 61,727,521 | How can i call inherited overloaded operator << and add more text in output in derived class? | i have base class Karta, and derived class Borac. In class Karta i overloaded operator <<, but in derived class(Borac) i want to call function operator<<() for base class and then add more text to the final output.
How to do that?
| To call a specific overload, you can cast the respective parameter to the type expected by that specific overload:
struct Base {
};
struct Derived : public Base {
};
std::ostream &operator << (std::ostream & o, const struct Base &b) {
o << "Base;";
return o;
}
std::ostream &operator << (std::ostream & o, co... |
61,727,262 | 61,727,311 | Plus operator on strings in c++ | Can you explain me the Exercise 1-2 from accelerated c++?
int main()
{
const std::string exclam = "!";
const std::string message = "Hello" + ", world" + exclam;
std::cout << message << std::endl;
}
Why is this not correct?
Changing the variable with "Hello" works fine.
Is it because of the fact that th... | The associativity of operator+ is left-to-right. Then "Hello" + ", world" + exclam is interpreted as ("Hello" + ", world") + exclam while "Hello" + ", world" is invalid. "Hello" and ", world" are const char[]s and could decay to pointer as const char* which can't be added.
Using std::string instead of c-style string, o... |
61,727,360 | 61,727,384 | how vector.empty() works? | i'm tying to check if a specific vector element is initialized...
i googled it and i found vector::empty
but it seems it doesn't work for me because it keeps returning true at any circumstances!!!
int main() {
int n, k;
cin >> n >> k;
auto tasks = new vector<list<int> *>(n);
tasks->insert(tasks->begin(), new list<int>)... | Because you are not calling std::vector::empty(), you call std::list::empty().
You insert 5 empty lists at the beginning of a vector, and then you call empty() on list at index 2.
Side note: Your vector is created with n lists and then you insert 5 more. Are you sure this is intended behaviour?
Also, using insert() is... |
61,727,390 | 61,733,120 | boost regex to match IF statements | I need to write a boost regex to match the following string and seperate it into three tokens depending on the parameters to the IF block
=IF(ISNUMBER(SEARCH("Windows",GETWORKSPACE(1))),ON.TIME(NOW()+"00:00:02","abcdef"),CLOSE(TRUE))
Ideally these should come to
token1 = "ISNUMBER(SEARCH("Windows",GETWORKSPACE(1)))"
t... | You need a simple parser.
Here's one with my favorite Boost swiss-army knife for quick parsers.
I've created a very flexible "token" grammar that honours (nested) parentheses and double-quoted string literals (potentially with embedded escaped quotes and parentheses):
token = raw [ *(
'(' >> -token_list >> ')'
... |
61,728,132 | 61,735,726 | Why is the return value of this `ctypes` wrapper function `c_long(0)` and not `c_long(3)`? | Why is the return value of this ctypes wrapper function c_long(0) and not c_long(3)?
// main.cpp
#include <iostream>
class AComplicatedCPPObj {
int *d_;
public:
explicit AComplicatedCPPObj(int *d)
: d_(d) {
}
int *getD() const {
return d_;
}
void setD(int *d) {
... | You created a temporary pointer to a temporary object in this line:
self.obj = lib.AComplicatedCPPObj_new(ct.pointer(ct.c_int(d)))
After this line executes, the pointer and c_int objects are both released. So you have undefined behavior. The pointer passed to the function no longer exists.
I don't know why you want ... |
61,728,234 | 61,730,239 | Call C++ function from inside dynamically loaded dll | I'm writing a C++ programm that dynamically loads a dll at runtime and calls a function within that dll.
Thats working fine but now i want to call a function defined in my C++ programm from within the dll.
My main.cpp looks like this:
#include <Windows.h>
#include <iostream>
typedef void(*callC)(int);
int main()
{
... | In your C++ program:
extern "C" _declspec(dllexport) void callableFromDll(int value) {
printf("This function was called from the main process. Value: %d\n", value);
}
In your DLL:
typedef void(*callableFromDll)(int);
callableFromDll func;
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_re... |
61,728,465 | 61,728,594 | Exception thrown: read access violation. this was nullptr in array of objects | I'm a CS student taking an OOP course and I don't know how to fix this issue. I understand that when the += operator tries to add the first element into the array, 'this' is nullptr and an exception is thrown, but I don't know how to fix it.
Shopping list header looks like this:
#include "Groceries.h"
class ShoppingLi... | These statements in the body of the operator
l1 = list;
list = l1;
do not make sense. After the first assignment statement there is a memory leak because the address of the allocated memory is lost. In fact these two statements are equivalent to this statement
list = list;
including the side effect of the overwriting... |
61,728,599 | 61,731,897 | Does this actually ensure that a number is between 1-9? | int position = 0;
void set_position() {
std::cout << "Player " << player << "'s Turn (Enter 1-9): ";
while (!(std::cin >> position)) {
std::cout << "Player " << player << ", please enter a valid number between 1 and 9: ";
std::cin.clear();
std::cin.ignore();
}
std::cout << "\n";
while (boar... | Too Long Didn't Read (TLDR)
That code only filters out non-numbers.
Explanation:
To help you understand, lets look at what actually happens inside
while(!(std::cin >> position))
On the inside of all that lies std::cin >> position. >> is the "extraction operator", so we're going to extract something from std::cin (sta... |
61,728,690 | 66,095,794 | Problem with setting pixels to OLED display 128x64 | So I had a class "SnakeGame" that handle my game.
I have another class named engine which is just a class the take the player input and setting pixels (a header file and main file):
void Engine::SetPixels(int positionX, int positionY, int sizeX, int sizeY) {
display.fillRect(positionX, positionY, sizeX, sizeY, WHIT... | The problem with my code is I had 2 arrays of char whose size was about 512MB each so the total was 1024MB. I used so much more rams than the Arduino have so it would freeze and stop working.
|
61,728,851 | 61,728,931 | Why the loop is not breaking and also the if condition isnt working as expected? | #include"std_lib_facilities.h"
int main()
{
int i = 0;
int len_password;
cout<<"How Long Should Be Your Password?\n";
while(i == 0){
cin>>len_password;
if(!cin && len_password > 15){
cout<<"Please enter an appropriate value:\n";
}
else{
break;
cout<<"success!";
}
}
}
I w... | You need to print "success" before breaking out of the loop. Also, your check for !cin doesn't make sense.
Instead, you could check if the cin operation failed, and if so, you can clear the stream to take additional input:
while(!(std::cin >> len_password) || len_password > 15)
{
std::cin.clear();
std::cin.ignore(... |
61,729,164 | 61,740,398 | Qt c++ dependent Comboboxes and dependent label | I have a data.csv file with 2 columns. The first column contains some country names and the second column contains the capital of each country. In my user interface there is a combobox containing the names of the countries and next to it there is a label. What I want is to choose a country from the combobox and the lab... | You have 2 fields, the first is the country and the second is the capital, so I think that the best way is to map both in the QComboBox item by using QComboBox::currentData:
const QStringList fields = linetext.split(',');
// Set the item text (displayed), and the itemData (capital)
ui->combobox->additem(fields.first()... |
61,729,165 | 61,736,776 | Using static constexpr member array as pointer in template parameters | The following main.cpp illustrates the problem:
#include <type_traits>
template <class T, std::size_t N>
struct Array
{
T data_[N];
};
template <const std::size_t* EltArray, std::size_t EltCount>
struct Foo
{
};
int main()
{
// SIDE NOTE if arr is not declared static: the address of 'arr' is not a valid tem... | I want to share the answer i just found in open-std and a compliant solution.
We all know that we cannot pass any variable as non type.
Did you know that we can pass a const reference to anything we want ?!
So the solution is:
#include <array>
// When passing std::array<std::size_t, EltCount> (by value), i get the err... |
61,729,611 | 61,761,049 | cmake mingw-w64: strange error when trying to build | I have installed MinGW-w64 and built a simple Hello World Program. But the second time I run cmake --build . a strange error occurs.
When the Path variable is set to C:/MinGW/bin everything is fine and works. But when I set the Path to C:/msys64/mingw64/bin this happens:
PS C:\repos\hellovs\build> cmake ../ -G Ninja
--... | It's a GCC bug.
MSYS2 maintainers decided to not wait for the upstream and patched it.
Run pacman -Syuu from MSYS2 shell to update your packages.
|
61,729,747 | 61,729,991 | How to write regexp which will validate the following strings? | I have tried following regexp in cpp ^((T[X-Z]|R[X-Z])+?)(?:,\\s*|$). It validates only TX. If empty string it should be invalid, it should not accept numbers as well
User may enter:
TX
TX, TY
TX, TY, TZ,
RX, RY, RZ
RX
It should be valid in all cases.
| For the test cases that you put here,([TR][XYZ])(,( )?)? might work.
I have tested it for you here (Mention that global and multiline flags are enabled)
|
61,729,816 | 61,729,998 | the scope and priority of variable in c++ | Could anybody explains to me why the result is 2, which x is using and why.
auto x = 0;
int f(int i){
auto x = 1;
{
static auto x = 0;
x += i;
}
return x;
}
int main() {
cout << f(1) + f(2) <<endl;// result 2
return 0;
}
| In fact this function
int f(int i){
auto x = 1;
{
static auto x = 0;
x += i;
}
return x;
}
can be rewritten like
int f(int i){
auto x = 1;
return x;
}
because the static variable x declared in this block scope
{
static auto x = 0;
x += i;
}
is not used outside the bloc... |
61,729,844 | 61,730,032 | Vector Subscript out of Range. Comparing Elements of Vectors | So I have a vector like this
All_Pos={0,10,15,24,30,33,66}
And three smaller vectors that contain the numbers from the previous vector, let's say
Vec_Lin={0,15}
Vec_Circ={24,33,66}
Vec_Arc={10,30}
I want to make something like this:
All_Pos[0]=Vec_Lin[0]? YES -> Do something
All_Pos[1]=Vec_Lin[1]?No
All_Pos[1]=V... | You should check for out of range. [] operator works ,when indexing is in limits from '0' to vector.size().
void process_vector(void)
{
std::vector<int> All_Pos = { 0,10,15,24,30,33,66 };
std::vector<int> Vec_Lin = { 0,15 };
std::vector<int> Vec_Circ = { 24,33,66 };
std::vector<int> Vec_Arc = { ... |
61,730,209 | 61,730,279 | C++11: How to access base class member in a derived class? | In a C++11 program I'd like to access the member b2 of a base class
Base in a derived class Derived like so:
struct Base
{
const int b1 = 0;
const int b2 = 0;
Base (int b1) : b1(b1) {} // ok
};
struct Derived : public Base
{
Derived (int b1, int b2) : Base(b1), b2(b2) {} // error
Derived (int b2) :... |
How to access base class member in a derived class?
You can access the base class members either through this pointer or implicitly by using the name unless it is hidden.
like so:
Derived (int b1, int b2) : Base(b1), b2(b2) {} // error
While the derived class can access the members of the base, it cannot initialis... |
61,730,307 | 61,731,064 | Node.js native addons: where is node_api.h located? | I'm trying to create a native addon for Node.js and when I include
#include <napi.h>
The Intelli Sense of VS Code says that it cannot detect where node_api.h is located (it's included by napi.h).
node-gyp build works well and it compiles. But I do not understand where is that header in the system and where node-gyp g... | I have run a full search on disk C (I'm on Windows 10), and found out that the header file node_api.h is located in
C:\Users\<UserName>\AppData\Local\node-gyp\Cache\<NodeVersion>\include\node
as well as other headers like v8.h.
If you delete that folder, node-gyp build no longer works. node-gyp configure downloads all... |
61,730,410 | 61,730,685 | Complexity of adding new element to std::list | What is a complexity of inserting new element in STL list using insert() method? Is it always O(1)? If not, what depends on it? Can we say that adding new element to the list using push_front() and push_back() is always very fast with complexity O(1)?
|
What is a complexity of inserting new element in STL list using insert() method?
O(1).
Is it always O(1)?
Yes. Always.
Can we say that adding new element to the list using push_front() and push_back() is always very fast
Maybe. "Very fast" is subjective. It probably isn't as fast as pushing to the front of std::... |
61,730,423 | 61,730,529 | Implicit move constructor shall be noexcept if possible | Basically per the standard:
An inheriting constructor (12.9) and an implicitly declared special member function (Clause 12) have an exception-specification. If f is an inheriting constructor or an implicitly declared default constructor, copy constructor, move constructor, destructor, copy assignment operator, or move... |
Is there something I am missing?
Yes. const
The member Foo::stringField is not std::string, it is const std::string. const std::string is not nothrow move constructible1, and therefore the implicit move constructor of Foo is neither.
1 Const rvalue cannot bind to a non-const rvalue reference, so move constructor will... |
61,730,919 | 61,895,665 | attaching callgrind/valgrind to program in mid-way of its execution | I use Valgrind to detect issues by running a program from the beginning.
Now I have memory/performance issues in a very specific moment in the program. Unfortunately there is no feasible way to make a shortcut to this place from the start.
Is there a way to instrument the c++ program ( Valgrind/Callgrind ) in its mid-... | Thanks all for help.
Seems It's been already answered here: How use callgrind to profiling only a certain period of program execution?
but not marked as answered for some reason.
Summary:
Starting callgrind with instrumentation off
valgrind --tool=callgrind --instr-atstart=no <PROG>
Controling instrumentation ( can ... |
61,731,545 | 61,731,945 | Makefile of multiple programs rebuilds everytime although recipe 'all' is marked as phony | The problem is as described in the title. Every time i type make, even if no chagnes are made to the code, these commands are being run
g++ -o ./bin/prog1 ./obj/prog1.o -I./include
g++ -o ./bin/prog2 ./obj/prog2.o -I./include
Makefile is located at the root of the project folder and the rest of the files are in the in... | Marking all as .PHONY means that the target will always be considered dirty and its recipe will be re-evaluated.
If you don't want that, move the two programs into explicit targets:
$(BINDIR)/prog1: $(OBJ1)
$(CC) -o $@ $^ $(CFLAGS)
$(BINDIR)/prog2: $(OBJ2)
$(CC) -o $@ $^ $(CFLAGS)
all: $(BINDIR)/prog1 $(BINDI... |
61,731,637 | 61,761,006 | Broken CXX compiler error on cmake when building aws-sdk-cpp for iOS | I want to build static aws libs core, s3 and transfer for iOS which i downloaded from this link. I am using macOS High Sierra 10.13.6 and Xcode 10.0.
I am trying to run cmake on the source from the link with this command:
cmake ../aws-sdk-cpp
-DCMAKE_C_COMPILER=clang
-DCMAKE_C_FLAGS="-mios-version-min=11"
-DCMAKE_C... | After downloading the aws source, try with older version like:
git checkout 1.7.9
|
61,731,997 | 61,733,459 | How to generalize variadic function fn<S, ...Args> to fn<S0, ...Args0, S1, ...Args1, ... , SN, ...ArgsN> | Assume there is variadic function template<typename... Args> foo(const S& s, Args... args).
struct S {};
template<typename... Args>
void foo(const S& s, Args... args);
void check_foo()
{
S s0{};
S s1{};
char a0 = 0;
short a1 = 1;
int a2 = 2;
foo(s0, a0); // OK
foo(s0, a0, a1); // OK
foo(s1, a1, a2)... | Something along these lines:
template <typename... Args>
void bar(const S& s, Args... args);
template<typename Tuple, std::size_t... Is>
void call_foo(const Tuple& t, std::index_sequence<Is...>) {
foo(std::get<Is>(t)...);
}
template<size_t nextS, typename Tuple, std::size_t... Is>
void call_bar(const Tuple& t, st... |
61,732,062 | 61,732,505 | C++17 if statement with initializer, initializer assign nullptr, how to handle condition? | I am trying to use C++17 if statement with initializer in real code, but below code behavior makes me confused with this new feature.
#include <iostream>
struct call
{
public:
bool isLive()
{
return true;
}
};
call* createCall()
{
return nullptr;
}
int main()
{
if (auto call = createCall(... | You would get the same undefined behavior without the if:
auto call = createCall();
call->isLive();
This only appears to work, because the method is not actually using the this pointer (but in any case it is wrong).
In
if (auto call = createCall(); call->isLive())
the auto call = createCall(); is not part of the con... |
61,732,103 | 61,732,310 | Blake2b hash native C library usage | I am trying to use the native C library in my project (this one https://github.com/BLAKE2/BLAKE2) but it's not clear to me how to use it: it seems to be possible to use a step-by-step version (blake2b_init, blake2b_update and blake2b_final) and simpler one (blake2b).
Here (https://www.rfc-editor.org/rfc/rfc7693#appendi... | The problem is that you are asking blake2b() to produce 128 bytes of output, while the maximum it can produce is only 32 bytes. There's an enum for that in the header file: BLAKE2B_OUTBYTES. So write:
const char *pInput = "test text";
char *pOutput = new char[BLAKE2B_OUTBYTES];
int nRes = blake2b(pOutput, BLAKE2B_OUTBY... |
61,732,171 | 61,732,354 | Pass Integer array from C++ to Python using IPC/Shared memory | what is the best method to pass a int C++ Array to a python program using shared memory? for example i've array as defined:*
int arr[100];
for(int i =0;i<100;i++) {
arr[i] = i*2;
}
and i would get on python program:
[0,2,4,6.... 200]
?
Thanks
| You can always create a python module using pybind11 and create a function that exposes the array content.
pybind11 tutorial to get an idea of the complexity:
https://bastian.rieck.me/blog/posts/2018/cmake_cpp_pybind11_hard_mode/
|
61,732,481 | 61,737,692 | how to change label color when intersecate with an image in qt? | I have a Qlabel with white text on a black background. In this screen i create a white rectangle which change dimension, through:
QGraphicsRectItem* rect;
rect->setRect(0, START_HEIGHT, 0+variable, HEIGHT);
By calling a function which modify the value of "variable" and recreate the rectangle,I change its size.
This re... | You can create your own implemention to change the QPainter::compositionMode() of your item:
class TextItem : public QGraphicsTextItem
{
public:
TextItem(const QString &text, QGraphicsItem *parent = nullptr)
: QGraphicsTextItem(text, parent){ setZValue(100); }
TextItem(QGraphicsItem *parent = nullptr)
... |
61,732,643 | 61,733,085 | Using static_cast correctly in MFC | Changing this code was straightforward:
This:
S_COPY_PACKET* pCopyPacket = (S_COPY_PACKET*)(pCopyDataStruct->lpData);
Becomes:
S_COPY_PACKET* pCopyPacket = static_cast<S_COPY_PACKET*>(pCopyDataStruct->lpData);
But what about this line:
if (SendMessageTimeout(hOtherInstance, WM_COPYDATA,
NULL, (LPARAM)... | In your first code snippet, the lpData member of the COPYDATASTRUCT is a void* type, so you can static_cast it to a pointer to (almost) any other data type. However, you cannot use static_cast to convert between a pointer (&cds) and non-pointer (LPARAM) type. You need reinterpret_cast (but only one):
if (SendMessageTim... |
61,732,705 | 61,732,883 | How to unpack tuple with unknown size? | Given,
template<typename T>
void foo(T t)
{
std::tie(/*xxx*/)=t;
auto &[/*yyy*/]=t;
}
int main()
{
foo(forward_as_tuple(1,2,3));
foo(forward_as_tuple(1,2,3,4,5));
}
I want foo() to unpack the tuple that's passed to itself.
Can decomposition declarations with auto or std::tie(), handle the unknown tuple... |
How to unpack tuple with unknown size?
auto &[/*yyy*/]=t;
You can't.
maybe all elements could be pushed back to a vector of that type
Use std::apply:
std::vector<int> baz;
std::apply([&baz](auto... args) {
(baz.push_back(args), ...);
}, t);
|
61,733,179 | 61,734,903 | How can I detect the end of an array? | I written a class, in which I gave a Pointer to the first element of an array. I don't know the size of this, but I need to know when I have the last Element.
At the moment I give an extra variable to the method, which contains the size of it. and I want to remove it.
My Method:
#define NOP //__asm__("nop\n\t")
//Setu... | There is no other way, then to pass the length information to the function. The pointer to array shows to the start, but doesn't have the length 'attached'. You can pass the length as parameter, as a member of a struct or class object or as global variable. Or you can use some library which has a struct or class to bun... |
61,733,522 | 61,733,918 | Recursive calls when the condition is doubled | Here is the question: This program repeats the if condition twice; how will the recursive calls work inside each if block is what seems a little bit not that simple.
I am trying to understand if the execution from the first recursive call will jump to the second if block or if for every value of c, there will be anothe... | A recursive call like a non recursive call, the called function starts from its beginning.
If the compiler detect the recursive call is terminal the new call is not added in the stack but replaced by the equivalent of a jump (but still going at the beginning except few instructions about the stack management). Your sec... |
61,733,581 | 61,737,687 | Is std::list circular? | Is the std::list a circular doubly-linked list? Using it I can the the following:
#include <list>
int main(){
std::list<int> l = {10, 11, 12};
std::list<int>::iterator it = l.end();
it++;
std::cout << *it << std::endl; // prints 10
}
| There are actually two levels to this question:
The language standard semantics answer
This answer has already been given by Bathsheba, which is basically that the prescribed behavior of an std::list<> does not include any circularities. When you increment the iterator past the end of the list, you enter the territory... |
61,733,667 | 61,733,955 | C++ Class functions into groups | I am just here to ask if there's any way to group class functions in C++ into different "subgroups". (SerialPort functions, DataManagement functions, Encryption functions, ...)
I would like to use object to call that function from some "group" (I don't know how to call it)
For example saving current bool would be obj.s... | You could do it by making a separat class for each group and multiple inheritance them
class MultiResponsible : public SerialPort, DataManagement, Encryption {
...
}
That way you are on a the way to Single Responsibility principle.
|
61,734,265 | 61,734,480 | Does map store elements as std::pair? | Does std::map store elements as std::pair? Iterating over map looks like this:
#include <map>
int main() {
std::map<int, char> m;
m[1] = 'A';
m[2] = 'B';
m[3] = 'C';
std::map<int, char>::iterator it;
for(it = m.begin(); it != m.end(); it++)
{
std::cout << "Key: " << it->first;
... | No, std::map doesn't store data as pairs, it just exposes it as pairs. Although it's not forbidden to use std::pair in underlying storage.
In typical red-black tree implementation you need at least two pointers to children nodes on top of key and value stored (and probably a pointer to parent node, I don't really remem... |
61,734,461 | 61,734,563 | LawOfCosines solving for c, but getting odd answer | I have been trying to code a program that can solve for c using the Law Of Cosines. The program runs correctly, but the answer I get is ridiculously big, noted by how it was in scientific notation.
Here is my code:
#include <iostream>
#include <cmath>
using namespace std;
class TrigMath
{
private:
double a;
... | The cos() function there takes input as radians not as degrees.
Try to convert degrees to radians and then supply it as input.
In the class functions seta, setb and sety you have written A = a, B = b and Y = y.
You have to change them to a = A, b = B and Y = y.
So after applying all the changs the code should be like
... |
61,734,491 | 61,738,052 | printf data type specifier complex question | printf("\e[2J\e[0;0H");
What does this line mean?
Can I know what to learn and from where to understand this statement?
| "\e" as an escape sequence is not part of the C standard.
A number of compilers treat the otherwise undefined behavior as a character with the value of 27 - the ASCII escape character.
Alternative well defined code:
//printf("\e[2J\e[0;0H");
printf("\x1B[2J\x1b[0;0H");
printf("\033[2J\033[0;0H");
#define ESC "\033"
p... |
61,734,543 | 61,734,798 | Is there a possible way to return a for loop result into function like ternary operator? | We've seen so far that how a ternary operator works:
return (x == y) ? x : y; ' If x equals to y, then return x, otherwise y
The alternative code could be written as follows:
if (x == y)
return x;
else
return y;
The question is, is this possible to return the sum of N numbers using a return statement with For... | Use recursion. The tail recursion will be optimized for stack usage.
int forLoop(int x) {
return x < 1 ? 0 : (x + forLoop(x - 1));
}
|
61,734,872 | 61,735,305 | Overloading operator+ for linked lists | I'm a beginner and now I am trying to implement the class linked list which contains the function begin().
The function return well the first element in the list, but what i am trying to do is to return the iterator on the next position, for instance something like this:
List<int>::iterator iter2 = a.begin() + 2; // or... | Let's take a look at your begin function:
typedef Node<T>* iterator;
iterator begin() {
...
}
This function returns a Node<T>*, a pointer to a Node<T> object. As a result, when you write
list.begin() + 2;
C++ interprets this to mean "I've got a pointer, and I've got a number, so I'll step that pointer forward the... |
61,735,093 | 61,737,015 | Can .EXE use symbols from an indirectly imported DLL? | I have a Sample.exe project that depends on Common.dll . I need to use libcurl.dll in both Sample.exe and Common.dll . Do I need to import libcurl.lib into both Sample.exe and Common.dll , or will the .EXE module be able to use libcurl.dll if it's imported by Common.dll .
So far in my experiments I'm getting "unresolve... | No, it cannot. The linker doesn't search through the dlls you import for symbols from other dlls it itself imports, nor does it resolve this kind of indirect importing. You'll have to link with libcurl.dll as well.
|
61,735,153 | 61,741,174 | How can I save a python function to a static c++ container using pybind11? | Essentially, on the C++ side I have a container that holds a certain type of function. Now I would like to expose this container to python with the possibility for the users to provide their own python functions.
The simplest example would look like this:
#include "pybind/common/Common.h"
using CppFunc = std::function<... | static std::vector<CppFunc> vec{} stores references to python objects (user functions) which never get released due to static storage, therefore interpreter cannot terminate.
To ensure interpreter termination you can call a cleanup function at module termination:
#include "pybind11/pybind11.h"
#include "pybind11/funct... |
61,735,315 | 62,763,280 | Can't build RDCOMClient using rtools40 and R 4.0 | A while back, I created a fork of the RDCOMClient package to keep it working with R 3.6 (https://github.com/dkyleward/RDCOMClient). People are now running into issues again because it won't work with R 4.0. The problem doesn't seem as easy to fix, and I'm hoping for some help.
If I flip Rstudio back to R 3.6 (and rtool... | Rik's answer was incredibly helpful and got a version working; however, after spending a day on it, I was able to improve on it. I want to put that here in case I have to do it again. The main improvement is being able to build a working package for both 32- and 64-bit architectures. By default, R installs both, and th... |
61,735,349 | 61,736,380 | Handle no value option in Config file in Boost program_options | This question has been already been asked here before - Boost parse_config_file, empty key value. But since there was no proper solution provided there, I am asking this again hoping someone could provide a better solution.
Unlike the above question, In my case, the code is not throwing the Boost Error:
boost::program_... | UPDATE Initial answer got the wrong idea. Here's the update.
So you want foo= (without a value) to behave as if the line wasn't even in the config.
That means that the default value semantics (i.e. what happens when notifying - which migrates state from the Parser Component to the Storage Component) aren't good.
You co... |
61,735,609 | 61,735,625 | implicit instantiation of undefined template "std::__1::basic_istringstream<char, std::__1::char_traits<char>, std::__1::allocator<char> >" | I am learning C++ and following a tutorial, but got issue with building the code in the starter code.
Here's the source code file where this error is being thrown.
#include "linux_parser.h"
#include <dirent.h>
#include <unistd.h>
#include <istream>
#include <string>
#include <vector>
using std::stof;
using std::str... | You need #include <sstream> in order to use std::istringstream.
|
61,735,649 | 61,735,790 | Segmentation fault (core dumped) error after running compiled a.out | I'm writing code that should replace choosen word in text to "*". Dont know that's work but when I'm running compiled file a.out there is Segmentation Fault error. Any help pls?
bleep.cpp
#include <iostream>
#include <string>
#include "functions.hpp"
int main() {
std::string word = "broccoli";
std::string text =... | Hope this helps : Check for i too in the while condition and positions of i as in your case it kept on incrementing because you had used the same i to move forward.
#include<bits/stdc++.h>
using namespace std;
void looking_for(string &text, string word)
{
for (int i = 0; i < text.length();i++)
{
int ... |
61,735,688 | 61,738,360 | Is There a replacement of DirectShow? | I want to make a virtual web cam application. so I find out all pages that had written before 2010.
But there was no result. All the projects are old even I open and some parts of methods of codeproject's sources is doesn't useful now.
So I'm looking for a replacement of DirectShow. I tried following directshow guide e... | So this is an AB question: you need one thing and instead you ask for another.
Yes, there is replacement for DirectShow. DirectShow is a previous multimedia API in Windows, and its successor API and current API in Windows is Media Foundation. This will however get you not an inch closer to the solution of your original... |
61,735,878 | 61,736,070 | C++ count the number of words from standard input | I saw a piece of C++ code to count the number of words inputted from standard input:
#include <iostream>
#include <iterator>
#include <string>
using namespace std;
int main() {
auto ss {
istream_iterator<string>{cin}
};
cout << distance(ss, {}) << endl;
return 0;
}
I have several questions:
... | auto ss deduces ss to be std::istream_iterator<std::string>, because that is what the full statement is constructing and assigning to ss.
istream_iterator uses the specified istream's operator>> to read formatted input of the specified type, where operator>> reads input delimited by whitespace, including space characte... |
61,736,084 | 61,849,496 | Passing 'const franka::Robot' as 'this' argument discards qualifiers [-fpermissive] robot.loadModel(); | I am using a library provided by a robot manufacturer to read the numerical robot model and control it in real time. There are two cpp (1, 2) files and a header in order to be able to read the robot numerical model.
In one of the examples provided by the company, the object robot of the class franka::Robot is defined a... | The answer to this question is that the object robot is constant and therefore, its methods can not be accessed in the control loop. Instead, we can define a static variable and call the methods inside the loop.
static franka::Model model(robot.loadModel());
Inside the control loop:
model.mass();
|
61,736,254 | 61,736,719 | Weird behavior in function overload resolution with const keywords for template arguments | So I have been reading Programming Principles and Practices in C++ by Bjarne. And the section on conversion of templated objects of base/derived classes got me kinda confused. So I tried to try out different combinations and stumbled on something weird
#include <iostream>
class A {
public:
int i;
};
class B : pu... | Yes, const A* and A* const are very different things, and that's why your conversion operator Array_ref<const Q> cannot fulfill a parameter of type Array_ref<const A*>.
If Q = A*, then const Q = Q const = A* const.
|
61,736,333 | 61,736,463 | C++ how to instantiate std::array inside a class constructor? | I want to have a big container (specifically a std::array) the size of which I know at compile time but which I can specify from the constructor.
I have been able to do the first part: i.e. a std::array which a size specified at compile time. Schematically:
// hpp
constexpr int my_size = 100;
class C
{
std::array<i... | Changing the extent (size) of std::array would change the size of the object containing it -- since the array elements are stored contiguously in the object rather than indirectly (e.g. via pointer).
A class' type must be "complete" in order for a constructor to be called -- and for a class to be "complete", it must b... |
61,736,386 | 61,738,431 | C++ String excercise with random numbers | I have to do this excercise:
A common punishment for school children is to write out the same sentence multiple times. Write a C++ stand-alone program that will write out the following sentence one hundred times: “I will always use objectoriented design.” Your program should number each of the sentences and it should ... | I've made the entire program for you:
#include <iostream>
#include <ctime>
void selectionSort(int[], int);
int main(void)
{
std::string punishStr = "I will always use objectoriented design."; // declaration
std::string tempStr = punishStr;
std::string typoStr = "TYPO";
int length = punishStr.length();... |
61,737,209 | 61,737,557 | Exception thrown: read access violation. _Pnext was 0x148F854. (C++ Destructor Error) | case 4: // ---------------------------------------- Delete Customer
cout << "Enter your Customer ID:" << endl;
cin >> exist_id;
for (int i = 0; i <= cnum; i++) {
if (c[i].C_ID() == exist_id) {
cc = 't'; // check to set custo... | Destructors in C++ are called by default when the object dies/destroys to handle the not needed allocated memory for the first place and it shouldn't be called anywhere else.
In your case, I think that the best practice to do is to create a member function delete_customer in customer class that has the exact code in th... |
61,737,267 | 61,737,582 | Append data to array in C++ | double b[3] = {3,3,4};
for(int i=0;i<3;i++) {
cout<<b[i]<<" "<<endl;
}
int sum = 0;
for(int i=0;i<3;i++) {
sum += b[i];
} cout<<"\n"<<sum<<endl;
for(int i=0;i<3;i++) {
double norm_b = b[i]/sum;
cout<<norm_b<<endl;
}
Result:
0.3 ... | Thank you guys
Solved
Update:
#include <vector>
vector<double> vec;
for(int i=0;i<3;i++) {
vec.push_back(b[i]/sum);
cout<<vec[i]<<endl;
}
|
61,737,313 | 61,750,488 | How to map different function signatures into the same std::map? | I had some issues which were pointed in the comments, so this is my new minimal reproducible code sample;
#include <functional>
#include <iostream>
#include <vector>
#include <map>
std::string foo(int bar)
{
return std::to_string(bar);
}
std::string foo(std::vector<int> bar)
{
int baz;
//process
return... | If I understand the comments correctly, the std::map<Key, Value> is only part of the problem. You first need the Value part - what C++ type can hold the overload set of f?
Jarod's comment is right: You basically need [](auto... args){ return foo(args...)};. This is a single lambda object, with an overloaded operator().... |
61,737,336 | 61,737,806 | Constructing DynamicArray with NULL in C++ Builder | I want to use the DelphiOSCUtils library in C++Builder.
The problem might be that it uses Generics, and C++Builder cannot handle Generics well.
The code inside the lib is like:
USES ..., System.Generics.Collections;
TOSCMessage = class(TOSCPacket)
private
...
public
constructor Create(Address: string); overload;
... | Your issue has nothing to do with Generics.
In C++, NULL is (usually) defined as an alias for an integer constant 0. But TOSCBundle does not have a constructor that accepts an int as input. That is what the compiler is complaining about in your case.
The TOSCBundle constructor you are trying to call takes a System::D... |
61,737,373 | 61,737,505 | PostQuitMessage(0) won't terminate my 'program' | I'm just trying to learn a little bit of C++ and wrote a few lines that do nothing but open a window.
I've added a Message Handler too and by clicking the [X] on my window it closes as its supposed to.
As the next step I wanted the Program to terminate when the [X] is clicked but it does'nt do that.
Here's my code:
#in... | The problem is on this assignment:
wc.lpfnWndProc = DefWindowProc;
You are telling the message loop to dispatch messages directly to DefWindowProc(), so your custom WndProc() is never used, so PostQuitMessage() is never called. DefWindowProc() does not call PostQuitMessage() for any message that it processes.
Change t... |
61,737,683 | 61,738,073 | What is the error in my consonant/vowel replacer? | So I am making a small program.You enter a string then my program outputs the string except where a was a consonant is now a "C" and for vowels a "V".Why does it output wrong when I enter "Elicopter" and maybe other words?
#include <iostream>
#include <string>
using namespace std;
int main()
{
const char con[]={'b','c... | Aside from the obvious already pointed out by @1201ProgramAlarm ('i' being in the list of consonants), there is lots of very unidiomatic code in there -- the way you would code in C, and rather low quality C at that (no offense).
While no code is ever perfect, perhaps you might benefit from having a look at the same (w... |
61,737,952 | 61,739,593 | How to copy a object's list to another object's list | I want to copy all attributes, lists and subtrees from one object to another object. However I am not able to copy the list with all its elements. How should I do it?
SPSTTree copyTree(SPSTTree original)
{
SPSTTree copy = (SPSTTree) malloc(sizeof(SPSTNode));
// Copy non-pointer values
copy->Element = orig... | Use std::copy to copy the list.
std::copy(original->list.begin(), original->list.end(), std::back_inserter(copy->list));
The malloc is a problem, because you skip object creation. Are you somehow interfacing C-code and forced to do such a thing? From your snippet it looks like you could use std::unique_ptr instead.
st... |
61,737,978 | 61,764,667 | Round-Robin Iterator and STL's pass-by-value policy | I'm writing an iterator round_robin_iter that keeps a bunch of iterators around. Whenever round_robin_iter is incremented, it increments the current iterator and passes on to the next one, in a circular manner. This allows me to easily interleave items from different containers. However, with a growing number of iterat... | From the very helpful comments to the question, I gathered the following for passing "heavy" iterators to STL algorithms:
if I no longer need the iterator, then I'll move it (pass std::move(iter))
if I do still need the iterator then, by definition, I need 2 different such iterators at some point and thus, the copy ca... |
61,738,322 | 65,944,560 | How to calculate the miss links in a BVH tree? | I am creating an OpenGl based ray tracer for polygon models. To accelerate the application I am using BVH-trees. Because there is no recursion in GLSL, I decided to find an other way to traverse the bounding boxes, sent to the fragment shader as shader storage buffers.
I would like to implement that kind of way:Traver... | I do not have an answer about a depth-first tree, but I have figured out a way to do that if your tree is a heap. So here is some code in GLSL I used
int left(in int index) { // left child
return 2 * index + 1;
}
int right(in int index) { // right child
return 2 * index + 2;
}
int parent(in int index) {
r... |
61,738,397 | 61,738,859 | Override superclass callback function used by another method [C++] | A very similar question was asked here:
C++: Overriding a protected method which is called by another method
However, I would like to know how to override a callback function in a Base class so that another method can call the derived class's callback from the constructor rather than the Base class's callback.
I've giv... | This cannot be done. You can see the explanation in this post.
The object is constructed from base - up. The base class gets constructed first and then the members of the derived class extend / override the base class. So when the base constructor is running, the members of the derived class don't exist yet, so you can... |
61,738,422 | 61,738,582 | Is it possible to insert escape sequence in a raw string literal? | What if I want this to consume fewer lines in my file?
auto rsl = R"rsl(==== WELCOME ===
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Pellentesque sed scelerisque purus. Nulla facilisi.
Suspendisse laoreet mattis urna sit amet suscipit.
===== Thanks for your attention ====)rsl";
Can I sprinkle this raw... | While it's usually best to stick to one type of literal or the other, you can mix raw and non-raw literals in concatenation:
auto u8 = u8"UTF-8 encoded string literal: \u041F\u0420\u0418\u0412\u0415\u0422 \n";
auto u8Rs = u8R"u8R(UTF-8 encoded string literal: )u8R" u8"\u041F\u0420\u0418\u0412\u0415\u0422" u8R"u8R(
some... |
61,738,474 | 61,739,268 | Writing end of line to wxTextCtrl | I was trying to write text to a wxTextctrl object in a wxWidgets application. Example code is below. For some reason, I'm not managing to get a line break. And most examples I've found online did one of the things that aren't working here.
The code:
#include "wx/wx.h"
using namespace std;
class MainWindow : public w... | You need to create wxTextCtrl with wxTE_MULTILINE style. You then normally only need \n which will be correctly interpreted for each platform.
|
61,738,722 | 61,739,027 | What if we don't create a new node and use a pointer to insert data and make links instead (in linked list)? | I was trying to implement basic operations of a Linked list using structures and classes but I usually mess up something. I am confused about memory allocation here. For example, why this program is not working correctly?
#include<iostream>
using namespace std;
struct node{
int data;
node* link;
};
node* head... | void insert(int x){
node temp;
temp.data = x;
temp.link = head;
head = &temp;
}
Objects have a lifetime, in the function above the object denoted by the variable temp is created when the function is called and destroyed when the function exits.
But head is pointing at this object. In other words, once ... |
61,738,978 | 62,696,903 | Can't Hide a QtAndroid Splashscreen with QtAndroid::hideSplashScreen(); | I am currently developing a Qt C++/QML app for android and I've come across an issue. By following the steps in this guide: HERE.
This produces a very clean and functional SplashScreen (natively I assume). However, It instructs me to use QtAndroid::hideSplashScreen(); to hide the splashscreen when all elements are loa... | The fix seems to be removing <item name="android:windowBackground">@drawable/splash</item> from AppTheme.xml.
Tested on Qt 5.14.2 / Android.
|
61,739,000 | 61,739,053 | Constructors and Destructors of Objects | I'm wrapping up my C++ course and I am repeatedly asked: how many times does a constructor/deconstructor get called in an objects life.
The simple answer to me seems like only once, and as far as I know, that's the case, but is there a case where they could be called more than once?
| No. Constructor is called at most once per lifetime. Sometimes there is no need to call a constructor for example in the case the constructor is trivial.
|
61,739,425 | 61,739,699 | Do you know how to solve "error: expected expression const char new_body[ ] = sprintf(const char *body, "Il valore del sensore è: %.2f", humidity);" | I've got a problem sending an HTTP response to a server and i have to use "sprintf"
while (1) {
float temp = sht31.readTemperature();
float humidity = sht31.readHumidity();
if(temp!=stored_temp || humidity!=stored_humidity){
printf("Change detected!\n");
stored_temp=temp;
stored_... | Details of sprintf can be found at
http://www.cplusplus.com/reference/cstdio/sprintf/
int sprintf ( char * str, const char * format, ... );
1. It returns int not const char[].
2. you can do sprintf as:
char body[MAX_PATH];
sprintf(body, "Il valore del sensore è: %.2f", humidity);
Now body has char array to be used... |
61,739,490 | 61,740,174 | What happens if you return a reference to a local variable through a lambda function object? | #include <iostream>
auto get_lambda()
{
int i = 5;
auto lambda = [&i]() { std::cout << i << '\n'; };
return lambda;
}
int main()
{
auto lambda = get_lambda();
lambda();
}
Inside the 'get_lambda' function I define the local variable 'i'.
The function then returns the lambda object that has one cap... | In your case, you are invoking undefined behaviour. The i name is local to get_lambda() function, and once i gets out of scope, it gets destroyed. So, with your lambda, you are now storing a reference to something that isn't there anymore. This is also known as a dangling reference. Capture the local variable by value ... |
61,739,922 | 61,740,035 | Processing Valarrays | Thanks for the attention in advance.
So i'm processing a valarray from STL, i'm curious about capturing values using a Closure.
Why i can't pass values by reference. Taking as instance the following code :
#include <iostream>
#include <valarray>
#include <functional>
int main()
{
std::valarray<int>arr={1,2};
... | Unlike almost any other standard library function that takes a form of predicate or other callable object, the std::valarray<T>::apply function actually only takes an actual pointer to a function, and not using templates to accept anything callable.
A capture-less lambda can be converted to a pointer to a function, lik... |
61,740,047 | 61,740,305 | My recursion does not work if I change the function input? | My recursive function stops execution and does not work at all. But if I change the input formula of the recursion, then it works perfectly fine. Can someone tell me where am I doing wrong?
I mean, if I use n/2 instead of (n+1)/2 and (n-1)/2 in the recursion formula then it works. More clearly if I use;
return 2*f(n/... | Consider what is happening when n=3.
First you call f(3), which in turn will call f(2) and f(1).
Then f(2) calls f(1) and f(0).
f(1) works correctly because of your base case, but f(0) goes on to call f(0) and f(-1). And so your recursion goes on forever.
The correct fix depends on what the function is supposed to be d... |
61,740,148 | 61,740,279 | Does using lambda as constructor argument requires C++ 17? | I have the following class that accepts lambda in its constructor
template<typename MAPPER>
class MapHead {
protected:
MAPPER mapper_;
public:
MapHead(MAPPER mapf)
: mapper_(mapf) {}
template<typename IN>
auto call(IN input) -> decltype(mapper_(input)) {
... | There is no class template argument deduction pre-c++17, so you have to specify the template arguments.
Not very beautiful, but this works:
auto lambda = [](int a) {
return (uint32_t) a * 2;
};
auto node = MapHead<decltype(lambda)>(lambda);
You can wrap this in a factory function to get argument deduction.
|
61,740,316 | 61,740,362 | How to get my overloaded << operator to print out my function? | I am having trouble with an overloaded operator for my Cinema class, which is supposed to print out the list of all movies, the list of times associated with it, and then the release date. I think I have the printAll() function to work fine, but I seem to be having troubles with getting it to print out in the right way... | You need to let the compiler know that printAll isn't going to make changes to the object (that is, that it's good to be called by const objects). So make the header:
void printAll() const;
and
void Cinema::printAll() const {
The second error is because you've forgotten parenthesis on your function call. Change
cout ... |
61,740,324 | 61,746,388 | How to update QWindow in qt c++, text doesn't show | I'm writing QT deskop app and I have a small issue.
I want to open new tab with text that I put from a file.
I have two class one in mainwindow.h and second in form.h
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
c... | the problem is that your Form exists only in this function scope.
void MainWindow::on_actionShow_text_file_triggered()
{
show_tab("all logs");
Form Fr;
Fr.text_to_plain(text);
}
Here -> Form Fr; the Form is created: constructor(explicit Form(QWidget *parent = nullptr);) of the class Form is called
And at t... |
61,740,583 | 61,740,643 | C++: recursively replace all instances of a letter in a string with another letter | I'm just going through some textbook c++ questions and one of them is to write a function which recursively replaces all instances of a certain letter in a string with another letter. I know that there are pre-existing functions for this, but because this chapter focuses on recursion, this question insists that the sol... | Just provide a default argument that keeps track of the index:
string replace(string in, char from, char to, int i = 0)
{
if (i == in.length())
return in;
if (in.at(i) == from)
in.at(i) = to;
return replace(in, from, to, i + 1);
}
Here's a demo.
This only uses at(), and length(), and doesn't even use ... |
61,740,734 | 61,740,783 | C++ warning: virtual function override with unused arguments | This is my 1st question posted on StackOverflow. I have come across a C++ warning to solve. The thing is we have overridden virtual functions in derived class, while there are a few function arguments not being used in the overridden function body. As a result, the compiler keeps warning. This is quite a common issue i... | All three (the third being [[maybe_unused]] attribute mentioned in the comments) are fine, and choice is purely aesthetic and subjective.
(void)a is least meaningful to me personally, but it has a long tradition, and some other cases of unused names don't have the same option of leaving out the name as an argument does... |
61,741,451 | 61,746,297 | How to create and use a python object stored as a c++ object? | So as the title sort of suggests, I am working on a c++ project where I need to call a python module, save it as an object, and call one of its methods multiple times. Below you can find the code for the class, which contains the python object. Currently, it is implemented inside of a for loop which calls the method mu... | The most critical part of writing Python C/C++ code is getting the reference counting right. Python differentiates between different kinds of references, namely new, stolen and borrowed references.
With every API function you call, you have to the check the documentation to see what kind of reference it returns, if any... |
61,742,004 | 61,742,153 | auto&& return type from a C++ lambda | I'm interested to understand what exactly the trailing auto&& return type means, specifically as distinguished from decltype(auto), which doesn't work here, and an unspecified return type, which also doesn't work.
In the code below, fn returns the x_ field of the argument. When the argument is an lvalue, x_ comes back ... |
but I expected -> decltype(auto) to return int&
This is expected behavior of decltype,
(emphasis mine)
Inspects the declared type of an entity or the type and value category of an expression.
1) If the argument is an unparenthesized id-expression or an unparenthesized class member access expression, then decltype y... |
61,742,027 | 61,742,234 | create_directory("/MyPath/.MyFolder") is not creating directory; expected that a hidden directory is created | I want to create a hidden directory in Boost 1.7.3 . When I try :
boost::filesystem::create_directory("/MyPath/.myFolder");
It doesn't work, it does nothing. I tried looking at the doc, but I can't find an answer.
| It turns out I'm just stupid. I'm developing in Ubuntu and I used command ls to verify if my directory was created, but this command doesn't show hidden files. ll does. It was working since the beginning.
|
61,742,046 | 61,765,886 | Can I get the source text of JavaScript functions in C++ callback function using google v8? | I am embeding google v8 into my C++ program. I want to get the source code of Javascript functions passed as arguments into my C++ function. For example:
function ComputePixel(nir, red, blue) {
return (nir-red)/(blue-red)
}
var layer = L8.function(ComputePixel, {
‘nir': L8.select('B5'),
‘red': L8.select('B4... | You should be able to call ToString on it:
v8::String::Utf8Value str(args[0]->ToString());
|
61,742,616 | 61,743,414 | How does gcc/clang parse c++ if it can't be parsed by a LR(1) parser? | GCC/Clang are handwritten parsers. I read a post saying that C++ can't be parsed by an LR(1) parser (Why can't C++ be parsed with a LR(1) parser?). If so, how come GCC/Clang are handwritten recursive descent parsers, when LR(1) is more powerful than recursive descent?
| GCC/Clang are not strict recursive descent parsers; they allow backtracking (reparsing an arbitrarily-long text), among other deviations from theoretical purity. Backtracking parsers are strictly more powerful than non-backtracking parsers (but at the cost of no longer being linear time).
The real complexities in parsi... |
61,742,757 | 61,743,263 | Singleton pattern using "Class &Class::Function()"? Why a Reference and not a Pointer? | Can anyone please advise what does following code mean? It looks like singleton pattern but uses & instead of pointer.
class Class
{
public:
static Class &Function();
}
Class &Class::Function()
{
static Class class1;
return class1;
}
| Singleton is an idea made by programmers. It means that it holds no specified form behind it (especially dealing with c++ pointers and references) and only has it's set of rules.
The code you see infront of you meant to create a static variable when the function is called and keep it till the end of the whole program c... |
61,743,113 | 61,743,202 | Is this code for emptying a linked list okay? | I need to work on a function that resets a linked list without completely eliminating it, and I wanted to know if my piece of code is right. Any other suggestions?
void reset(){
if (initial == nullptr){
return;
}
Node<T> *flag;
Node<T> *temp;
while(initial->ob... | By my understanding you're trying to erase your linked list.
1. You may just loop through the given node and delete all of them setting the head node as nullptr.
2. You may make an object which holds that linked list and may serve your purpose by using method 1 in erasing everybody but the object still exists with a va... |
61,743,145 | 61,743,614 | Why doesn't IconTheme resource path get listed on get_search_path | On GTKMM reference docs for Gtk::IconTheme the section for add_resource_path() says
void Gtk::IconTheme::add_resource_path ( const std::string & path )
Adds a resource path that will be looked at when looking for icons,
similar to search paths.
This function should be used to make application-specific icon... | APIs that refer to "resource" paths are talking about paths inside of GResources not paths on the filesystem.
|
61,743,418 | 61,743,477 | I'm getting a strange error when I try to do serialization with cereal in C++ | I keep getting this strange error
/usr/bin/ld: CMakeFiles/libdungeon.dir/src/main.cpp.o: in function `decltype (({parm#2}.serialize)({parm#1})) cereal::access::member_serialize<cereal::BinaryOutputArchive, Character>(cereal
::BinaryOutputArchive&, Character&)':
main.cpp:(.text._ZN6cereal6access16member_serializeINS_19B... | You can't separate the declaration and definition for function templates to a header (.h) and implementation (.cpp) file in C++. To fix, move the function template definition for Character::serialize to the header file:
//in character.hpp
...
template <class Archive>
void serialize(Archive & ar){ //function definitio... |
61,743,592 | 61,743,824 | Temporary bound references to struct members | I was trying Coverity out on some code base and I got a warning on a code akin to
struct Foo
{
std::string name;
};
Foo getFoo();
//...
const auto& name = getFoo().name;
useName(name);
Is this code valid?
I had the intuition that it's indeed invalid. But then, when searching for proofs, I've come across [class.te... | This code is well-formed. As the linked standard says, the lifetime of the temporary returned by getFoo() will be extended to the lifetime of the reference variable name.
(emphasis mine)
Whenever a reference is bound to a temporary or to a subobject thereof, the lifetime of the temporary is extended to match the lifet... |
61,743,861 | 61,743,977 | RVO/NRVO can not be disabled in C++17 in Clang++? | I was getting different results from the same snippet of code running under different C++ version with Clang++. It seems like the compiler had automatically called the RVO/NRVO when I compiled the code with C++17, curious is that a bug or different feature?
Apple clang version 11.0.0 (clang-1100.0.33.17)
Running under ... | In C++17 the language definition changed. In the code in your question there is no temporary , and nothing to elide.
The prvalue expression can be viewed as having delayed instantiation instead. The expression auto a = getTempA(100); is by definition identical to A a(100);.
|
61,743,949 | 61,763,298 | Binary Tree to Heap Tree Conversion - Stuck in infinite loop | While working on a problem, I have tried the following solution. Somehow my output is stuck into infinite loop and not printing result or updated heap tree.
Given a tree where the left and right subtrees are min heaps, but the root node does not maintain the min heap property. Your code should modify the tree rooted at... | Your primary problem is this line of code:
mino = (std::min(n->left, n->right));
Here, you're comparing two pointers when you really want to compare the values in the two objects you're referring to, and return a pointer to the object that has the smaller value. That is:
mino = (n->left->value < n->right->value) ?... |
61,743,973 | 61,744,073 | C++ Declaring an inherited constructor? | I'm having difficulties in defining a constructor for a class that inherits the properties of another class
class Transportation {
public:
int ID;
string company;
string vehicleOperator;
Transportation(int,string,string) {
}
};
class SeaTransport: public Transportation {
public:
int portNumb... | It seems you mix together scoping and a constructor initializer list.
The double-colon operator :: is for scope, while a constructor followed by a single colon and a list of initializations is an initializer list.
You must declare the SeaTransport constructor to take all the arguments, including those for the parent cl... |
61,744,244 | 61,744,836 | C++ a way to get all inherited classes info | So i have this part of code
class Robot
{
public: string Name;
public: explicit Robot(const string& Name) { this->Name = Name; }
public: Robot() { Name = "Robotic"; }
public: virtual ~Robot() = default;
public: virtual vector<string> GetCapabilities() = 0;
public: friend ostream& operator << (os... | There isn't a simple one-line way in standard C++ to implement this sort of thing. For example, there is no way for a derived class to iterate over all its base classes, and call some member function in every base to collect the results, without explicitly naming all the bases/members separately.
It is possible to ca... |
61,744,261 | 61,744,335 | Why parenthesis are needed when dereferencing a double pointer? | I have this function to delete the very first node in a single linked list:
void removeFront(Node **tmpHead){
if ((*tmpHead)->next == NULL)
cout << "Single Node! RemoveFront() aborted!\n";'
else{
Node *oldNode = *tmpHead;
*tmpHead = oldNode->next;
delete oldNode;
}
}
Why do I need to put *tmpHead betwe... | Due to operator precedence, *tmpHead->next is interpreted as *(tmpHead->next).
Since tmpHead is of type Node**, tmpHead->next is not a valid sub-expression.
That's why you need to use parenthesis around *tmpHead and use (*tmpHead)->next == NULL.
|
61,744,787 | 61,745,933 | Initializing class members with {} | Someone gave me (part of) the following code:
struct MyStruct
{
int x = {};
int y = {};
};
I never saw this syntax before, what does initialization with {} mean?
| Since the C++11 standard there are two ways to initialize member variables:
Using the constructor initialization list as "usual":
struct Foo
{
int x;
Foo()
: x(0)
{
}
};
Use the new inline initialization where members are getting their "default" values using normal initialization syntax:
stru... |
61,744,910 | 61,746,411 | How to find the number of columns in a 2d std::array | I have this function, which checks if all rows are equal in a 2d std::string array:
template <int sizeElements, int sizeArrays>
bool CheckEquality2dArray(const array<array<string, sizeElements>, sizeArrays> &my2dArray)
{
if (equal(my2dArray.begin() + 1, my2dArray.end(), my2dArray.begin()))
{
return true... | I've changed the template arguments to:
template <size_t sizeElements, size_t sizeArrays>
I then deleted the template parameters when i used the function (thanks to molbdnilo) and everything is working now :)
|
61,745,183 | 61,745,272 | Taking a pointer to a derived class ends in a runtime exception in C++ | I have a simple abstract base class:
class Sensor {
protected:
GenericDriver *driver;
public:
Sensor() {};
virtual void startNewReadout(void) = 0;
};
From which I derive a concrete class:
class OneWireSensor : public Sensor {
private:
OneWireDriver oneWireDriver; //not really necessary here
public:
... | The problem is most likely caused by the dangling pointer from the constructor of OneWireSensor.
OneWireSensor::OneWireSensor(PinData *pinData) {
// A function local object.
OneWireDriver oneWireDriver(pinData);
// Pointer to the function local object.
// It becomes a dangline pointer as soon as the f... |
61,745,365 | 61,745,522 | Inserting tree by using constructor without using other function | I tried to create a simple binary tree by using constructor
TreeNode(int val) : val(val), left(nullptr), right(nullptr) {}
I am totally lost on creating binary tree. I can create a tree by creating insert function but by utilizing constructor i am not too sure.
#include "pch.h"
#include <iostream>
using namespace s... | You have a one-parameter constructor that takes the node value and sets both pointers to nullptr.
That is, it has the same effect as
Node->val = data;
Node->left = NULL;
Node->right = NULL;
In other words, you can replace all uses of newNode(x) with new TreeNode(x).
(By the way: stick to nullptr, don't throw NULL int... |
61,745,618 | 61,746,782 | How to understand "abstract-declarator containing an ellipsis shall only be used in a parameter-declaration" | Consider the following quote,It says:
[dcl.fct]/16
A declarator-id or abstract-declarator containing an ellipsis shall only be used in a parameter-declaration.[...]
I agree with A declarator-id containing an ellipsis shall only be used in a parameter-declaration,Because we can't use something like ...id-expressio... | The ellipsis is not part of a type-id, but of a template-argument-list.
If we apply the following grammar from [temp.names]
simple-template-id:
template-name < template-argument-listopt >
template-name:
identifier
template-argument-list:
template-argument ...opt
[...]
template-argument:
type-id
... |
61,745,759 | 61,747,210 | The cin.getline() should not accept space if user inputs? | class acc_cr{
protected:
char username[100];
char password[100];
int i = 0;
public:
void create(){
fstream fout;
//new username:
cout<<"Enter Your New Username:\n";
while(i == 0){
cin.getline(username,100);
//checking if this username already exists:
if(fstream(us... | If you use cin.getline(username, 100,' ') the input is automatically terminated if the user enters a string. But I really don't suggest that because it spoils the whole experience for the user.
The best solution I suggest is to use std::string instead of char array. Then you will be able to use stringstream.
string... |
61,745,781 | 61,745,847 | Why does one ostream << overload work but the other doesn't? | I have to use some overloaded << ostream operators for a project, and I got the first one to work properly for date, but the one that is from my other class seems to be giving me some problems and I can't figure it out for the life of me. It doesn't give me any errors, it just doesn't work the proper way and prints out... | Simple error
cout << movie1;
should be
cout << *movie1;
The moral is, don't use pointers needlessly.
|
61,745,807 | 61,750,782 | PKCS11 - Generate key for SHA256_HMAC | I use Botan2 library to access SoftHSM2. I managed to generatesome AES/DES keys, yet I would like to generate a secret for SHA256 HMAC.
My code (after creating session, logging in and detecting my token):
namespace p11 = Botan::PKCS11;
p11::SecretKeyProperties propsOtpGen(p11::KeyType::Sha256Hmac);
propsOtpGen.set_labe... | After trying all calls imaginable, i still haven't made it work with SHA256HMAC key type. Seems like there is no generator for it.
The onlu workaround I found is using the GenericSecret key type.
namespace p11 = Botan::PKCS11;
p11::SecretKeyProperties propsOtpGen(p11::KeyType::GenericSecret);
//...
This generates the ... |
61,746,073 | 61,746,332 | Is there a way to check if a user input in c++ is in a certain predefined vector and if not tell the user to re-enter the input? | Right now I'm making a text-based game on c++ and one problem I'm facing is ensuring that user input is valid. I can do this easily with numbers but for <char> I'm having issues. Essentially the user should only input either "F", "S", "H" or "Q" and in python I'd do that as
acceptable_chars = ["f", "s", "h", "q"]
in... | In C++, single characters and strings have different types. For single characters, use single quotes: 'f', 'h', etc. For strings, use double quotes: "f", "h", "quit", etc.
I assume you want to use single characters; if you want to use strings, replace char by std::string in the code below.
To organize your valid choice... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.