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 |
|---|---|---|---|---|
71,677,501 | 71,724,924 | Radix sort get the right key to sort signed integers | I have a trouble with finding a right value for sorting with radix sorting algorithm.
I have implemented it right, but I have an issue with negatives. I tried just to reverse value with a binary. It helped me a little, but negatives are in ascending order instead of being in descending order. Funniest thing is that sor... | Sort key formula that you need is very simple:
uint32_t SortKeyToU32(int32_t Value) {
return uint32_t(Value) + (1U << 31);
}
the reason for it following. First we cast from 32-bit signed to unsigned. This casting just reinterprets bits of signed value as unsigned.
Lets see how signed values are presented in value ... |
71,677,547 | 71,677,645 | Does C++ constructor return an object? | All books and internet pages I read say that C++ constructors do not have a return value and they just initialize an object:
#include <iostream>
class Number {
int m_val{};
public:
Number() = default;
Number(int val) : m_val(val) {}
int val() { return m_val; }
};
int main() {
Number n; // Initi... | Indeed a constructor doesn't have a return value.
But Number(10) is an object of type Number. And that is an expression with a value.
|
71,678,240 | 71,736,898 | CGAL read_OFF discards face depending on vertex order | When reading an off-file with cgal it appears that the vertex order of a face decides whether or not it is read in by read_OFF. But the off-file definition does not say anything about the vertex order of a face.
I am reading in self generated off-files using the read_OFF method of cgal:
using Kernel = CGAL::Exact_predi... | one_face_read.off does not define a valid surface mesh has the orientation of the two faces are not compatible. You can use the following function to read points and faces and call CGAL::Polygon_mesh_processing::is_polygon_soup_a_polygon_mesh() to check if the input is a valid surface mesh. The function CGAL::Polygon_m... |
71,678,278 | 71,678,443 | How to declare member template of class template as friend? | Given the following code:
template <typename T, typename D> class B;
template <typename T>
class A {
public:
A() { }
template <typename D>
A(B<T, D>);
};
template <typename T, typename D>
class B {
friend A<T>::A(B<T, D>);
int x;
};
template <typename T>
template <typename D>
A<T>::A(B<T, D> b) {
b.x = 4... | The important part of the error message seems to be this line:
test.cc:8:3: error: template<class D> A<T>::A(B<T, D>) [with D = D; T = int]
Notice how the template type D is not expanded to the actual type.
That lead me to believe that adding a new template type for the friend declaration might help:
t... |
71,678,379 | 71,680,560 | How to using boost::multi_index with struct in struct? | I have a vector containing information called ST_ThepInfo.
My problem is when using struct ST_ThepInfo in struct Infovalue_t.
struct ST_ThepInfo
{
int length;
string ex;
int weight;
};
struct Infovalue_t {
ST_ThepInfo s;
int i;
};
struct ST_ThepInfo_tag {};
typedef boost::multi_index_container<... | Hashed indexes require the key type to be hashable and equality-comparable.
You need to provide these for the info struct:
Live On Coliru
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/random_access_index.hpp>
#include <boost/multi_index_container.hpp>
... |
71,678,559 | 71,678,795 | How can you change the value of a string pointer that is passed to a function in C++? | I need to change the value of a std::string using a function.
The function must be void, and the parameter must be a pointer to a string as shown.
#include <iostream>
void changeToBanana(std::string *s) {
std::string strGet = "banana";
std::string strVal = strGet;
s = &strVal;
}
int main() {
std::... |
The function must be void, and the parameter must be a pointer to a string as shown.
With this requirements you cannot change the value of the pointer that is passed to the function, because it is passed by value.
Don't confuse the pointer with what it points to. Parameters are passed by value (unless you pass them b... |
71,679,130 | 71,682,074 | Storing variadic unique_ptr pack into a tuple | I am trying to write a constructor that takes a variadic pack of unique_ptrs as argument and store it in a tuple:
template<class... E>
class A
{
std::tuple<std::unique_ptr<E>...> a_;
public:
A(std::unique_ptr<E>&&... a)
: a_(std::make_tuple(std::move(a)...)) {}
};
but thi... | It looks like in this case the issue is just that your variable is type A<double> but you are passing two values, so you need to use A<double, double>.
A<double, double> obj(std::make_unique<double>(2.0), std::make_unique<double>(3.0));
Alternatively, you can eliminate the need to state template parameters if you decl... |
71,679,224 | 71,679,513 | error C2672 and C2784 when using lamdas with template functions | I have written the following function which hides the loops when iterating over a 2d vector:
template<typename ElementType>
void iterateOver2DVector(std::vector<std::vector<ElementType>> & vec,
std::function<void(ElementType & element)> function)
{
for(auto & row : vec)... | The call will try to deduce ElementType from both the first and second parameter/argument pair.
It will fail for the second pair, since the second argument to the function is not a std::function, but a closure type.
If it fails for one pair, then the whole deduction fails, even if the other pair would deduce the templa... |
71,679,270 | 71,679,386 | Ordering coordinates c++ | I'm trying to order a list of coordinates in c++, but it's not working.
i'm using c++ sort function, and first ordering the x values and then the y values
if n = 9 and the coordinates:
(2,2) (2,3) (1,2) (1,3) (2,1) (1,1) (3,2) (3,3) (3,1)
the output should be:
(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3 ,3)
Bu... | Your comparison is flawed:
bool comparey(coord a, coord b){
if(a.x == b.x && a.y < b.y){
return 1;
} else return 0;
}
You always return 0 (should be false) when a.x != b.x. For example comparey({0,1}, {1,1}) == false but also comparey({1,1},{0,1}) == false.
You can use std::pair for the comparison... |
71,679,698 | 71,680,854 | Initialization of a base class reference from a derived class member | I have two classes, Base and Derived. Derived constructs Base using its own member object, which inherits from Base::BaseChild.
struct Base
{
struct BaseChild
{
int x = 5;
};
Base(BaseChild& c): baseData(c), constantVar(c.x)
{
assert(constantVar == 5);
}
int getX() const {ret... | The base class Base of Derived is constructed before the member data.
As a result data will not be initialized when you pass a reference to it to Base's constructor. The initialization will happen after that constructor call.
You are however trying to read the member x of data in Base's constructor. At this point data'... |
71,680,595 | 71,680,635 | Is a constructor a function and is it possible to call a constructor | I came across this where one of the user comment says:
A constructor cannot be called, it is not a function. It is invoked automatically when a new object is created.
My question is that is the above comment true/correct? If yes, then why isn't a constructor considered a function and why can't we call it?
| Formally in the C++ Standard it is (along with several others) a special member function so yes it is a function, but it is a special function and not all of the normal rules apply.
There is no syntax to write code that calls a constructor directly or forming a function pointer to it. The Standard specifically says "C... |
71,680,931 | 71,769,940 | Why does this OpenMP code compile with g++, but fail with nvcc? | I'm trying to compile this code that uses OpenMP. When I compile it with nvcc, it gives an error that appears to be complaining about a token that isn't even there.
Here's a minimal version of my code:
int main() {
// this loop somehow prevents the second one from compiling
for (int foo = 0; foo < 10; foo++) ... | There is evidently a defect in CUDA 11.2 as far as this code example goes.
The problem appears to be resolved in CUDA 11.4 and later.
The solution is to upgrade the CUDA install to CUDA 11.4 or later.
|
71,680,983 | 71,681,678 | Why is newer version of g++ saying `static_assert(is_trivial_v<_CharT> && is_standard_layout_v<_CharT>);` when class did not change? | In the following, the my_char class is said to not be trivial. I'm thinking that maybe the compiler is wrong, but maybe you know better than me what is wrong.
In file included from /usr/include/c++/11/bits/basic_string.h:48,
from /usr/include/c++/11/string:55,
from /usr/include/c++/11/bits/locale_classes.h:40,
from /u... | Your class my_char is not suitable as a character type for basic_string. From cpp-reference:
The class template basic_string stores and manipulates sequences of char-like objects, which are non-array objects of trivial standard-layout type.
and if you follow the definition of trivial, we have among other requirements... |
71,681,003 | 71,682,298 | C++ map fast 1,2,3 integers to hardcoded chars? | I need to map int values 1,2,3 to chars 'C', 'M', 'A'
Whats the fastest way (this will be called 100s times per sec 24/7)?
a macro or an inline function and bunch of ?: operators or ifs or switch? or an array?
| A lookup-table seems the most obvious approach as it is also branch-free:
constexpr char map(std::size_t i) {
constexpr char table[] = "0CMA";
// if in doubt add bounds checking for i, but it will cost performance
return table[i];
}
Observe that with optimisation, the lookup table boils down to an integer consta... |
71,681,204 | 71,681,334 | constructor for a polynomial class that must initialize the coefficients although the degree is unknown | i have this question:
You will implement a polynomial class that uses a dynamic array to store the polynomial's coefficients.
The Polynomial class has two private members variables: a dynamic array to store the
coefficients and the degree of the polynomial like so:
(private:
double *coef; // Pointer to the dynamic arra... | I suggest creating a struct Term:
struct Term
{
int coefficient;
int power;
};
A polynomial, by definition is a container (or sum) of terms:
class Polynomial
{
public:
std::vector<Term> terms;
Polynomial(int coef1, int constant1);
}
In the above class, the constructor will create two terms:
Polynom... |
71,681,274 | 71,681,632 | Does GCC 7.3 omit the [[nodiscard]] attribute for reference returning member functions? | I've got the following code utilizing the [[nodiscard]] attribute of C++17.
class SomeClass {
public: /** Methods **/
[[nodiscard]] int getValue() { return n; }
[[nodiscard]] int &getRef() { return n; }
[[nodiscard]] int *getPtr() { return &n; }
private: /** Members **/
int n{5};
};
int main()
{... | Yes, it is a bug. It was fixed in GCC 8 as you have already realized.
Bug report: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80896
|
71,681,431 | 71,681,598 | c++ standard_layout for ref types | I'm trying to understand why standard_layout does not apply to ref types?
#include <type_traits>
struct X {
int y;
};
static_assert(std::is_standard_layout_v<X>);
static_assert(std::is_standard_layout_v<X&>); // does not compile
| As you've found, is_standard_layout only works with an object type, not a reference.
As such, if you want either a type or a reference to a type, you could use:
static_assert(std::is_standard_layout_v<std::remove_reference_t<X>>);
remove_reference_t will yield the referred-to type for a reference, or the type itself i... |
71,681,457 | 71,681,529 | accessing struct members using pointer to pointer | I have a program like below, when I try to access a struct member using pointer to pointer it says the expression must have a pointer to class type. Please tell me how can I access data element of the struct object using a pointer to pointer
#include "stdafx.h"
#include<iostream>
struct Node{
int data;
Node* ne... | In *node->data = val; there are 3 operators involved.
operator* to dereference
operator-> to access a member
operator= to do the assignment
In which order will these happen? According to operator precedence which states:
Precedence
Operator
2
operator->
3
operator*
16
operator=
node->data will happen ... |
71,681,675 | 72,745,846 | How to recompile a single .cc file in a project built previously with CMake tool in Ubuntu 20.04? | I am using the ORB_SLAM3 project (https://github.com/UZ-SLAMLab/ORB_SLAM3) as a baseline for a monocular odometry system.
To understand how the ORB_SLAM3 software ingests the EuRoCV dataset, I am modifying some of the initial codes in the mono_euroc.cc file available in /Examples/Monocular folder.
However, each time I ... | For the time being, I am following this process. I opened two terminal windows, both pointing to the parent directory (i.e ~/Dev/ORB_SLAM3). Everytime I change something in the target file (here it is the ./Examples/Monocular/euroc_mono) I execture the ./build.sh command in one and run the file on the other. I can conf... |
71,681,765 | 71,682,448 | Ambiguous constructor overload on GCC, but not on Clang | Let's say we have the following simple code:
#include <iostream>
#include <type_traits>
struct S {
template <typename T> explicit S(T) noexcept requires std::is_signed<T>::value {
std::cout << "T\n";
}
template<typename T> explicit S(const T&) noexcept {
std::cout << "const T&\n";
}
};
... | GCC is correct. It's ambiguous.
First, we have to look at the implicit conversion sequences. In both cases, the identity conversion sequence is involved: int to int, and int to const int& (the latter is considered the identity conversion sequence thanks to [over.ics.ref]/1).
Second, we look at the tie-breaker rules reg... |
71,683,269 | 71,683,425 | Pattern matching with variadic templates and default argument | I'm trying to add a default "hidden" setting into a templated class:
template<bool DebugMode=false, typename... Args>
struct A
{
A() {};
};
int main()
{
A<double, double> a;
}
which fails when compile with g++ 8.3.1 and C++17:
error: type/value mismatch at argument 1 in template parameter list for ‘templa... | It's basically the same as with default function arguments: You can only omit parameters from the right. And I don't expect this to change, also because what you want to do can be achieved by adding a layer of indirection:
template<bool DebugMode=false>
struct Wrap {
template <typename ...T> struct A {};
};
templa... |
71,684,134 | 71,684,178 | Why is this partial template specialization failing? | Here is my code.
#include <iostream>
template<class> struct IsInteger;
template<class> struct IsInteger { using value = std::false_type; };
template<> struct IsInteger<int> { using value = std::true_type; };
int main()
{
std::cout << std::boolalpha <<
IsInteger<5>::value::value << '\n';
}
Above code results i... | You need to use your trait as IsInteger<int> instead of IsInteger<5>.
Also, the idiomatic way to use std::true_type and std::false_type in cases like this is to inherit from them, instead of aliasing them as value:
template<class> struct IsInteger : std::false_type {};
template<> struct IsInteger<int> : std::true_type ... |
71,684,205 | 71,684,414 | C++ Improve time complexity | I would like to ask for tips on how to improve the time complexity of the program.
I can't change the interface (function headers)
For example, if I do sort before find (), will it have any effect?
Or are there any alternatives to my code.
Thank you for all the advice
In the link to the whole program, here is a part of... | You are storing companies in a vector. In multiple methods, the vector is sorted and the searched.
do not sort the vector again if it is already sorted
as pointed out, use a binary search instead of std::find
or use a hash-based container, e.g. std::unordered_set to store the companies. This should make most operation... |
71,684,499 | 71,684,656 | I cant read a binary file with C-STYLE. Problem with strings c++ | For some reason, I can't read a file that contains "string"s with C-style. If I use an array of characters, then I can do it. But I want to do strings and I would like to know how to do it. When I print the b."x attribute" it shows random characters.
And yes, I know I should be using c++ files. But this is purely for a... | You try to write 'boleta'
struct Boleta
{
string name;
string surename;
string legajo //156.455-6;
int cod_materia;
string date // 2022/10/26;
};
to a file like this
fwrite(&boleta, sizeof(boleta), 1, f);
this will not work. std::string is a pointer to the actual string data, the actual string is... |
71,684,608 | 71,684,792 | How to properly print enum type | I have this class code in c++:
#include <iostream>
#include <cstring>
using namespace std;
enum tip{txt,
pdf,
exe
};
class File{
private:
char *imeDatoteka{nullptr};
tip t;
char *imeSopstvenik{nullptr};
int goleminaFile = 0;
public:
File(){}
File(char *i, char *imeS, int golemina, tip tip)... | You could create a lookup table using map and string:
#include <map>
#include <string>
std::map<tip, std::string> tip_to_string = {
{txt, "txt"},
{pdf, "pdf"},
{exe, "exe"}
};
And then when you want to print some tip t:
std::cout << tip_to_string.at(t) << std::endl;
Or you could do a function:
std::strin... |
71,684,938 | 71,693,525 | Two versions of a code based on a #define | I'm working with a microcontroller and writing in C/C++ and I want to separate stuff that's supposed to work only in the transmissor and stuff that will work for the receiver. For this I thought about having a #define DEVICE 0 being 0 for transmissor and 1 for receiver.
How would I use this define to cancel other defin... | You have the following directives:
#if (DEVICE == 0)
...
#else
...
#endif
To be sure the code will be exclusive.
Although I recommended to do it dynamically: you can have a boolean global attribute/function parameter and execute code according to its value.
The code will be optimized-out on a certain target (even... |
71,685,067 | 71,701,798 | Class Inside a Class in C++: Is that heavy? | Suppose I do something like:
class A
{
public:
class B
{
public:
void SomeFunction1() const;
using atype = A;
};
using btype = B;
void SomeFunction2() const;
private:
B b;
};
Then I create an instance of class A and copy it:
A a;
A acopy = a;
Does that make the class A ... | Both possibilities (B as nested class and B as external class) will yield exactly the same performance.
In fact, the compiler will generate the same assembly code in both cases.
B as external class:
https://godbolt.org/z/7voYGd6Mf
B as nested class:
https://godbolt.org/z/731dPdrqo
B is a member of A. Hence it resides i... |
71,685,424 | 71,685,535 | (C++) How do I display an error when more than one "." is used in a calcualtor? | I am making a calculator using command line arguments, and one of the problems I am having is that I can't find a way to display an error to inputs that have more than one ".". 3.33 can be accepted, but 3.3.3.2 cannot because its an invalid number.
int main(int argc, char *argv[]) {
if (argc == 1) {
cout << "E\n... | One way for checking the validity of a string is to use regular expressions, for example, you can use this.
You can write something like this to extract your operands:
float op1, op2;
std::string p1 = argv[1];
std::string p2 = argv[2];
std::regex pattern("[+-]?([0-9]*[.])?[0-9]+");
if (std::regex_match(p1, pattern) &&... |
71,685,459 | 71,685,499 | I'm trying to build a dice program using C++ it isn't displaying my return | The code is printing the greeting and all the messages except the number. I need to see what is being generated by my random number generator.
#include <iostream>
#include <cstdlib>
#include <ctime>
void greeting(int pnum){
if(pnum == 1) {
std::cout << "Please press \"ENTER\" to roll the die";
... | in main you do this
while (ran > 0);
{
return ran;
}
First you never give 'ran' a value, so its either > 0, in which case you exit with a random completion code. Or 'ran' is <= 0, in which case you exit with a value of 0.
Its not clear what you are trying to do here, but either way your program terminates immediat... |
71,685,465 | 71,685,497 | How can I initialize a custom Array class by aggregate initialization? | I have my own basic version of std::array
Here's how it looks:
template<typename T, size_t N>
class Array {
public:
Array()=default;
T& operator[](size_t n) {return m_data[n];}
size_t Size() {return N;}
private:
T m_data[N];
};
I can initialize it this way:
Array<int, 3> arr;
arr[0... | In order for aggregate initialization to work you need to make the class an aggregate class. To achieve this you need to make the array member public. Depending on the standard version you may also need to remove the defaulted default constructor Array()=default; and let it be defined implicitly instead. Don't declare ... |
71,685,930 | 71,685,992 | Data race about map::operator[] | Is there any potential problem in this code snippet?
#include <mutex>
#include <map>
#include <vector>
#include <thread>
constexpr int FOO_NUM = 5;
int main()
{
std::map<int, std::mutex> mp;
std::vector<std::thread> vec;
for(int i=0; i<2; i++)
{
vec.push_back(std::thread([&mp](){
std::lock_guard<std::mutex> ... | Yes, there is a data race, but it is even more fundamental.
None of the containers in the C++ library are thread-safe, in any way. None of their operators are thread safe.
mp[FOO_NUM]
In the shown code multiple execution threads invoke map's [] operator. This is not thread-safe, the operator itself. What's contained i... |
71,686,081 | 71,686,131 | Why isn't constexpr guaranteed to run during compilation? | Why isn't constexpr guaranteed to run during compilation?
Additionally, why was consteval added instead of changing constexpr to guarantee a compile-time execution?
| constexpr already guarantees compile-time evaluation when used on a variable.
If used on a function it is not supposed to enforce compile-time evaluation since you want most functions to be usable at both compile-time and runtime.
consteval allows forcing functions to not be usable at runtime. But that is not all that ... |
71,686,401 | 71,687,139 | C++: How can I sort a string vector of numbers in numerical order? | In my program, I have an empty string vector that gets filled in via user input. The program is meant to take numbers from user input, then sort those numbers in order from smallest to largest (the data type is string to make it easier to check for undesired inputs, such as whitespaces, letters, punctuation marks, etc.... | You can specify a comparision function that returns whether the first argument is "less than" the second argument to the std::sort function.
While testing, I found that some empty strings, which make std::stoi throw std::invalid_argument, are pushed into the vector (it looks like by vect.resize(i+1);). Therefore, I add... |
71,686,910 | 71,687,864 | How to appropriately read in user input without manually inputting it in? | I have been trying to figure out how to read in user input without having to manually type every example out. I am building a stone game that is supposed to familiarize me with circularly linked lists. I have to manually type out examples like this to achieve the output. Is there another approach to replace this, and r... | A useful workaround to obnoxiously long inputs is temporarily using a text file with the std::getline function. Just replace #include <iostream> with #include <fstream> until the program is done.
you can find a pretty good explanation of that in this SO answer.
Edit: you'll also need to change your iostream declaration... |
71,687,088 | 71,687,353 | C++ template recursively print a vector of vector using template | #include <any>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
template<class T>
struct is_vector : std::false_type {};
template<class T>
inline constexpr bool is_vector_v = is_vector<T>::value;
template <typename T>
string VectorToString(const vector<T> &vec)
{
str... |
What should struct is_vector looks like to do this?
It looks like what template partial specialization looks like
template<class T>
struct is_vector : std::false_type {};
template<class T, class Alloc>
struct is_vector<std::vector<T, Alloc>> : std::true_type {};
Demo
|
71,687,711 | 71,687,954 | C++: Implementation of virtual destructor necessary when using inherited structs with only properties? | I know that I need to define a virtual destructor (best option even if my class is final).
In my case, I am using C-like structures (no functions, no defaults, just plain members) and use inheritance to compose a new structure. I then store a pointer to the base class in std::unique_ptr and let RAII do the rest.
I am n... | It doesn't matter whether the class is polymorphic or whether it is trivial.
If delete is called on a pointer of different type (up to cv-qualification) than the most-derived type of the object it points to and the pointed-to-type doesn't have a virtual destructor, then the behavior is undefined.
One obvious reason for... |
71,688,949 | 71,689,061 | Sandard way of implementing c++ multi-threading for collecting data streams and processing | I'm new to c++ development. I'm trying to run infinite functions that are independent of each other.
Problem statement is smiliar to this:
The way I'm trying to implement this is
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <unistd.h>
#include <mutex>
int g_i = 0;
std::mutex g_i_mutex; // prot... | You correctly take a lock inside increment_itr, but your fun function is accessing g_i without acquiring the lock.
Change this:
void increment_itr()
{
const std::lock_guard<std::mutex> lock(g_i_mutex);
g_i += 1;
}
To this
int increment_itr()
{
std::lock_guard<std::mutex> lock(g_i_mutex); // the const wasn't act... |
71,689,137 | 71,689,236 | What is the best way to drop last element using c++20 ranges | Is there any better way to drop last element in container using c++20 ranges than reverse it twice?
#include <iostream>
#include <vector>
#include <ranges>
int main()
{
std::vector<int> foo{1, 2, 3, 4, 5, 6};
for (const auto& d: foo | std::ranges::views::reverse
| std::ranges::vie... | What you need is views::drop_last which comes from p2214 and has a priority of Tier 2.
As the paper says:
We’ll go through the other potential range adapters in this family and
discuss how they could be implemented in terms of existing adapters:
take_last(N) and drop_last(N). views::take_last(N) is equivalent to
view... |
71,689,408 | 71,689,471 | showing multiple windows in opencv | with the following function, I am trying to plot the calculated histogram of a 3 channel photo but when I use the function multiple times it only shows the windows of the last time that it was called and does not show previous ones. How can I change it to show all windows?
void showHistogram(std::vector<cv::Mat... | Only the last image is shown when the same window names are used, so you should add an unique thing to the window name to prevent them to be the same.
For example:
#include <sstream>
void showHistogram(std::vector<cv::Mat>& hists, vector<string> titles)
{
static int windowId = 0;
std::stringstream ... |
71,689,518 | 71,689,578 | Array assignment error in C++, What is wrong with my code? | I am trying this code in CodeBlocks but the result is some random numbers!
I appreciate if you check the code and let me know what my mistake is. It should result in multipliers of 25:
#include <iostream>
using namespace std;
main(){
const int array_size = 10;
int numbers[array_size];
int counter = 0;
... | You are incrementing counter after setting the value of numbers[counter]. After that. numbers[counter] (with the new value of counter) is a new uninitialized element.
You should move the increment after the printing:
#include <iostream>
using namespace std;
int main(){
const int array_size = 10;
int numbers[... |
71,690,353 | 71,690,553 | C++ std::any function that convert std::any of C char-array to string | #include <iostream>
#include <any>
#include <string>
#include <vector>
#include <map>
using namespace std;
string AnyPrint(const std::any &value)
{
cout << size_t(&value) << ", " << value.type().name() << " ";
if (auto x = std::any_cast<int>(&value)) {
return "int(" + std::to_string(*x) + ")";
}... | Type of "555" is const char[4] which might decays to const char*. You handle char*, but not const char*.
Handling const char* fixes your issue:
std::string AnyPrint(const std::any &value)
{
std::cout << size_t(&value) << ", " << value.type().name() << " ";
if (auto x = std::any_cast<int>(&value)) {
r... |
71,690,714 | 71,751,904 | OpenCV numpy to cv::Mat conversion | I inherited an application with opencv, shiboken and pyside and my first task was to update to qt6, pyside6 and opencv 4.5.5. This has gone well so far, I can import the module and make class instances etc. However I have a crash when passing numpy arrays:
I am passing images in the form of numpy arrays through python ... | I finally found a solution. I dont know if this is the correct way of doing it, but it works.
I made a header file that contains
PyMODINIT_FUNC PyInit_cv2();
as a forward declaration and then copied over everything in the modules/python/src2 directory. I assumed this was already happening in the cv2.cpp file, because ... |
71,690,762 | 71,692,030 | How can I connect two classes (which don't know eachother) through public interface (C++) | I'm currently working on a project where everything is horribly mixed with everything. Every file include some others etc..
I want to focus a separating part of this spaghetti code into a library which has to be completely independent from the rest of the code.
The current problem is that some functions FunctionInterna... | You can do like you suggested, override the internal interface in your external code. Then
// how can i received there the InterfaceInternal_foo overrided in External.h ?
just pass a pointer/reference to your class External that extends class InterfaceInternal. Of course your class Internal needs to have methods that... |
71,691,109 | 71,691,359 | Copy constructor and default assignment operator | I have made the following Car class:
class Car
{
private:
int id;
int* data;
public:
Car(int id, int data) : id(id) , data(new int(data)){}
//Car(const Car& rhs) : id(rhs.id) , data(new int(*rhs.data)){}
void print(){std::cout << id << " - " << *data << " - " << data << std::endl;}
};
With the fol... | Lets consider what happens in the 2 cases individually. Also, note that there is difference between initialization and assignment in C++. In particular, Car B=A; is copy-initialization and not copy-assignment.
Case 1
Here we consider the case where there is no user defined copy-constructor. That is, the case where you'... |
71,691,584 | 71,691,664 | Why are the results performed using Code Runner in VScode different from the results performed in a shell? | I try to learn the function fork(). However, the results performed using Code Runner in VScode are different from the results performed in a shell. Just like blew pictures show, I used same commands but get different results.
I know that the second output in shell is right and I would like to know why is the first outp... | It's a buffering issue.
When stdout is connected to an actual terminal it will be line buffered That means the output is actually written to the terminal when the buffer is full, is explicitly flushed, or when you print a newline ('\n').
This is what happens in the second case.
In the first case, VSCode will not run it... |
71,691,612 | 71,692,064 | 2D array to find sum of columns, doesn't display properly | #include <iostream>
#include <iomanip>
using namespace std;
void table(int i[], int j[]);
int m[4][5] = {
{2,5,4,7},
{3,1,2,9},
{4,6,3,0},
};
int main()
{
table({}, {});
}
void table(int i[], int j[]) {
for (int k = 0; k < 5; k++) {
int sum = 0;
for (int l = 0; l < 4; l++) {
sum... | The presented code does not make a sense.
For starters the parameters of the function table are not used. Moreover they are initialized as null pointers after this call
table({}, {});
Also the array m is declared with 4 rows and 5 columns. It means that the last row contains all zeroes and the last column also contai... |
71,691,700 | 71,692,217 | Reducing memory alignment | I want to know if it is possible to "reduce" the alignment of a datatype in C++. For example, the alignment of int is 4; I want to know if it's possible to set the alignment of int to 1 or 2. I tried using the alignas keyword but it didn't seem to work.
I want to know if this is something not being done by my compiler ... | I want to know if it is possible to "reduce" the alignment of a datatype in C++.
It is not possible. From this Draft C++ Standard:
10.6.2 Alignment specifier [dcl.align]
…
5 The combined effect of all
alignment-specifiers in a declaration shall not specify an alignment
that is less strict than the alignment t... |
71,691,749 | 71,691,787 | Is Passing Reference From Child To Parent During Construction UB? | The following is a simplified version of some code.
struct Test {
Test( int &id ) : id( id ) {}
int &id;
};
struct B : Test {
B() : Test( a ) {}
int a;
};
Now, I'm aware that the parent, in this case Test would be created before the B object when a B object is created. Does that then mean that the a v... | Yes your code is fine.
You can use memory addresses and reference to not yet initialized members in the constructor. What you cannot do is using the value before it has been initialized. This would be undefined behavior:
struct BROKEN {
BROKEN( int* id ) : id(*id) {}
int id; // ^ -------- UB
};
s... |
71,691,881 | 71,691,919 | How to avoid "Undefined Reference" error when using my own library in an executable, building the project with CMake? | I'm trying to set up a C++ project using CMake but I think I'm missing something. When I'm trying to use my library in an executable I get the error:
Scanning dependencies of target dynamic-shadows-lib
[ 33%] Linking CXX static library libdynamic-shadows-lib.a
[ 33%] Built target dynamic-shadows-lib
Scanning dependenci... |
# Set sources for ${TARGET_LIB}
target_sources(
${TARGET_LIB}
PUBLIC
${PROJECT_SOURCE_DIR}/src
)
You add source files, not directories. Just:
add_library(... STATIC
src/vec2f.cpp
)
Do not use PROJECT_SOURCE_DIR, it will change when someone does add_subirectory from above. If you want cur... |
71,691,888 | 71,692,095 | Why can I not pass a numeric template parameter to my templated function? | I have a custom class encapsulating a std::tuple ("MyTuple") and another class implementing a custom interface for a std::tuple ("MyInterface"). I need this separate interface in the code base, the code below is simplified.
Since elements of std::tuple need to be accessed with the key as template parameter, the interfa... | When you want to call a template method of an instance, you need to write this:
return interface.template getString<Key>();
You'll find every details of why in this answer: Where and why do I have to put the "template" and "typename" keywords?
|
71,692,007 | 71,692,102 | Array of pointers holds the same value for all elements | I'm currently deep-diving into the way pointers work.
Something for me unexplainable happened when executing the following lines of code:
std::vector<OptimizerPlanOperatorPtr> sources;
for (const auto &source : sourceOperators){
OptimizerPlanOperator planOperator = OptimizerPlanOperator(sour... | You are storing the location of an object whose lifetime ends with the current iteration and handing ownership of it to a shared_ptr. Both are problems that lead to undefined behaviour.
Casting a pointer to std::shared_ptr does not automagically make the pointed-to object into a shared object and extend its lifetime, ... |
71,692,143 | 71,871,181 | UHD USRP crash in debug mode | I have a simple receiver application with USRP B200. It works fine in release mode but crashes in debug mode. Program crashes when following method is called.
uhd::usrp::multi_usrp::make(args)
Here the stack view when it crashes:
The program only requires libboost_thread from the boost library. I tried with different... | I found the problem. The same build configuration must be used for UHD binaries. Using release built uhd.dll in debug mode causes the crash.
Unfortunately, The official build of UHD doesn't contain debug builds. Those who need the debug version, need to compile it themselves. Here is the build guide:
https://files.ettu... |
71,692,281 | 71,692,389 | Why is it not possible to return a const reference while overloading the [] operator | Let us take this code as an example
#include <iostream>
using namespace std;
struct valStruct {
double& operator[](int i){return values[i];}; //line 6
double operator[](int i) const {return values[i];}; //line 7
double values[4];
};
int main () {
valStruct vals = {0,1,2,3};
cout << "Value be... |
why do we need line 7 at all since line 6 exists and can do both writing and reading.
We need line 7 to work on const objects. Line 6 can't be used on const objects of type valStruct. This is because const class objects can only explicitly call const member functions, and the overloaded operator[] in line 6 has not b... |
71,692,411 | 71,692,547 | How to sort a vector<any>? | Is it possible to sort vector<any> by using std::sort or somehow else?
I was trying to do smth like this
vector<any> va{ 55ll, 'a', -1};
sort(va.begin(), va.end(), [](const any& lhs, const any& rhs) { return any_cast<decltype(lhs.type())>(lhs) > any_cast<decltype(lhs.type()>(rhs) });
|
Is it possible to sort vector by using std::sort or somehow else?
It is possible. You can do it the same way as sorting anything else: By defining a function to compare two std::any with strict total order.
any_cast<decltype(lhs.type())>(lhs)
This won't work. std::any::type returns std::type_info, and unless you s... |
71,693,165 | 71,694,292 | C++ Fastest numerical string to long parsing | Here is what I came up with.
len is guaranteed to have meaningful value (positive and true size of the char array)
s is long unsigned number as a string without null-termination (received from 3rd party lib) typically 11-12 symbols e.g. "123456789000"
running on x86 linux
I am not C++ dev, could you help make it fast... | You might want to have a look at loop unrolling.
When the body of a loop is short enough, checking the loop condition every iteration might be relatively expensive.
A specific and interesting way of implementing loop unrolling is called Duff's device: https://en.wikipedia.org/wiki/Duff%27s_device
Here's the version for... |
71,693,329 | 71,693,391 | Is returning a pointer to a local variable always undefined behavior | I have read that we should not return a pointer or a reference to a local variable. So in the below given example, i understand that when i wrote: return f; inside function foo, i am returning a pointer to a local variable. And using that pointer outside the function, will lead to undefined behavior.
#include <iostrea... | Returning a pointer to a non-static function local variables will cause the pointer you get at the call site to be a dangling pointer and using it will have undefined behavior.
Here, this is not the case. A string literal has static storage duration, meaning it will live until the end of the program. This means it is... |
71,693,532 | 71,694,961 | Assembly: Why there is an empty memory on stack? | I use online complier wrote a simple c++ code :
int main()
{
int a = 4;
int&& b = 2;
}
and the main function part of assembly code complied by gcc 11.20 shown below
main:
push rbp
mov rbp, rsp
mov DWORD PTR [rbp-4], 4
mov eax, 2
mov DWORD PTR [rbp-20], eax
lea rax, [rbp-20]
mov QWOR... | Let me address the second question first.
Note that there are actually three objects defined in this function: the int variable a, the reference b (implemented as a pointer), and the unnamed temporary int with a value of 2 that b points to. In unoptimized compilation, each of these objects needs to be stored at some u... |
71,693,714 | 71,693,879 | In a C++ function template, why can't I use a lambda to specify the array size of a parameter? | I stumbled on the following while trying to implement some SFINAE trickery (what I was actually trying to achieve is irrelevant; I wan't to understand this behavior):
I define a constexpr function that takes a reference to an array of size 1, but I specify the array size through a lambda call:
constexpr bool f(const c... |
Why am I getting this error?
/usr/lib/llvm-11/bin/clang++ -stdlib=libstdc++ -std=c++17 myprog.cc
Using lambdas in function signature isn't allowed in C++17:
[expr.prim.lambda]
A lambda-expression is a prvalue whose result object is called the closure object. A lambda-expression shall not appear in an unevaluated op... |
71,693,878 | 71,693,991 | My rand() isn't really working in C++ specifically in Visual Studio 2019. I do have had "include <time.h> and <stdlib.h> | My rand() gives out the same number (GPA) for every student.
srand(time(NULL));
int gpa = 0 + (rand() % (10 - 0 + 1));
for (int i = 0; i < number; i++) {
cout << "Enter the student #" << i + 1 << "'s name: ";
getline(cin, pStudents[i]); cout << endl;
}
for (int i = 0; i < number; i++) {... | You only compute it once.
Here is how to fix it on your code:
srand(time(NULL));
for (int i = 0; i < number; i++) {
cout << "Enter the student #" << i + 1 << "'s name: ";
getline(cin, pStudents[i]); cout << endl;
}
for (int i = 0; i < number; i++) {
int gpa = 0 + (rand() % (10 - 0 + 1));
cout << "Studen... |
71,694,096 | 71,694,194 | What is the difference between class and struct in the "Type Erasure" code by using std::make_shared in C++? | I am trying to understand the behavior of "Type Erasure" by using std::make_shared. The basic idea is to use a class Object to wrap some different classes, such as class Foo and class Bar.
I write the following code, and it does work.
// TypeErasure.cpp
#include <iostream>
#include <memory>
#include <string>
#include ... | The only real difference between a class and a struct in C++ is that, for a struct, the default member access and inheritance is public, whereas, for a class, the default is private.
So, to make your code work for the class Derived template, just make its inheritance of Base public:
template< typename T >
class Derived... |
71,694,352 | 72,045,831 | Why is C++ getline() non-blocking when program is called from python subprocess? | I have a C++ program that waits for some text input with getline(), and it works well from the command line.
However, I would like to call it from Python - send some text, get the output, and have it wait for more input.
I tried with subprocess, but it seems that getline() in this case doesn't wait for input but gets a... | I created a class and added the start of the subprocess to the __init__ method. The methods of the class are used to interact with the C++ program. At this point however I was still having the same issue.
I solved it by adding a __del__ method that terminates the subprocess.
|
71,694,365 | 71,694,691 | std::queue and std::deque cleanup | Suppose we have a situation where we need FIFO data structure. For example, consume some events in the order they came in.
Additionally, we need to clear the entire queue from time to time.
std::queue seems like the perfect fit for doing that, but unfortunately it lacks a function for clearing the container.
So at this... |
we got back what we asked for, but we've got too much: we also got push front and pop back
You got exactly what you asked for, a dequeue is a data structure that allows efficient inserts and deletes at either end point. It might not be the data structure for you, but that's your fault for choosing it.
we will have t... |
71,694,462 | 71,694,603 | Can I define begin and end on an input iterator? | Lets say I have an input iterator type MyInputIter (which I use to traverse a tree-like structure) that satisfies the std::input_iterator concept.
Are there any reasons why I shouldn't define begin() and end() on the iterator itself?
struct MyInputIter
{
// iterator stuff omitted
auto begin() const { return *t... |
Are there any reasons why I shouldn't define begin() and end() on the iterator itself?
Potential issues to consider:
Implementing those functions for the iterator may be expensive. Either because of need to traverse the structure to find them, or because of extra state stored in the iterator.
It may be confusing sin... |
71,694,522 | 71,697,647 | How to solve "std::basic_ofstream<char, std::char_traits<char> >::open(std::string&)" | I get an error about std::basic_ofstream<char, std::char_traits<char> >::open(std::string&) when compiling this code:
FileEXt = ".conf";
const char* FileEX = FileEXt.c_str();
const char* File = Uname + FileEX;
string File = Uname + FileEXt;
ofstream outFile;
outFile.open(File);
Full code:
LPCSTR lpPathName = ".\\DB... | You are passing a std::string to ofstream::open(). Prior to C++11, open() did not accept a std::string as input, only a const char* pointer, eg:
outFile.open(File.c_str());
|
71,694,553 | 71,694,591 | How to solve "error C2078: too many initializers" when moving the same members from the parent class to its child? | I am facing a relatively tricky situation here that seemed quite easy at first sight. After moving those three members from the parent class Parent to its child class Child it seems that I'm no longer able to take advantage of the default constructor.
Why? And is there a way out here without having to specifically impl... | You need empty braces for the base subobject in aggregate initialization. (Default constructor is irrelevant in this case, both Parent and Child are aggregate and aggregate initialization gets performed.)
However, if the object has a sub-aggregate without any members (an empty struct, or a struct holding only static m... |
71,694,567 | 71,694,615 | push_back of an integer doesn't work on my vector of strings | I am trying to push back 3 vectors in parallel, and when I get to push_back() into the string vector, I get this error:
no instance of overloaded function "std::vector<_Ty, _Alloc>::push_back [with _Ty=std::string, _Alloc=std::allocator<std::string>]" matches the argument listC/C++(304)
ask3.cpp(38, 8): argument types ... | movies is a vector of string, so you cannot push int directly.
If you are using C++11 or later, you can use std::to_string to convert integers to strings.
Another way to convert integers to strings is using std::stringstream like this:
std::stringstream ss;
ss << moviecount;
movies.push_back(ss.str());
|
71,695,153 | 71,696,329 | Enable Perfect Forward Secrecy In Indy 10? | In How to enable Perfect Forward Secrecy In Indy 10?, the question is answered for Delphi. As I am trying to achieve the same in C++, I get stuck at the SSL_CTX_set_ecdh_auto() method. It is present in the source of Indy, and thus (I assume) in the installed version (I am running C++Builder 11), but there is no referen... |
[SSL_CTX_set_ecdh_auto()] is present in the source of Indy, and thus (I assume) in the installed version (I am running C++Builder 11), but there is no reference in the C++ header file IdSSLOpenSSLHeaders.hpp.
That is because all of the OpenSSL functions used in the IdSSLOpenSSLHeaders.pas unit are marked as {$EXTERNA... |
71,695,335 | 71,695,493 | What is the variadic function template overloading precedence rule? | I'm using variadic function templates in the common recursive format and I need to change the behaviour of the function whenever I'm handling a vector.
If the functions templates were not variadic, overloading works well, but with variadic function templates, the overloading resolution seems to change when unpacking th... | You need to declare template<typename T> void complexfun(std::vector<T>) before the function that is supposed to be using it.
Just swap the order of those function templates so you get:
template<typename T> // this function template
void complexfun(std::vector<T>) {
std::cout << "2 end" << s... |
71,696,301 | 71,697,738 | Declare static array in class with size passed to constructor? | Is there any way, to declare static array in class with size that was passed to constructor? It is alright if the size has to be const and it makes it impossible to set it in runtime.
I tried doing something like this:
class class_name
{
public:
float* map;
class_name(int n, const int d)
{
... | Yes, this code
class_name(int n, const int d)
{
float arr[d];
map = arr;
}
is a bad idea, for 2 reasons
float arr[d]; creates a local variable in stack, so it ceases to exist at the end of the block. So map becomes a dangling pointer. If you needed dynamic size allocation, you should just ... |
71,696,714 | 71,705,396 | MQTT client waits indefinitely during publish of message | I try to implement an asynchronous MQTT client with the paho library, that receives messages on topic "request", formulates a string and puts the response out on topic "response". I use the callbacks to handle the incoming messages.
#include "mqtt/async_client.h"
#include "mqtt/topic.h"
const std::string SERVER_ADDR... | I'm going to make a guess here, because I don't really know how async works in C++.
The MQTT client has a single message handling thread, this deals with all the incoming and outgoing TCP packets as they arrive/depart on the socket. When a new MQTT message arrives it then calls the message handler callback (message_arr... |
71,696,964 | 71,697,336 | C++ Union Array differs in 32/64 bits | My code:
union FIELD {
int n;
char c;
const char *s;
FIELD(){}
FIELD(int v){ n = v; }
FIELD(char v){ c = v; }
FIELD(const char* v){ s = v; }
};
struct SF {
const char* s0;
char s1;
int s2;
const char* s3;
};
int main() {
printf("sizeof(long) = %ld\n", sizeof(long));
... | Apply alignas(FIELD) to every single member variable of SF.
Additionally you cannot rely on the size of long to tell 64 bit and 32 bit systems appart. Check the size of a pointer to do this. On some 64 bit systems long is 32 bit. This is the case for my system for example.
Furthermore %ld requires a long parameter, but... |
71,697,593 | 71,707,107 | Why the CPU usage is higher when using OpenCV on C++ than on Python | I am using Ubuntu 20.04.4, and I compiled OpenCV as release mode. Whenever I read frames, it consumes quite a lot of my CPU. I tested this in other machines as well. However, using a very similar script on python, it uses much less CPU. I found this question that seems to have a similar problem as mine. Although I am u... | Thanks for @ChristophRackwitz. Apparently, it was the fourcc configuration that was causing the high CPU usage. Using a resolution of 1920x1080 will cramp FPS to 5 using the default YUYV encoding. This is likely why I got lower CPU usage using python.
If I set the fourcc on python to MJPG the CPU usage spikes.
|
71,699,002 | 71,699,431 | Variadic template returning a N-tuple based on an unknown number of arguments | I would like to have a variadic function template that takes pointers of a certain type T, fills those pointers, and for each of them generate an object as a result, the final result being a tuple of all these generated objects.
Given a function from a library (that uses a C api):
struct opaque {};
bool fill_pointer(o... | That's heavy pseudocode, I'll answer with heavy pseudocode:
template<typename ... Ts>
constexpr auto fill_and_gen_objects(Ts* ... os)
{
bool some_status = true; //whatever
return std::make_tuple(some_status, gen_object(os) ...);
}
Ok, actually it even compiles, see here
EDIT: downgraded to C++14 ... that's wh... |
71,699,081 | 71,700,665 | Can't assign a QString as a value for a LineEdit in Qt | I am working on a simple calculator app in Qt. I want to display an error message when the user tries to divide by zero. I have tried the code below but the output just stays as 0.
if(dblDisplayVal == 0.0){
QString error = "Can't divide by zero!";
ui->display->insert(error);
... | you should use setText function instead of insert.
this is an example:
QLineEdit *lineEdit = new QLineEdit(this);
lineEdit->setReadOnly(true);
ui->gridLayout->addWidget(lineEdit, 0, 0, 1, 1);
QString error = "Can't divide by zero!";
lineEdit->setText("Can't divide by zero!");
and it is the output:
|
71,699,562 | 71,699,676 | How to convert a string into a hexadecimal and store that hexadecimal value into a string in c++ | I want to store the hex values into a string, but I don't know to do that when my string is not giving me the hex values when it is printed out. I'm pretty sure it has something to do with hex, but I don't know how to get those int values that print out the correct hex values to be stored into a string without it being... | I see 2 different ways:
The first one uses a char array and writes to it with sprintf with %X.
The second way uses a stringstream and streams the int values into it with the hex specifier. You can get the string with the .str() method of stringstream.
#include <iostream>
#include <string>
#include <sstream>
#include <i... |
71,699,687 | 71,699,791 | C++ Code keeps crashing after a validation | I have written a piece of code to validate a keyword, it validates and makes sure that the word is 5 letters long and it is all letters with no numbers in it. However, when I run it, the code seems to stop working at all and doesn't prompt me for the next question, I've tested it without this code and this part of the ... | Before the for loop you need to check that key.length() is equal to keyLength. Otherwise the loop can invoke undefined behavior when the user enters a string with the length less than keyLength.
Also the function isalpha does not necessary returns 1. It can return any positive value.
Change your code something like the... |
71,699,793 | 71,700,155 | nested 'while' loop not looping back to outer 'for' loop after finishing (c++) | I'm needing to find how much tax $ any given number of taxpayers have to pay over any number of years. At the beginning of the program, # of taxpayers is entered, and # of years is entered. The while loop executes fine, and does what it's supposed to do the first time; however, it never loops back to the 'for' loop & a... |
it never loops back to the 'for' loop & asks for the next taxpayer's income
That is because after the while loop is finished the 1st time through, year has caught up to years, and so on subsequent iterations of the for loop, year <= years is always false.
You need to reset year back to its starting value on each iter... |
71,699,898 | 71,699,994 | c++: passing arrays by reference | I am trying to define a function prototype which takes an array of char of different lengths. I understand that I must pass the array by reference to avoid the array decaying to a pointer to its first element. So I've been working on this simple example to get my understanding correct.
#include <stdio.h> // size_t
... | Your function is declared correctly, but you are not passing the array to it correctly.
func(*str); first decays the array to a pointer to the 1st element, and then deferences that pointer, thus passing just the 1st character to func(). But there is no func(char) function defined, so this is an error.
func(&str); take... |
71,699,928 | 71,700,136 | inline static constexpr vs global inline constexpr | Suppose that I have a few inline constexpr variables (named as default_y and default_x) in a header file and I decided to move them to a class that they are completely related to and mark them static (cause it seems better in terms of design).
namespace Foo
{
inline constexpr std::streamsize default_size { 160 }; // n... | Placing static inline constexpr variables should not impact efficiency in any way. Due to constexpr they're const-initialized at compile time if it's possible. inline keyword here is helping you to initialize static variable inside the body of a class. You might find this material on the inline keyword interesting: htt... |
71,700,710 | 71,700,782 | How to write wrappers for classes in c++ that overrides some member and inherits other members | I want to implement a custom vector class myVector<dataT> which is identical to std::vector expect that its index starts from an offset which is given as parameter.
Example usage below:
myVector<int> vec(3,0,1); // length=3, initial_value=0, offset=1
assert(vec.size()==3);
vec[1]=1, vec[2]=2, vec[3]=3;
assert(vec[1]==1... | Method 4: make offset the first parameter to the constructor, use variadic parameters for the rest, and perfect-forward them.
template<typename ...Args>
myVector(int offset, Args && ...args) : std::vector{std::forward<Args>(args)...}
{
}
This solves the immediate problem of a single implementation for overriding all o... |
71,702,086 | 71,703,353 | Why the size of class showing 12 and 16 byte? | I have five classes here, class A B C I can explain the size of them.
class D I expect the result is 12 bytes, but the output is 16 bytes, I found the reason is that after adding the virtual function, the alignment will become 8 bytes,
So I created the Test class again, according to the above reasoning, my expected res... |
class D I expect the result is 12 bytes, but the output is 16 bytes
Your expectation is misguided.
I found the reason is that after adding the virtual function, the alignment will become 8 bytes,
That's the reason. 12 is not aligned to 8 bytes. 16 is.
So I created the Test class again, according to the above reaso... |
71,702,201 | 71,702,321 | Different instruction address shown in ltrace and objdump | I use ltrace and objdump to analyse the simple code below. But I find there is a difference on instruction address shown between ltrace and objdump.
#include <iostream>
int main() {
std::cout << "Hello";
return 0;
}
As the following info, you can see that the address of [call std::basic_ostream] is [0x400789] ... | Those are return addresses (instruction after the call in the parent, the address which call pushes on the stack).
ltrace can't know how long the instruction was that called a function, e.g. call reg with a function pointer is only 2 bytes vs. 5 for call rel32 vs. 6 for call [RIP + rel32] (memory-indirect call which GC... |
71,703,032 | 71,703,198 | Regex pattern issue remove specific digits | I'm trying to use a regex to extract a time string in this format only "01 Apr 2022". But I'm having trouble getting these digits out "07:28:00".
std::string test = "Fri, 01 Apr 2022 07:28:00 GMT";
std::string get_date(std::string str) {
static std::vector<std::regex> patterns = {
std::regex{"Fri,(.+)([0-9... | Here is a regex which will do the job: std::regex reg{R"(\d{2} \w+ \d{4})"};. And in your code you use m[0], not m[1].
But if your format is stable (and it sure looks like one) you don't need regex at all. Just do something like this: str.substr(5, 12) or std::string(str.begin() + 5, str.begin() + 16).
|
71,703,047 | 71,704,227 | invalit type 'int[int]' for array subscript | I`m trying convert QBytearray to QVector<QVector3D>.
extern "C" {
typedef struct {
double **vertexes;
int top_rows_vertexes;
int top_column_vertexes;
double **edges;
int top_rows_edges;
int top_column_edges;
}MATRIX;
int start_processing(const char * file_na... | int top_rows_vertexes;
That is a plain integer
A.top_rows_vertexes[0][0]
Here you are trying to index into an integer, which obviously will not work.
You probably want to index into vertexes like for the other cases:
coords.append(QVector3D(A.vertexes[0][0], A.vertexes[0][1], A.vertexes[0][2]));
But that is rath... |
71,703,459 | 71,703,524 | Runtime error in following leetcode problem | Problem link - https://leetcode.com/problems/maximum-average-subarray-i/
class Solution
{
public:
double findMaxAverage(vector<int>& nums, int k)
{
deque<pair<int,int>> d; //deque since its a sliding window problem
vector<double> ans; //to return answer
double avg;
double sum=0;
int n=nums.size();
... | The error is here
return *max_element(ans.begin(), ans.end());
If ans is empty, you dereference ans.end().
|
71,703,838 | 71,703,983 | Cannot find a key of a std::map with customized compare function | #include <cstdio>
#include <iostream>
#include <vector>
#include <map>
using namespace std;
struct mycmp {
bool operator()(const int &a, const int &b) const {
return abs(a) <= abs(b);
}
};
int main(){
map<int, int, mycmp> M1;
map<int, int> M2;
for(int i = 0; i < 5; i++) {
M1[i]++;
... | Given two elements a and b the comparator is used to decide if a should come before b. If comp(a,b) == true then a comes before b.
The same element cannot be placed before itself. Though, your comparator requires that, because mycomp(a,a) == true.
More specifically the comparator must impose a strict weak ordering. The... |
71,703,881 | 71,710,551 | iOS Keychain in C++, how to call SecItemAdd? | I'm trying to call iOS Keychain framework from C++, following various documentation pages and StackOverflow questions I arrived at the following:
// library is multiplaform so for now using macros for platform imports
#ifdef ANDROID
// Android specific imports
#else
#include <CoreFoundation/CoreFoundation.h>
#include <... | I figured it out, as it turns out, on macOS you can put CFStrings directly in the query dictionary, but on iOS you need to store binary data. Something like this:
string value = "testvalueblahblah";
std::vector<uint8_t> vec(value.begin(), value.end());
...
values[3] = CFDataCreate(kCFAllocatorDefault, &vec[0], vec.si... |
71,704,144 | 71,749,693 | Xcode, CMake unable to link C++ library with ObjC++ library | I have created a minimalistic C++ library that I want to use in my Xcode project. It has this directory structure -
library/
- CMakeLists.txt
- build/ // build files will reside here
- iOS.cmake // toolchain file
- core/
- CMakeLists.txt
- squareroot.h
- squareroot.cpp
... | Alright, I finally got what was the problem.
The libraries I was generating, were static libraries.
Static libraries cannot resolve their dependencies on their own (i.e., here, library in platform/ cannot resolve its dependency of core/) unless I explicitly add both of them to Xcode.
It started working after I added b... |
71,704,403 | 71,704,516 | Returning a boolean literal from function as reference | I have encountered this code during trying to find a bug:
int x = 10; // for example
const bool& foo() {
return x == 10;
}
int bar() {
bool y = foo(); // error here
}
This code block causes a crash when compiled with gcc11.2, while it works correctly and sets y as true in Visual Studio 2019. Both compilers g... | This is undefined behaviour as you are trying to return a reference on a value whose scope is destroyed once you exit the function.
|
71,704,975 | 71,705,200 | how can i convert a class which uses template to a normal class which uses Double | I thought I was doing good using class templates. But as soon as I started going backwards I had some difficulties. My task is to remove the tempalte realtype class and replace it with a normal double.
I really have no idea how to get started.
My idea was to simply remove this line
and I thought everything will work fi... | You haven't used the template type anywhere, but you have used a specialisation of that template (and also K_Circle_Basis?). You need to remove all the <Double> too.
class K_Arc_Basis
{
public:
DECLARE_K_STANDARD (Arc_Basis) // what does this expand to??
private:
typedef K_Arc_Basis ThisType;
typedef K_... |
71,705,383 | 71,705,454 | Why smart pointer type member variable can't be initialized at the declaring place in a class? | When I want to add a member variable with smart pointer type to a class, I found that it can't be initialized at the declaring place:
class Foo {
public:
std::shared_ptr<int> intSharedPtr = new int; // not ok
Foo() {}
};
But I can do this:
class Foo {
public:
std::shared_ptr<int> intSharedPtr; // ok
int* i... | std::shared_ptr can't be copy-initialized from raw pointer, the conversion constructor is marked as explicit.
You can use direct-initialization:
class Foo {
public:
std::shared_ptr<int> intSharedPtr {new int};
Foo() {}
};
Or initialize from an std::shared_ptr:
class Foo {
public:
std::shared_ptr<int> intShared... |
71,706,321 | 71,706,987 | Definition of static data member without repeating its type | When I have a class with a static const or constexpr data member, defining that variable reqires me to repeat stuff:
/// my_class.hpp
class my_class { constexpr static int x = 1; };
/// my_class.cpp
#include "my_class.hpp"
// auto my_class::x; // error: declaration of 'auto my_class::x' has no initializer
// decltype(... | Starting from C++17 you don't need to separately define static constexpr variables.
Just class my_class { constexpr static int x = 1; }; is enough, without a .cpp file.
|
71,706,827 | 71,706,919 | What's the use of <ratio> when we have contexpr values? | The <ratio> header lets you uses template meta-programming to work with and manipulate rational values.
However - it was introduced in C++11, when we already had constexpr. Why is it not good enough to have a fully-constexpr'ifed library type for rationals, i.e. basically:
template<typename I>
struct rational {
I ... |
Is there some concrete benefit to using std::ratio that C++11 constexpr functionality would not be well-suited enough for?
You can pass ratio as a template type argument, which is what std::chrono::duration does. To do that with a value-based ratio, you need C++20 or newer.
In C++20 and newer I don't see any benefits... |
71,706,909 | 71,723,497 | C++ thread still joinable after calling `join()` | I have a piece of code that simulates the provider/consumer scenario where each provider and consumer is a thread. I've paired each consumer with a provider and the consumer will wait until its provider has finished (by calling join() on the provider thread) before executing. The code is as follows:
std::vector<std::th... | The vector threads is growing as you push be threads into it, there's a good chance that some of the threads will start executing before you've finished adding all the threads. When the vectors capacity increases all iterators and references to it become invalid. This means that in threads[provider_idx] the returned re... |
71,707,275 | 71,707,513 | C++ `using namespace` directive makes global-scope operator disappear? | For reasons I do not understand, the following C++ code fails to compile on VS 2022 (dialect set to C++20):
#include <compare>
namespace N1
{}
namespace N1::N2
{
class A {};
A operator-(A&);
}
std::strong_ordering operator-(std::strong_ordering o);
namespace N1
{
using namespace N2; // (1) !!!
std:... | Your compiler is correct, and I would expect other compilers to agree.
For the behaviour of a using-directive, see C++20 [namespace.udir]/2:
A using-directive specifies that the names in the nominated namespace can be used in the scope in which the using-directive appears after the using-directive. During unqualified ... |
71,707,566 | 71,719,001 | OpenGL first person realistic keyboard movement | So I'm making this FPS game where I want to move forward, backward, left and right with keyboard input and look around with the camera like in a real FPS-game like Battlefield. The camera movement in combination with the keyboard input works great, but now my camera can fly around. And I just want to be able to stay on... | I want to thank everyone for helping me out! I understand better how everything works now. I want to move in the x-z plane and y must be zero (yes I chose the Y-axis as "up" or "the sky"), because I don't want the camera to move up or down. So when I go forward I only want to change the x and z parameter of the glm vec... |
71,707,916 | 71,708,175 | Sending a large text via Boost ASIO | I am trying to send a very large string to one of my clients. I am mostly following code in HTTP server example: https://www.boost.org/doc/libs/1_78_0/doc/html/boost_asio/examples/cpp11_examples.html
Write callbacks return with error code 14, that probably means EFAULT, "bad address" according to this link:
https://mar... | The segfault indicates likely Undefined Behaviour to me.
Of course there's to little code to tell, but one strong smell is from you using a reference to a non-member as the buffer:
boost::asio::buffer(write_buffer, write_buffer.size())
Besides that could simply be spelled boost::asio::buffer(writer_buffer), there's no... |
71,708,233 | 71,708,437 | How to avoid multiple definition of overridden method | I have a Base class and a Derived class (which derives from the Base class).
Both classes have a method called "getNumber ()".
In my main (), I want to run the method "getNumber()" of the Derived class.
My main instantiates an object of the Animal class.
In the Animal class is member variable : a pointer to the Base cl... | The problem is that you're including a source file named Derived.cc instead of a header file. This results in multiple definition error because this source file is then included (directly and indirectly) into other files and so there are "multiple definition" for the mentioned member function Derived::getNumber().
To s... |
71,708,334 | 71,709,941 | Frama-Clang: Invalid integer constant | While working with Frama-Clang, I ran into a problem.
The following code shows the problem broken down to the minimum:
const long long value = -1;
int main(){
return 0;
}
Running the Frama-C (Frama-Clang) analysis leads to the following output.
> frama-c invalid_integer.cpp
[kernel] Parsing invalid_integer.cpp (... | The error comes from a miscommunication between Frama-Clang and the Frama-C kernel itsef. Specifically, in the case of initializers of global integer variables, Frama-Clang neglects to convert a negative constant into the application of unary minus to a positive integer, which is what the kernel is expecting at this po... |
71,709,402 | 71,709,634 | Build error serializing struct to XML using Boost | I'm trying to serialize some structs to XML using Boost. I can't change the structs, so I'm trying to do it non invasively.
Following the simple "non intrusive version" example in the docs I managed to get flat text serialization to work. However when I try to extend it to XML by looking at the XML example I'm unable t... | The assert says it all:
// If your program fails to compile here, its most likely due to
// not specifying an nvp wrapper around the variable to
// be serialized.
BOOST_MPL_ASSERT((serialization::is_wrapper< T >));
So, let's add that
Live On Coliru
#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.