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,645,708 | 63,645,777 | What is up cast and down cast in inheritence? | class Base
{
public:
Base(){}
virtual void f() {};
}
class Derived : public Base
{
public:
Derived() {}
virtual void f() {}
}
int main()
{
Base *obj = new Derived();
obj->f();
return 0;
}
Well, this type of behaviour is called upcasting or downcasting?
What is upcasting and downc... | This is upcasting.
Upcasting is basically “widening” or casting up the tree, (parents), while downcasting is “narrowing” or specialization, casting down the tree (children)
Or you can say upcasting is derived -> base type.
Downcasting is base -> derived type.
For example
Animal * a = new Dog();
is upcasting,
whereas
(... |
63,645,881 | 63,645,944 | How this std::string pointer turns into array? | Hi I am having trouble with this code here from a tutorial about returning Arrays from functions
std::string(&func(std::string(&arr)[10]))[10]
{
return arr;
}
int main()
{
std::string array[10] = { "efwefwef","wefffj","mfls","hrkr","sgte","ege","ky","retg","sujtre","fl;yiu" };
std::string* array23 = func(ar... | The plane arrays(c-style) can be decayed to a pointer to the type of the array, and the pointee can be accessed using operator[] (i.e pointer[index]).
The function func returns the reference to an (c-style) array of std::strings with 10 elements in it.
If you write the function clearly with an alias, it would look lik... |
63,646,274 | 63,647,615 | sum of all abundant numbers less than or equal to n | The problem is to find the sum of all abundant numbers less than or equal to n where an abundant number is a number whose sum of all proper factors is greater than that number for eg. 12 is an abundant number as
1 + 2 + 3 + 4 + 6 = 16 which is greater than 12.
This is my implementation I am getting TLE and I'm stuck he... | Your problem is to find the set of abundant numbers less than n, not to check if one particular number is abundant. Take for instance the sieve of Eratosthenes, an ancient algorithm for finding all prime numbers less than a given number. It doesn't check one by one if a number is a prime, but work more efficiently inst... |
63,646,394 | 63,646,495 | How to choose type from some different on compilation time? | I want to do something like this:
template <uint64_t N>
struct a {
static constexpr T1 v1 = {};
static constexpr T2 v2 = {};
static constexpr auto v3 = (N % 2 == 1 ? v1 : v2);
};
But I can't use (? :) with different types. How I can do this?
| For example, you can use if constexpr and a lambda function (C++17):
template <std::uint64_t N>
struct a {
static constexpr T1 v1 = {};
static constexpr T2 v2 = {};
static constexpr auto v3 =
[] {
if constexpr (N % 2 == 1)
return v1;
else
return v2;
}();
};
Anoth... |
63,647,176 | 63,659,345 | Can't see my texture on 2d object using OpenGL | I'm trying to use textures in my mini OpenGL program. As using OpenGL requires a lot of duplicated code so I abstracted my code into a class. But I can't see anything on the window. OpenGL doesn't throw any errors. I'm using stb_image.h from https://github.com/nothings/stb/ to process image files. What I am doing wrong... | I'm using class to handle the layout of vertices. In the implementation of that class, there is a loop like this:
for (int i = 0; i < ...; i++) {
...
glEnableVertexAttribArray(i);
...
}
Above one is correct, but I made a mistake previously by typing 0 instead of i like this:
glEnableVertexAttribArray(0);
... |
63,647,202 | 63,647,273 | Why this C++ program is not printing anything? |
I have this C++ program but its not printing anything in the console.
I am copying the content of the string in 2 vectors and doing count increment operations on them.
#include <iostream>
#include<vector>
#include<bits/stdc++.h>
#include<string>
using namespace std;
int main()
{
string s;
cin>>s;
int i,j;
ve... | I found your code fall into a infinite loop in the following.
for (i = 0; i < t - 1; t++) // not t++, but it should be i++
{
a.push_back(s[i]);
}
I also believe that a debugging skill helps you finding a bug in your program.
|
63,647,280 | 63,647,286 | How To Turn Char of '2' into Integer 2 in C++ | I am Kind Of New To C++. But I Want To Turn The Character 2 into An integer 2. I tried using Casting But It Gives Me The ASCII Value Of The Char. How Can I Achieve This Iam Using Linux And Codeblocks
| Just subtract the ASCII value of '0' from '2' to get the integer 2.
char c = '2';
int n = c - '0';
This is guaranteed to work even if the encoding is not ASCII, since the language requires that the encoding of the characters increases from '0' to '9'.
|
63,647,476 | 63,647,900 | I am getting " template argument deduction/substitution failed:" Error in C++ | I have a C++ Code as Following:
#include <iostream>
using namespace std;
// Enter your code for reversed_binary_value<bool...>()
int reversed_binary_value()
{
return 0;
}
template <bool i, bool... arg>
int reversed_binary_value()
{
int z=0;
z=reversed_binary_value(arg...)*2;
if(i==0)
return z;
... | The error in your code is calling reversed_binary_value()
z=reversed_binary_value(arg...)*2;
that expect the boolean values a template parameters.
So you have to call it as follows
z=reversed_binary_value<arg...>()*2;
// ....................^......^^^
But now you have another problem: when the variadic pack args... i... |
63,647,583 | 63,647,925 | Is there a way to ignore end of file characters while reading files in c++? | So I am trying to read a file into a program in C++, but there are random end of files thrown in throughout the file. When trying to read the file, ifstream stops reading when it hits an end of file character.
This is the code that I am using to try to read the file
size_t bytesAvailable = 1000;
std::ifstream file(dire... | Try opening the file in binary mode. On some platforms, text mode and binary mode behave differently, such as the text mode interpreting end-of-line into LF, or interpreting a control character (possibly Ctrl+D or Ctrl+Z) as an end-of-file.
size_t bytesAvailable = 1000;
std::ifstream file(directory, std::ifstream::in|... |
63,647,664 | 63,647,705 | C++ Array subscripting differences | I have an array declared like this
float dati[10];
I normally subscript the array like as follows
dati[2] = 5;
But i have also seen other types of substriptions like
2[dati] = 5;
and
*(dati+2) = 5;
Can anyone tell me what's the difference between these three?
| Compiler translates a[i] as *(a+i), so this bit links up your first and third manner of indexing.
Now, a being the address of first element of an array - aka a pointer - and i being an integral constant or variable you know a + i is the same thing as i + a. This means the following also holds
a[2] = *(a + 2) = *(2 + a)... |
63,647,981 | 63,648,067 | What is the right way to overload the assignment operator for a derived class? | Let's say I have a Base class:
class Base
{
public:
Base(float x, float y, float z, float w):
x(x), y(y), z(z), w(w) {}
float x;
float y;
float z;
float w;
};
bool operator==(const Base &a, const Base &b);
Now, I have a Derived class from Base:
class ... | Assuming you have an operator= in the Base class, you could write:
Derived& Derived::operator=(const Derived &a){
Base::operator=(static_cast<Base const&>(a));
r = a.r;
g = a.g;
b = a.b;
return *this;
}
|
63,647,994 | 63,653,177 | Do I need cudaSetDevice before cudaStreamSynchronize? | In my system I program multiple GPUs concurrently. Do I need to call cudaSetDevice() before calling cudaStreamSynchronize()?
When creating the cudaStream_t objects, I did set the device correctly before calling cudaStreamCreate().
| I may be wrong but I don't think you need to call the function cudaSetDevice() again if you already used it when creating the stream.
Resources:
https://developer.nvidia.com/blog/cuda-pro-tip-always-set-current-device-avoid-multithreading-bugs/
https://forums.developer.nvidia.com/t/how-many-times-does-cudasetdevice-nee... |
63,648,497 | 63,674,630 | Including Multiple Classes/ .o files with MinGW Tool in C++ | I want to compile 2 classes into .o file and include them in Test.exe file created from avl.cpp main file.
I use the MinGW tool while doing this, but Nothing happens when I type the command mingw32-make into CMD. When I did this with only 1 class, there was no problem.
The content of the makefile file is as follows:
al... | Makefile uses dependancies to determine what gets built in which order.
So the line execute: should really be execute: compile to tell make to do the execute step after the compile step completed.
But you should really split compilation an linking into steps to use the dependancy resolving qualities of make.
Here's how... |
63,648,638 | 63,675,669 | How to pass objects as arguments? | I have changed the code here
all the variables have to remain private and using friend functions is a requirement.
Here there are two classes A and B and I am supposed to accept 5 numbers(void enter()).The function average is to be able to access all variables and give the average.
I know that currently the line
obj2.... | You can not access member variables in the main function because they are private.
You can send the first instance to the method as a parameter, then use the class A member variables inside the method.
#include<iostream>
using std::cin;
using std::cout;
using std::endl;
class A
{
int a;
int b;
public:
friend clas... |
63,648,810 | 63,649,314 | Why does copy constructor get called with this statement: myVector.push_back( A() ); | https://www.educative.io/edpresso/what-is-a-move-constructor-in-cpp
int main()
{
vector <A> vec;
vec.push_back(A());
return 0;
}
Now, when the above code is executed, the default constructor is called at the time that the temporary object A is created. The copy constructor is called as the temporary o... | Temporary objects gets destroyed at the end of statement, where they are declared;
A(); // will be destroyed at semicolon;
You need to get the object before destroyed, that's when copy constructor takes into place;
A obj = A(); // A object created and copied into obj before gets destroyed.
Same thing happening with v... |
63,648,815 | 63,648,966 | Segmentation Fault while accepting input | I am trying to accept the input from user
where first line will be Integer to indicate number of testcases
if number is 3
Input will be like
3
Hello world
hey there, I am John
have a nice day
I am using getline to read the input
My code
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
... | You can't create an element of a vector using the [] indexing operator; your line arr[i] = s; is trying to assign a string to an element that doesn't (yet) exist.
There are several ways around this: first, you could use the push_back function to add a new element to the end of the vector, in each loop; second, you coul... |
63,649,222 | 63,649,560 | Count All Sub sequences having Product less than K | Given a non-negative array, find the number of subsequences having a product smaller than K.
Examples:
Input : [1, 2, 3, 4]
k = 10
Output :11
Input : [4, 8, 7, 2]
k = 50
Output : 9
So, We want to count the number of subsequences whose product is less than K.
There are sub-problems, and it can be solved using Dynamic P... | The condition
if(prod > 1 && prod <= K)
return 1;
will have it return from the function (for example) when [1, 2] is selected from [1, 2, 3, 4] and prevent it from searching for [1, 2, 3].
Also:
The condition prod <= K is wrong becasue you want the product smaller than K, not K or smaller.
You cannot dist... |
63,649,260 | 63,649,347 | C++ - invalid initialization of reference of type 'node*&' from expression of type 'node' | I was doing some list exercises but for some reason the compiler notice some problems about the struct node type, but i can not see what is the problem.
I declared normally node structure, in the addNode(node *&, int) function i use a
pointer by reference of node type for modify the list in the main and a integer for s... | int main()
{
node list;
is missing a star to declare a pointer. You probably want:
int main()
{
node* list = NULL;
|
63,649,617 | 63,649,630 | Error with input-validation using std::cin | I have implemented this check in my program to determine if the input is of the right type or not, and if not it asks to re-write the input.
If the input is wrong it works just fine but, if the input is right, you need to write it again. How can I avoid this? (you can find an example here https://godbolt.org/z/KjoTbc)
... | You are not checking the first std::cin >> input ; and running while (!(std::cin >> input)), which asks input, unconditionally.
Remove the first unchecked reading and try this:
#include <iostream>
#include <limits>
int main() {
int input;
while (!(std::cin >> input)) {
std::cin.clear();
std:... |
63,649,684 | 63,649,706 | How do you pass a function as an argument into the transform() function? | I am trying to create a program that uses transform() to determine the size of strings in a vector and then put the results into a separate vector.
I do not fully understand how to pass a function into transform() and I am getting an error, any help would be much appreciated!
My code:
#include <vector>
#include <string... | There's nothing wrong with how you're passing a function to transform. The issue is your result vector is empty, so you invoke undefined behavior when you iterate from result.begin(). You need to do:
std::transform(words.begin(), words.end(),
std::back_inserter(result), stringLength);
Here's a demo.
Yo... |
63,649,700 | 63,649,735 | Comparing string against list of strings in C++ | If I have a list of strings for example:
Dog
Cat
Tree
NiceCar
Car
And then I get one string from list what is the fastest way to check them? I was thinking about some hashing and then to comparing the hashes.
std::hash<std::string> hasher;
std::string stringToCheck = "Car";
switch (hasher(stringToCheck))
{
case ... |
I will ofcourse hash the whole list on program start and then compare against that.
If that's the case, I would suggest using a standard library utility - std::unordered_set, which internally stores the data and uses hashing to search for it:
int main() {
std::unordered_set<std::string> strings = {
"d... |
63,649,866 | 63,650,066 | Constructing a tuple from a move only type with a std::function member | please consider the code below:
struct no_copy {
int x_;
std::function<void()> f_;
template <typename F>
no_copy(int x, F&& f)
: x_{ x }, f_{ std::forward<F>(f) } {};
no_copy(const no_copy&) = delete;
no_copy& operator= (const no_copy&) = delete;
no_copy(no_copy&&) noexcept = default;
no_copy& operator= (no_cop... | This is apparently an implementation bug: there's no initializer list in your code at all, and current versions of all compilers accept it (MSVC since v19.22).
|
63,650,165 | 63,650,402 | C++ Optimizer : division | Lets say I have 2 if statements:
if (frequency1_mhz > frequency2_hz * 1000) {// some code}
if (frequency1_mhz / 1000 > frequency2_hz ) {// some code}
I'd imagine the two to function the exact same, yet I'm guessing the first statement with the multiplication is more efficient than the division.
Would a C++ compiler o... | Yes and no.
The code is not identical:
due to rounding, there can be differences in results (e.g. frequency1_mhz=1001 and frequency2_hz=1)
the first version might overflow sooner than the second one. e.g. a frequency2_hz of 1000000000 would overflow an int (and cause UB)
It's still possible to perform division usi... |
63,650,783 | 63,650,813 | Is there a C++ idiom for writing to either STDOUT or a file? | I'm writing a command line tool and I would like it to write to STDOUT by default, but write to a file if specified. I'm trying to do this in a way that keeps the interface for writing the output consistent by using an output stream.
This was my first idea:
#include <iostream>
int main(int argc, char* argv[]) {
std... | A simple way to do this is just write to standard output and let the user use shell redirection to send the output to a file, if desired.
If you want to implement this in your code instead, the most straightforward way I can think of would be to implement the body of your program in a function that accepts an output st... |
63,650,832 | 63,650,902 | Capture file via stdin/cin with < and read to EOF | My main.cpp
#include <iostream>
#include <fstream>
int main(int argc, char* argv[]) {
std::string filename;
std::cin >> filename;
std::ifstream inf(filename);
std::string line;
while(std::getline(inf, line)) {
std::cout << line << std::endl;
}
return 0;
}
Trying to read:
main < somefile... | File redirection with < sends it directly to stdin, so you don't need to create a std::ifstream.
#include <iostream>
int main(int argc, char* argv[]) {
std::string line;
while(std::getline(std::cin, line)) {
std::cout << line << std::endl;
}
return 0;
}
|
63,651,268 | 63,651,764 | C function from assembler code as a char string | I was just wondering how random number is generated in assembler, I found question from russian stack overflow where a person asks rather not how to generate a random number in assembler, but how to implement that in c code using _asm{}.
The answer posted to his question surprised me (translated to eng):
char r[]="!!!!... | About the code example
Pasting the second answer's text from your link to a translator gave me:
And you can make it so that the machine code will be located in an array. Here's how you can write a program to count the number of characters in a string.
So it's only an example about how to use assembly code inside a C ... |
63,651,305 | 63,651,453 | SDL_image could not initialize! SDL_image Error: Failed loading libpng16-16.dll: The specified module could not be found | I have spent the last hour trying to find a fix for this error. I have searched all over SO and other sites for answers but nothing that I have found has worked so far. So here I am, in desperate need of help.
First of here are the versions of software and libraries that I am using:
SDL2-2.0.12
SDL2_image-2.0.5
VS Com... | I figured out the problem. I added all of the dependencies from the SDL2-2.0.12\lib\x86 to my projects Release and Debug directories and the program ran as expected. Just remember to copy the x64 folder instead of x86 if you plan on using 64 bit.
|
63,651,389 | 63,651,449 | what happens when routine "free" fails in a "try" block in c++ | Typically, if memory issue occurred in calling routine "free", a program will stop immediately with error message telling details of the error. Now assume "free" is called in a "try" block. If an error occurred with the call, will the program stop immediately with an error message, or will the program completes executi... | free can't error out without some preexisting problem in your code occurring, almost certainly a result of undefined behavior. Once you're in the land of nasal demons, there are no guarantees. free doesn't have a concept of exceptions (it's a C function, no C++ features), or even error return codes; if you corrupt your... |
63,651,414 | 63,651,491 | Why aren’t posit arithmetic representations commonly used? | I recently found this library that seems to provide its own types and operations on real numbers that are 2 to 3 orders of magnitude faster than normal floating point arithmetic.
The library is based on using a different representation for real numbers. One that is described to be both more efficient and mathematically... | The most objective and convincing reason I know of is that posits were introduced less than 4 years ago. That's not enough time to make inroads in the marketplace (people need time to develop implementations), much less take it over (which, among other things, requires overcoming incompatibilities with existing softwar... |
63,651,548 | 63,651,635 | Error while performing string copy operation in C++ | Please explain why is this giving an error but the other on is running fine
The following code gives the error:
#include <iostream>
#include <string>
#include <conio.h>
#include <math.h>
#include <iomanip>
#include <string.h>
using namespace std;
int main()
{
string s1,s2;
int i;
cout << "Enter the strin... | In your case, s2 is initialized to an empty string with a length of 0, so you can't write past the bounds. If you want to, you must first resize it:
s2.resize(s1.length());
for(i=0; s1[i]!='\0'; ++i)
{
s2[i]=s1[i];
}
Also, c++ std::string does not need a terminating nullbyte, unlike C strings.
|
63,651,580 | 63,651,830 | fstream in a function | i cannot extract anything from the file in the tilstart function but the program finishes with no issues. The goal of the function is to go through the txt file until it gets to "start". I have to use recursion but i had to (//)tilstart(files) in the end of the function to prevent stack overflow since the file wasn't g... | thank you for yalls tips! i found out the reason i wasnt getting an input from the file was because in main i forgot to edit the first line after i made the second line.
ifstream files("input13.txt");
files.open("input13.txt");
once i did:
ifstream files;
files.open("input13.txt");
it worked! if anyone could tell me ... |
63,652,326 | 63,733,219 | How do I call a C++ constructor using the cxx crate? | I found this question, but it is 3 years old and since then, crates like cxx have come into existence. Is it possible now to construct a C++ object from Rust, or do I still have to create a shim?
| To the extent that constructors "return" a C++ type by value, they're not translatable to Rust because Rust moves (memcpy) are incompatible with C++ moves (which can require a move constructor to be called). Translating an arbitrary constructor to fn new() -> Self would not be correct.
You can bind them unsafely with b... |
63,652,941 | 63,653,269 | How to serialize/deserialize std::map<int, MyObject> to/from json in C++ | I'm trying to serialize/deserialize std::map<int, MyObject> using https://github.com/nlohmann/json
It says here that the keys for the map must be able to generate std::string. How can I achieve that?
Basic usage for implementing conversion to/from my custom object MyObject would be:
using nlohmann::json;
namespace ns ... | The wording in the readme is clear as to why this doesn't work (emphasis mine):
Likewise, any associative key-value containers ... whose keys can construct an std::string and whose values can be used to construct JSON values ... can be used to create a JSON object.
This is why using int as a key doesn't work with thi... |
63,653,036 | 63,653,102 | Can we really avoid extra space when all the values are non-negative? | This question is a follow-up of another one I had asked quite a while ago:
We have been given an array of integers and another number k and we need to find the total number of continuous subarrays whose sum equals to k. For e.g., for the input: [1,1,1] and k=2, the expected output is 2.
In the accepted answer, @tale... | Let's start with a slightly simpler problem: all values are positive (no zeros). In this case the sub arrays can overlap, but they cannot contain one another.
I.e.: arr = 2 1 5 1 1 5 1 2, Sum = 8
2 1 5 1 1 5 1 2
|---|
|-----|
|-----|
|---|
But this situation can never occur:
* * * * * * *
|-------|... |
63,653,168 | 63,653,180 | c++: array of pointers | I am new to c++ and I have a question about the array of pointers. In the following program
#include <iostream>
using namespace std;
int main(){
char b[10];
char* a[10];
b[0] = 'b';
a[0] = &b[0];
cout << a[0] << endl;
return 0;
}
a is an array of pointers pointing to char objects. a[0] is t... | The expression a[0] has a type of char *.
The << operator, when give a value of char *, interprets it as a '\0' terminated text string, and that's what you see. That's how it works.
Just by the luck of the draw, the second char of b, b[1], turned out to be a binary zero, which serves perfectly as a '\0', however this i... |
63,653,383 | 63,653,482 | priority queue as min heap c++ vs heapq in python (how to convert heapq.heappop(openList) to c++?) | I have the following python code:
import heapq
heapq.heappush(openList, currentSearchNode)
#NOTE List of nodes that have been checked
closedList = []
while openList:
#NOTE Pop the lowest fscore (to-go + been from or gScore + hScore) and set it as current
currentSearchNode = heapq.hea... | How about like below;
while (!min_heap.empty()) {
currentNode = min_heap.top(); // sets the top small (since std::greater used)element to currentNode;
/* do something with currentNode */
min_heap.pop(); // pops the element from container
}
|
63,653,477 | 63,653,560 | In a C++ range-based for loop, can begin() return a reference to a non-copyable iterator? | Update:
Thanks to everyone who submitted an answer.
In short, the answer is that the "iterators" that begin() and end() return must be copyable.
Artyer proposed a nice workaround: Make an iterator class that contains a reference (or, alternatively, a pointer) to the non-copyable object. Below is example code:
struct ... | Yes, iterators must be copyable. This is because range iteration is logically equivalent to the following code:
auto && __range = range_expression ;
for (auto __begin = begin_expr, __end = end_expr; __begin != __end; ++__begin) {
range_declaration = *__begin;
loop_statement
}
This is the ... |
63,653,774 | 63,653,862 | How do i fix these errors : reference to non-static member function must be called and invalid use of member 'mat' in static member function? | I was writing a program where I had to use custom sort, so I made a custom comparator "comp", but using it inside C++ class, gives "reference to non-static member function must be called", I fixed this using static bool comp(). But after making my comparator functions static, I am getting the error "invalid use of memb... | The trick is to define a call-operator on your Solution class so that it can be used as a Comparator object that is passed to the std::sort() call, like this:
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int mat[26][26];
bool comp(char a, char b, int i) const {
... |
63,654,125 | 63,654,156 | Can anyone explain how custom comparator works in C++? | Ques: Given an array of linked-lists lists, each linked list is sorted in ascending order.
Merge all the linked-lists into one sort linked-list and return it.
Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
1->4->5,
1->3->4,
2->6
]
merging them into one sorted... | std::priority_queue is documented on cppreference with:
A user-provided Compare can be supplied to change the ordering, e.g. using std::greater<T> would cause the smallest element to appear as the top().
So if you want to have a priority queue where you can pop the smallest element, it expects you to pass a comparato... |
63,654,388 | 63,657,924 | Does typename have to be specified inside template? | It seems that GCC does not require a typename to be specified inside the template while Clang does.
Consider the following code snippet:
template<
typename T,
typename value_type = T::value_type
>
void func(T t) {}
The code above compiles successfully on GCC 10.0.1 when Clang reports the following error messag... | C++20 removes the need for specifying typename for dependent template names in specific cases where it's obvious that what is being specified must be a typename. Like, for example, a template parameter's default value when that parameter has already specified that it is a typename:
A qualified name is said to be in a ... |
63,654,874 | 63,655,252 | How can I use to the stream extraction operator to read a file assuming that only the last line will have errors of not containing 3 values | TEXT FILE IM READING
1 1 1
1.2 -2.3 0.4
-2 -3 -4
+0 -2 8.85
2.345
My code:
#include <iostream>
#include <fstream>
using namespace std;
double readFile(ifstream &myfile, double &a, double &b, double &c);
int main()
{
int counter = 0;
double a, b, c;
string line, inputFile, outputFile;
cout << "Enter ... | Your biggest issue is that >> skips leading whitespace, so it doesn't differentiate between a ' ' (space) or '\n' -- it's just whitespace. To handle it correctly, you need to read each line into a std::string and then create a std::stringstream from the line.
Then read your three double values from the std::stringstrea... |
63,655,078 | 63,709,511 | Display parameters in cppcms GET or POST request | How to get the parameters list from cppcms GET or POST URI's ?
For example :
GET uri_servicename?param1=value1
I want to extract this param1 and value1 if they exist in the URI.
Edit: I wanted to save them as variables.
| Got to know a method called query_string() under <cppcms/http_request.h> which gives the whole query string including all parameters and values in the http request.
We can use it as:
std::string paramlist = request().query_string();
Reference:
http://cppcms.com/cppcms_ref/latest/classcppcms_1_1http_1_1request.html
|
63,655,249 | 63,655,276 | Why do I get errors when I use the overloaded assignment operator, but I don't get using the compiler-supplied one? | I tried my best to only put the most important parts:
header.h
#include <cstdint>
#include <string>
#include <vector>
#include "byte.h" /// doesn't matter what's in here
#pragma once
using int64 = int64_t;
using int32 = int32_t;
/// FORWARD-DECLARATIONS
class BigInt;
/// *** CLASS BIGINT ***
class BigInt
{
std:... | Your operator= returns void, which can't be returned in return res = a.BigInt::operator - (b);, as the error message said, operator + is supposed to return a BigInt.
You should declare operator= as returning BigInt& (as the one generated by compiler does).
BigInt& BigInt::operator = (const BigInt &p)
{
(*this).vec ... |
63,655,564 | 63,655,695 | Can I have a "type of types" in C++? | I'm quite new to C++, but I've been trying to diversify my skillset a bit during the lockdown.
I'm attempting to write a node-based sound processing tool using SFML. I want to have a struct to contain all of my nodes' inputs and outputs. However, I obviously can't connect any type together. I'm looking to do something ... | Yes, you can have a "type of types".
However, notice the user connects nodes at runtime. Thus this is a runtime problem, not something you can solve at compile time.
In other words, simply use runtime values that contain whatever types your nodes accept/send and compare them as needed.
|
63,655,580 | 63,656,262 | How to properly keep track of VBOs and VAOs for cleanup? | Excuse my noobery, but I am one. I am currently trying to figure a way to keep track of VAO and VBO id's so that I can run through them using for loops and tell OpenGL to delete them. My current method is to push them into vectors and run through them backwards at termination, which has been resulting in a segfault. Us... | There is missing the address-of (&) operator
glDeleteVertexArrays(1, (unsigned int*)_vaos[i]);
glDeleteVertexArrays(1, &_vaos[i]);
Alternatively you can do:
glDeleteVertexArrays(1, _vaos.data()+i);
Anyway, you don't need the for loops at all (see std::vector):
void Model::_cleanup()
{
glDeleteVertexArrays(_vaos.s... |
63,655,586 | 63,655,674 | Why can I continue to use the overridden structure even if I redefine the structure as typedef and annotate the typedef line? | Why can I continue to use the overridden structure even if I redefine the structure as typedef and annotate the typedef line?
#include <iostream>
#define MAZE_SIZE 21
#define MENU_H_SIZE 30
#define MENU_V_SIZE 120
using namespace std;
char strMaze[MAZE_SIZE][MAZE_SIZE] = {};
struct _tagPlayerPos
{
int x;
in... |
Why can I continue to use the overridden structure even if I redefine the structure as typedef and annotate the typedef line?
You can't, the compiler doesn't know those names, you must be missing something, maybe you have these typedefs in other files included in main, it's hard to say, the only thing that is certain... |
63,655,780 | 63,704,891 | Instance of object in flex-bison c++ | My main.hpp looks like this :
#include "json.tab.h"
#include "ob.hpp"
extern Ob *ob;
In my test.l, I wrote :
%{
#include "main.hpp"
%}
%token KEY
%token COMMA
%%
KEY_SET : KEY {ob->someOp();}
| KEY_SET COMMA KEY ... | The parser generator looks like this :
%{
#include<stdio.h>
#include "main.h"
#include "json.h"
using namespace Maifee;
%}
...
meaw : INTEGER {Json::ok();}
Header:
#ifndef JSON_H
#define JSON_H
#include <bits/stdc++.h>
using namespace std;
namespace Maifee{
class Json {
publi... |
63,655,839 | 63,665,578 | C++ shared_ptr manipulation logic | I have this logic:
struct Foo;
struct Bar;
struct IComponent {
virtual Foo * GetFoo() { return nullptr; }
virtual Bar * GetBar() { return nullptr; }
}
struct Foo : public IComponent {
Foo * GetFoo() override { return this; }
}
struct Bar : public IComponent {
Bar * GetBar() override { return this; ... | If you don’t want to expose ownership (let alone transfer it) as part of your interface, returning a raw pointer (or some special observer pointer type, if you use such) is plainly the right idea. (In particular, avoid constructions like const std::shared_ptr<T>& foo() that meaninglessly express observation in terms o... |
63,655,886 | 63,655,928 | Can someone explain the behavior of the output while returning an array from function? | Code:
#include<iostream>
using namespace std;
int * arrayReturn();
int main(){
for(int i=0; i<10; i++){
cout<<"Value at "<<i<<": "<<arrayReturn()[i]<<endl;
}
return 0;
}
int * arrayReturn(){
static int arr[] = {10,20,30,40};
return arr;
}
Output:
Question:
Can anyone ple... | I compiled and executed your code.
This is the output:
$ ./sample.o
Value at 0: 10
Value at 1: 20
Value at 2: 30
Value at 3: 40
Value at 4: -346453624
Value at 5: 32646
Value at 6: -346453584
Value at 7: 32646
Value at 8: 6
Value at 9: 0
Please note the values from index 4 onward. They are garbage.
As the original ar... |
63,655,969 | 63,673,086 | Nested dependent names are not evaluated in template for concept | (Originally separated from this question.)
In the following code snippet,
#include <concepts>
template<
typename T,
typename value_type = typename T::value_type
>
concept check_type = std::default_initializable<T>;
struct Foo {};
template<check_type T>
void func(T t) {}
int main()
{
Foo foo;
func(fo... | GCC is correct under the current wording.
Per [temp.deduct]/5, satisfaction checking is done on the associated constraints of the function template:
If the function template has associated constraints ([temp.constr.decl]), those constraints are checked for satisfaction ([temp.constr.constr]).
[temp.constr.decl]/3.2 s... |
63,656,128 | 63,656,191 | glShaderSource crashes | I use:
std::string source;
char value;
std::ifstream stream(paths[id]);
while (stream.get(value)) {
source += value;
}
stream.close()
int shader = glCreateShader(mode);
shaders[id] = shader;
glShaderSource(shader, 1, (const GLchar* const *)source.c_str(), nullptr);
glCompileShader(shader);
A... | The problem is here: (const GLchar* const *)source.c_str(). The fact that it didn't work without a cast (effectively a reinterpret_cast) is a sign that you're doing something wrong.
Save the pointer to a variable: const char *ptr = source.c_str();, then pass &ptr to glShaderSource.
|
63,656,228 | 63,656,311 | Can we add an integer to an array in c++ | #include <bits/stdc++.h>
using namespace std;
/*Prototype for utility functions */
void printArray(int arr[], int size);
void swap(int arr[], int fi, int si, int d);
void leftRotate(int arr[], int d, int n)
{
/* Return If number of elements to be rotated
is zero or equal to array size */
if(d == 0 ... |
Can we add integers to an array in c++ as given in the else part of the left rotate function while passing the arguments (arr+n-d)?
How can we add integers to an array?
The answer is you can't, and that's not what's happening here.
int arr[] argument decays to a pointer to the first element of the array. It's the s... |
63,656,842 | 63,656,862 | C++ error: no match for ‘operator<<’ (operand types are ‘std::istream {aka std::basic_istream}’ and ‘int’) | So I am writing this simple calculator in C++.
The error message says:
main.cpp:38:6: error: no match for ‘operator<<’ (operand types are ‘std::istream {aka std::basic_istream}’ and ‘int’)
cin<<anotherQ;
And the code is:
using namespace std;
int main()
{
int running = 0;
while(running != 1) {
float nu... | You have
cin<<anotherQ;
in your code, which is incorrect.
cin >> anotherQ;
is the correct syntax.
|
63,657,199 | 63,657,314 | Convert int to char then push back to vector | i'm having an issue converting an int into a char. Code looks like :
int main {
int i = 10;
char c[80];
std::vector<char> data;
sprintf(i,"%d",c);
data.push_back(c)
}
But I keep getting a invalid conversion from char* to std::vector ... error. Is there an easier way to convert an integer into a character ... | For starters it seems there is a typo
sprintf(text,"%d",f);
You nean
sprintf( c ,"%d", i );
The value type of this vector
std::vector<char> data;
is char. So in the member function push you have to supply an expression that has the type char. However in this call
data.push_back(c);
you supplied an object of an arra... |
63,657,728 | 63,678,199 | Inserted in set and received Segmentation fault | I created code to convert graph representation (A list of edges -> the adjacency list)
How can i fix error?
I have Segmentation fault in line res[cur.first - 1].insert(cur.second);for input
4 3
3 2
2 1
4 2
My code
#include <bits/stdc++.h>
using namespace std;
pair<int, int> strToSotredPair(const string& s) {
in... | There are a couple of error's in your code because of which you were getting that error.
You wanted the graph edges as strings. So you need to take edge inputs as strings. For that, you would be required to use getline(cin,input) and cin.ignore().
(My suggestion: Do not take inputs as strings because as it is you are ... |
63,658,036 | 63,658,244 | How do I create a dynamic list in template metaprogramming? | I've been trying template metaprogramming and have had some trouble making a dynamic list. I've tried
#include <iostream>
template<int I>
struct Int {
};
template<class _Value, class ..._Others>
struct List {
typedef _Value Value;
typedef List<_Others...> Next;
};
template<class _Value>
struct List<_Value, voi... | You cannot access template parameters using :: syntax. The usual convention is to add type using for types and value constexpr static member for values.
template<int I>
struct Int {
constexpr static auto value=I;
};
Then use
std::cout << _List::Value::value << "\n";. It is not a type, so putting typename there was ... |
63,658,124 | 63,658,317 | Why in C++11 or C++14 does the compiler implicitly delete the copy constructor when I declare a move assignment operator? | I wanted to create a list data structure with an iterator class in it. Everything works well but when I declare a move assignment operator the program doesn't compile if it's using the C++14 or C++11 standards, but works fine in C++17, C++2a.
list.h:
#pragma once
#include <iostream>
template <typename T>
class list {... | return iterator(Head);
Why this works in C++17 is because in C++17 this is guaranteed copy elision. No copy or move takes place here.
In a return statement, when the operand is a prvalue of the same class
type (ignoring cv-qualification) as the function return type:
Prior to C++17, this requires a constructor, but t... |
63,658,378 | 63,658,474 | c++ best way to define a type consisting of a set of fixed integers | i need to work with "indicator" variables I that may take on one of 3 integer values {-1, 0, 1}.
so i would rather not declare
int I;
but rather
indicator_t I;
where the type indicator_t ~ {-1, 0, 1}
if furthermore i can later use I in numerical expressions, as an integer (without casting?), that would be excellent.
qu... | The simplest approach would be to convert the tri-state input into an enum class with 3 fixed discriminators:
enum class indicator_t {
negative = -1,
zero = 0,
positive = 1,
};
There are several nice things with this approach:
It's simple, which makes it easy to understand and maintain
enum class makes it... |
63,658,617 | 63,658,734 | Power Of Two Integers | I am trying to solve a problem regarding power of two integers. The problem description is like below:
Given a positive integer which fits in a 32 bit signed integer, find
if it can be expressed as A^P where P > 1 and A > 0. A and P both
should be integers.
Example:
Input: n = 8
Output: true
8 can be expressed as... | It's using maths to solve this.
9=3^2
Log 9 = log 3^2... Adding log at both side
Log 9 = 2 * log 3...using log property
2 = log 9 / log 3
As you can see the last statement is equivalent to code
double val = log(a) / log(i);
Then it's checking Val - round(val) is 0...if that's true val is the ans otherwise it won't be ... |
63,658,697 | 63,658,874 | Why can't I get this array to properly pull string from a file, it does fine the first pass, but when it loops it fails? | I am trying to pull a series of video game console names from a text file. The text file reads as such,
Nintendo Entertainment System
57
Sega Genesis
34
Microsoft Xbox 360
58
Sony PlayStation 4
261
Atari 2600
26
Nintendo Game Cube
52
So what I set up was a do while to get save the names in an array, then their prices,... | dataFile >> consolePrices[i]; on the first iteration leaves \n in the istream.
Then getline(dataFile, consoleNames[i]); extracts that new line symbol on the second iteration and you get the empty string. After that dataFile >> consolePrices[i]; tries to read int but meets the string Sega Genesis, leaves the consolePric... |
63,658,926 | 63,659,497 | Arduino servo object does not work within my own library | I have written a libary for somebody else to slowly sweep servo's from one position to another. It did not work like I intented and I had to remove the servo objects from the library. Instead I let the new version calculate the servo positions and return those values instead. Yet I really like to know why it is not wor... | The problem is most likely in your constructor. These lines:
servo.write( pos ) ;
servo.attach( servoPin ) ;
in the constructor are trying to work with hardware that may not be ready yet. You are calling the constructor at global scope, so these things may be happening before init() runs and sets up the hardware. S... |
63,659,755 | 63,659,948 | C++ How to find position of last occurrence of element in vector | Let's say I have a vector with the numbers: 10 10 58 31 63 40 76. I want to find the position of the last occurrence of the minimum element. The minimum element is 10. The position of the last occurrence of 10 is 1.
I've tried using reverse iterators, but I'm still a little bit confused.
| Assuming the vector:
std::vector<int> v = { 10, 10, 58, 31, 63, 40, 76 };
You can get the last minimum element using reverse iterators and std::min_element:
auto last_min = std::min_element(std::rbegin(v), std::rend(v));
Then get the distance from the beginning of the vector using std::distance and the "base" of the ... |
63,660,194 | 63,661,232 | Compare a string with another string inside an array | Good afternoon,
I'm currently working on an assignment with a custom programming environment using a sublanguage of c++ that lacks some of it's features.
I have written this code:
char comparameEsto(char voy, char vengo, pueblo sitios1, pueblo sitios2, pueblo sitios3,pueblo sitios4){
bool encontradoOrigen;
boo... | char copia declares just a single character. To declare a string, you have to create an array.
#define MAX_STRING_SIZE 30
char copia[MAX_STRING_SIZE];
for(int i=0; i<13;i++){
strcpy(copia,sitios1[i]);
}
|
63,660,290 | 63,660,314 | For loop inside method of class not running? | The for loop inside the method myMethod() isn't running
| You should be initializing i.
for(int i = 0; i < n; ++i) {
Also, you should definitely learn to use the debugger. Then, you can step through the code. You can see what i is, you can see what n is, and you can see where the execution path is not what you expected.
|
63,660,646 | 63,660,782 | Getting "json.hpp: No such file or directory" error despite having json.hpp in the same folder as main.cpp | I'm trying to integrate the json c++ library from nlohmann, while simply copying the 'single_include' file to the same directory as my main.cpp file. As per the integration instructions
#include <nlohmann/json.hpp>
// for convenience
using json = nlohmann::json;
But for some reason the compiler thinks that no such f... | In C++, when headers are surrounded by angle brackets (<>), it searches for the headers in the include paths, which usually do not include the directory that your main.cpp file is located unless explicitly configured otherwise. However, when your headers are surrounded by double quotes, it searches the current director... |
63,660,715 | 63,660,844 | How Can I Find Inorder Successor Or Predecessor In A Set In C++ STL | A Set in C++ STL is implemented Using Red Black/ AVL Tree Or Any Other Self Balancing tree. So, How can i find inorder successor or inorder predecessor in it??
| set<int> s;
for (int i = 0; i < n; i++) {
s.insert(i);
}
// returns an iterator pointing to x
auto p = s.insert(x);
// inorder successor can be found with incrementing iterator
// if it doesn't exists iterator to end to will be returned
if (++p.first != s.end()) {
cout << *p.first << endl;
}
|
63,660,739 | 63,663,739 | Vector<unsinged char> Transformation to String and Back | I'm trying to:
vector to string
Convert this string to const char*
Insert it to the database column of type VARCHAR(8192) without text or blob binding
Read it from database
Convert this string to vector
Result vector must be unchanged from the one inserted on 1.
Minimal Reproducible example:
vector<unsigned char> fro... | The right way to do this is to use base64 encoding and decoding.
Its commonly used and will work without blob_binding.
Withdraw of this, is a performance penalty.
|
63,660,771 | 63,665,204 | Problem with Eigen natural log function: "implicit instantiation of undefined template" | I am working on a chemistry simulation that uses Eigen for calculations involving linear algebra.
Here is my code for determining gibbs free energy yield given a current vector of substrate concentrations:
#define R 8.314 // Gas constant - J mol^-1 K^-1
#define T 298.0 // Temperature - K
typedef Eigen::MatrixXf Ma... | Most of Eigen's coefficient-wise operations, including .log(), refer to Array objects. The coefficient-wise log operation cannot be applied to the Matrix type used in your example (or to the Vector typedef, which is just a special case of Matrix).
Using .array() and .matrix() makes it possible to switch between the ty... |
63,660,834 | 63,661,453 | How to Strip the header from data received using recv in c++? | I have made this code below to download large file and save it to file. (I removed not important parts)
int nDataLength;
int i = 0;
static char buffer[4096];
while ((nDataLength = recv(Socket, buffer, sizeof(buffer), NULL)) > 0)
{
//MessageBoxA(0, std::to_string(nDataLength).c_str(), "TEST", 0);
fwrite(buffer, ... | OK, I came up with function that strips header before saving.
int nDataLength;
int i = 0;
static char buffer[4096];
while ((nDataLength = recv(Socket, buffer, sizeof(buffer), NULL)) > 0)
{
char* content = strstr(buffer, "\r\n\r\n");
if (content != NULL) {
std::string s2(buffer);
size_t p = s2.... |
63,661,031 | 63,668,520 | undefined reference to `i2c_smbus_read_block_data(int, unsigned char, unsigned char*)' | I'm trying to read a block of data from an imu (mpu9250) but when building with
g++ mpu.cpp -o mpu i get the following error:
/tmp/cckh5V8w.o: In function 'imu::read_accel()':
mpu_mine9250.cpp:(.text._ZN3imu10read_accelEv[_ZN3imu10read_accelEv]+0x94): undefined reference to 'i2c_smbus_read_block_data(int, unsigned cha... | The solutions was:
1. Using extern C: I was using extern C, but included them in the regular way as well and that caused the problem.
extern "C"
{
#include <linux/i2c.h>
#include <linux/i2c-dev.h>
#include <i2c/smbus.h>
}
2. Linking libraries when building:
g++ -o mpu mpu_mine9250.cpp -li2c
|
63,661,040 | 63,762,396 | std::string failed requirement error in android studio .cpp files | I am trying to integrate C++ with Android Studio via NDK but I am facing an error which says follows
In instantiation of template class 'std::__ndk1::basic_string<char, std::__ndk1::char_traits<char>, std::__ndk1::allocator<char> >' failed requirement '__is_allocator<std::__ndk1::allocator<char>, void, void>::value'; '... | The above arised due to the placement of the folder .
The NDK was by default placed in the C:/User Name/Android/Sdk/Ndk
The space that between the word User and the word Name made it difficult to locate the ndk folder for the IDE.
After shifting the SDK to another location C:/Android/Sdk the project worked successfully... |
63,661,090 | 63,661,121 | move constructor - is `new A()` rvalue? | struct Ex
{
Ex()
{
std::cout<<"Default"<<std::endl;
}
Ex(const Ex &obj)
{
std::cout<<"Copy"<<std::endl;
}
Ex(Ex &&obj)
{
std::cout<<"Move"<<std::endl;
}
};
int main()
{
std::vector<Ex*> myVector;
myVector.push_back( new Ex() );
}
Output:
Default
Is n... | When you do
myVector.push_back( new Ex() );
You call the default constructor Ex::Ex() with new Ex(), which creates a new object on the heap. Then you only push the pointer to this new object to vector, not the object itselt. That means only the pointer is copied, not the object it's pointing to. Thus, there is no need... |
63,661,191 | 63,661,306 | how does std::optional work under the hood? | I just learned about the std::optional feature in c++ 17 along with a few other very useful features...
but there is a few things that I don't understand about std::optional that I would like someone to explain them to me:
first of all as far as I know in std::optional the return value can either be the specified type ... | return {};
will simply call the default constructor of the class.
By giving the class a conversion operator to bool it can be implicitly converted to a bool when needed.
It would look something along the lines of
template <typename T>
class optional {
public:
optional() {}
optional(T t) : has_value(true), ... |
63,661,274 | 63,661,396 | Compile-time computation (C++ v. C) | I understand that the constexpr keyword can be used to perform compile-time computation in C++. For example:
constexpr int factorial(int n)
{
return n <= 1 ? 1 : (n * factorial(n - 1));
}
(taken from https://en.cppreference.com/w/cpp/language/constexpr)
Can compile-time computation be considered a key advantage of... | Only one thing is certain - compile-time computation makes C++ compilers necessarily more complicated and the compilation speed will necessarily be slower, because a compiler is required to do it during compilation time; see for example
constexpr int factorial(int n) {
return n <= 1 ? 1 : (n * factorial(n - 1));
}
... |
63,661,319 | 63,661,521 | What is the common idiom(s) for resetting the moved object? | In C++ move constructor is required to reset the moved object which to me seems to be a duplication of what the destructor does in most of the cases.
Is it correct that defining a reset-method and using it in both destructor and move-constructor is the best approach? Or maybe there are better ways?
| Move constructors typically "steal" the resources held by the argument (e.g. pointers to dynamically-allocated objects, file descriptors, TCP sockets, I/O streams, running threads, etc.) rather than make copies of them, and leave the argument in some valid but otherwise indeterminate state. For some types, such as std:... |
63,661,343 | 63,662,248 | Detecting i386 vs x64 for Windows with C++ Makefile.win? | Sorry if this question is obvious, but I normally don't compile C++ on Windows:
I'm trying to write a Makefile.win whereby I need to link with a specific *dll. In the subdirectory of the library which needs to be linked, there's a /x64 version and a /i386 version, i.e.
.../libs/x64/library.dll
.../libs/i386/library.dll... | Assuming your target is the host machine, I believe you'll have to rely on environment variables. On my PC (Win10) > echo %PROCESSOR_ARCHITECTURE% yields AMD64. As per this article it should be PROCESSOR_ARCHITEW6432, but that's not the case. Thus, the following should be pretty safe to use on multiple Windows versions... |
63,661,400 | 63,661,514 | Variadic function template accepting any pointers (to variable, function, member function, etc) as arguments | struct A
{
void a() {};
};
int b;
template<typename... Args>
void foo(Args... args) {}
template<typename... Args>
void goo(Args*... args) {}
int main()
{
foo(&b, &A::a); //compiles
goo(&b, &A::a); //does not compile
}
Why does goo(&a, &A::a) not compile? Isn't &A::a also a pointer?
Is it possible to cre... | No, pointers-to-members are not really pointers, in the sense that they don't store a (single) address. std::is_pointer returns false for them.
Pointers to functions, on the other hand, are pointers.
If you want to write a function that accepts only pointers-to-members (including member functions), do this:
template <... |
63,661,496 | 63,663,420 | "g++" works in Command Prompt but not in VSCode Terminal | When I type "g++" in Windows Command Prompt, I get this message "g++: fatal error: no input files
compilation terminated.". However, when I try that in the VSCode terminal, I get this message instead "'g++' is not recognized as an internal or external command,
operable program or batch file.". Anyone know how to fix th... | Nevermind. I restarted my computer and that fixed the problem.
|
63,661,577 | 63,661,670 | Cannot calculate number of verticies a model has. (Size of indeterminate array) | I believe my issue is because I am comparing the size of a pointer to the size of a float, instead of comparing the number of elements in the array against a float.
Model::Model(float* p_pos)
{
// Determine vertex count
m_vertexCount = (sizeof(p_pos) / sizeof(float)) / 3;
If I pass not as float* p_pos, but ins... | C arrays decay to pointers when passed as a function argument, so you cannot extract the length. If you want to know the length when passed to the function, you have 3 choices:
Switch to std::array
Pass the length of the array along with the array
Switch to std::vector
|
63,661,689 | 63,661,816 | Check if a stack is palindrome | In a recent coding interview I was asked to solve a problem in which the task was to complete a function which receives a stack as an argument by reference and checks if the passed stack is palindrome or not. I did come up with an approach but it's not at all a good approach according to me.
My Code
#include <iostream>... | One approach to this would be to pop half of the stack, push onto another stack and compare them. For example:
[A, B, C, B, A] // our stack, where right is top
-> [A, B, C, B], [A] // pop A, push A onto temporary stack
-> [A, B, C], [A, B] // pop B, push B
-> [A, B], [A, B] // pop C, discard C
... |
63,661,787 | 63,661,887 | Resource Folder In Cmake | I have a project like this:
- root/
- main/
- include/
- *.h
- res/
- *.txt
- src/
- *.c
CMakeListst.txt
- CMakeLists.txt
The res folder is the folder with a bunch of text files which my application reads.
This is how my root/CMakeLists.txt lo... | I believe you misunderstand what add_executable does. It will generally just pass the files specified in it to the compiler.
As the compiler presumably doesn't know how to process your foo.txt, it ignores it (i'm actually surprised that it does not complain). What happens in your CMakeLists file is roughly equivalent t... |
63,661,824 | 63,661,852 | How do I print only the file part of a full pathname? | Here is a quick recreation of the problem I'm facing:
#include <iostream>
#include <cstring>
int main()
{
char path[100] = "home/user/cvs/test/VSCode/Test.dll";
char *pos = strrchr(path, '/');
if (pos != NULL)
{
*pos = '\0';
}
printf("%s", path);
}
I find the last "/" in the path name, and need to pr... | After calling strrchr, pos will point to the last occurrence of /. If you advance it by one, it will point to the beginning of the filename:
char *pos = strrchr(path, '/');
if (pos != NULL)
{
++pos;
printf("%s", pos); /* Note - printing pos, not path! */
}
|
63,661,966 | 63,662,010 | Find out if two string inputs are anagram, ignoring white spaces, punctuation, and numbers | I am trying to find out if two string inputs are an anagram. The program has to ignore white spaces, punctuation, and numbers.
I have a function that validates each character in the input stream. When I run the program, it puts two white spaces after I input the first string. It also gives the wrong output.
#include <i... | You're missing a return true; at the end of your areAnagram function.
|
63,662,117 | 63,662,465 | Will "#include"s in C++ still work on other PCs if they have absolute paths? | I have a question about how exactly C++ #include statements work. So, let's say you have something like this:
#include <C:\path\to\library\header.h>
An #include with an absolute path.
Now, say you run your program which requires this library. Will it still work on another computer, even if it is not a standard library... |
Will “#include”s in C++ still work on other PCs if they have absolute paths?
On the condition that the system where the program is compiled has that file in the specified path, yes they work. However, this is not a reasonable requirement.
Will the header be included in your .exe file, or does #include search for the... |
63,662,264 | 63,662,454 | Template parameter type deduction for pointer vs. nullptr_t | Consider the following C++ program:
#include <cstdlib>
#include <functional>
#include <iostream>
#include <string>
#include <utility>
namespace {
template <typename Result, typename... Arg>
Result call_fn(std::function<Result(Arg...)> fn, Arg&&... arg) {
return fn(std::forward<Arg>(arg)...);
}
std::string test_fn... | The problem is the conflict in deduction rules for Arg... on one hand the std::function<...> defines it on the other the input arguments define it.
You should just use std::invoke instead of call_fn or use typename... Args2 for input parameters. Or you can drop the requirement for input to be a std::function and just a... |
63,662,597 | 63,682,926 | Getting the QTransform of a resizable selection area | I have built a small custom qml item that is used as a selection area (something like the QRubberBand component provided in Qt Widgets). The item also give the ability to user to resize the content of the selection, so by grabbing the bottom corner of the selection rectangle it is possible to drag to enlarge the conten... | The problem lies in this assumption:
QTransform::scale assumes that the center point of the transformation is the center of the object
All transformations performed by QTransform are referred to the origin of the axis, is just an application of various tranformation matrixes (https://en.wikipedia.org/wiki/Transformat... |
63,662,764 | 63,663,086 | How to return a C-String from a function and display it | I can't get my program to display the whole c-string, it only displays the first letter! I am trying to write a function that asks the user to input 2 c-strings. I then have a separate function to determine which c-sting is greater alphabetically, and another to display. Every time it displays the c-strings it only dis... | You have several issues with your code, not withstanding the obvious one of not using std::string.
Issue 1:
const char findBigger(char *c, char *d)
{
if (strcmp(c, d) == 0)
return *c;
else if (strcmp(c, d) < 0)
return *c;
else if (strcmp(c, d) > 0)
return *d;
}
This function should... |
63,662,796 | 63,663,828 | Why is OpenDDS failing to compile? | My friend is trying to compile OpenDDS from here:
OpenDDS Insall Directions
I have no code.. but i need this to make pastebin work?
She has followed that link to a T. And it produces these errors:
Errors
Here is the full output from Visual Studio:
Output
The interesting part:
I can compile it just fine using the instr... | This was fixed in this PR: https://github.com/objectcomputing/OpenDDS/pull/1701, but that hasn't made it into a release yet. I can't comment in the comment chain above, but dxiv is correct that this is caused by an include dependency that broke in VS2019. It's only in the dds/DCPS/Serializer.h header though, so just ha... |
63,662,890 | 63,663,083 | In what situation do I have to use a std::function? | It's hard for me to imagine a genuine use case for std::function that couldn't be covered by a template. Every time I consider using std::function, I find a way to avoid it:
// implementation using std::function
void forEach(std::array<int, 100> &data, const std::function<void(int&)> &f)
{
for (size_t i = 0; i < 10... | std::function type-erases a callable type and makes it possible to treat them homogenously.
For example, you can have a vector of callbacks:
std::vector<std::function<int(std::string)>> callbacks;
|
63,662,959 | 63,663,048 | Push pop top in stack c ++ | I have an empty stack of integers,and q queries in the following format:
Push x : add x in the top of the stack
Pop: remove the top of the stack
Top: print the top of the stack
Example
Input:
10
Push 5
Top
Push 6
Top
Push 3
Top
Pop
Top
Pop
Top
Output:
5
6
3
6
5
I will put my code in comment because I don't know how to ... | I don't see the purpose of the for loop, as coded. Instead, (and taking ajourney's answer on board), I would do:
int main()
{
stack<int>st;
for ( ; ; )
{
string s;
cin >> s;
if(s=="push")
{
int a;
cin>>a;
st.push(a);
}
i... |
63,663,210 | 63,853,762 | detect start / end of signal peak in time stamp - data series | I have a data file contains timestamps - data signals.
I was trying to detect the peak of the signals as well as the start and end of the peaks.
Referred to this post, I could detect the peak with no issue.
The questions is how to robustly detect the start / end of the peak signals?
How do I detect the start of continu... | I followed this matlab findpeaks link to define the start and end of peaks.
It describes the definition of prominence (thus the width) of peaks.
|
63,663,520 | 63,663,901 | global const objects in cpp with no runtime initialization | How can I declare a global const object in cpp so that its associated data is fully stored in .rodata instead of the object being created during runtime initialization and needlessly copied?
For example if I make globals of type
const std::string
const std::array<const std::string, 4>
const std::map<std::string, const... | You can define objects at compile-time by defining a constructor that supports it. Note that the members of the object should also be const.
In the following example, we create an object foo at compile time. We can validate this with the static_assert function. On the other hand, foo2 is created at runtime. Unfortunate... |
63,663,847 | 63,663,973 | C++ How do I check if an object is in an array? | I'm new to c++ and I'm making my first project with it. I have an array with some strings in it and I need my code to check if an input is in that array, store it and continue with the code but I don't know how.
Code:
#include <iostream>
using namespace std;
int battleCapacity;
string T1P1;
string pokemonlist[] = {"B... | If You want to add something to the array it is much more prefarable to use vector instead of a regular array, as are of a fixed size.
that said, here is a simple function to find a string in the vector:
bool stringInVector(vector<string> list, string str)
{
for(int i = 0; i < list.size(); i++)
{
if(lis... |
63,664,252 | 63,672,095 | Why do we use pointers to pointers while declaring dynamic 2d array in c++? | Can anyone explain why we use pointers to pointers (**) when declaring a dynamic 2D array in C++? I don't get why we use a loop for it.
using namespace std;
int main(){
int **matrixPtr;//2d array declaretion
cout << "enter no of rows: ";
int row;//defining row
cin >> row;//initializing value of row fr... | Roughly a 2D matrix is just a 1D matrix whose elements are 1D matrix of elementary elements, thus an array of array. Right?
Then if you want to allocate it dynamic you have:
the type for the elements, say int,
the type for storing a dynamic array of elements, then int *, pointer to int; how many, say cols,
the type fo... |
63,664,262 | 63,664,325 | Deal with overflow for character vector | Suppose I have a vector:
std::vector<char>& over;
and somewhere in my code I have an input that allows me to assign data to that character vector.
I understand that an unsigned char has a bit size of 255 such that if I input 256 characters into that char array at once the program will overflow. But what if I need to p... | You mixed type overflow with vector size.
Overflow of a type means: the calculation result is out of the type's defined range.
Example: https://godbolt.org/z/3o7jqq
#include <iostream>
#include <limits>
int main(int, char**)
{
unsigned char a{std::numeric_limits<unsigned char>::max()};
std::cout<< +a << ... |
63,664,364 | 63,664,600 | Having problem in working with insert, delete and search in an string array at the same time | I was trying to implement insert, delete and linear search in an string type array in the same code. Delete and Linear search works fine here, but insertion is not running perfectly.
Here is the main function of my code.
#include<iostream>
#include <stdlib.h>
#include<stdio.h>
#include<algorithm>
#include<string.h> ... | As rightly said by some authors , what is required by you should not be done by fixed memory allocation , instead dynamic memory allocation (example : vectors in c++) should be used. However since you wanted to try the fixed one still, you can do the following :
Declare a string array of a larger size, instead of the ... |
63,664,366 | 63,664,417 | Program finding product of two numbers | In this program what is the null case condition I have to put into it when the input is null so that the program in this case
//*product of two no.s*//
#include<iostream>
using namespace std;
int main()
{
double firstnumber,secondnumber,productoftwonumbers;
cout<< "Enter two numbers :";
cin>> firstnumb... | If what your asking is finding out if there are no 0's in the input then here's the solution:
Add this after cin>> firstnumber>>secondnumber;
if(firstnumber == 0 || secondnumber == 0) return 1;
If you're looking for something else we need a better explanation.
|
63,664,916 | 63,664,952 | Use template parameter to pass both node type and data type for a linked list | In my linked list class I want to pass the dataType of the data to store as a template parameter as well as the node type that contains the data, but I keep getting compile error.
Heres the node class
llist.h
template<class itemType>
class Node {
itemType item{};
Node* next{};
Node* prev{};
public:
Node... | If you want to use nodeType as template like nodeType<itemType>, you can declare it as template template parameter.
template <class itemType, template <typename> class nodeType>
class LinkedList
Then use it like
LinkedList<int, Node> list;
LIVE
If you want to declare it as type template parameter as you're doing now,... |
63,665,368 | 63,666,068 | String input length greater than 4 gives segmentation fault | The problem is that this code works well for input string of size 4 but for size more than 4 it gives segmentation fault.
The problem is to check the index of all anagrams of a string in another string.
for example: for string1 input abab and string2 input ab - it works good but for BACDGABCDA and ABCD gives segmentati... | Your string temp has always a length of 4. Variable k is const 4. Variable i starts at 4 and goes up to 9. So after some iterations you try to erase elements after the end of your string temp.
Using a debugger or adding some additional checks in your code will provide a faster answer to such issues than just asking oth... |
63,665,757 | 63,667,215 | how to get output of a wrong command with libssh | I have this function which can connect to a remote system via ssh:
std::string _ErrMsg;
int _RetVal = 0;
MyException errMsg;
int port = 22;
try
{
if (my_ssh_session == NULL) {
std::cout << "Error creating ssh session" << std::endl;
throw MyException("Error i... | Errors are printed on the stderr channel, which is distinct from the default stdout channel.
The last argument of ssh_channel_read determines which is read: 0 for stdout, 1 for stderr.
I suggest you read from both channels by calling ssh_channel_read twice.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.