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 |
|---|---|---|---|---|
68,876,622 | 68,876,715 | Issues with pointers in c++ erase/remove algorithm | I have been trying to create a C++ program to find all the prime numbers under a certain integer, n, using the Sieve of Eratosthenes algorithm, which goes as follows:
Create a vector of integers ranging from 2 to n.
Start with the smallest element of the vector, 2, add it to a new vector of primes, and remove all mul... | std::remove_if() (potentially) re-orders the elements of the vector. Thus, ptr no longer necessarily points to the same value in further calls of the std::remove_if() predicate. By contrast, the value of p is not affected by std::remove_if().
You can see that they aren't the same with a little bit of ad-hoc debugging:
... |
68,876,843 | 68,876,892 | Why does C++ offer declarations in if statements? | I recently learned that an if statements can be used to declare variables in C++. I personally don't really understand the reason behind it.
Shouldn't if statements only check if the conditions are properly meant, and declaring a variable would result in an error?
That is, from what I believe, if statements can only c... |
Who would use int n = Test() as an if statement?
It limits the scope of the n, in the if statement, and whoever wants this to have will do so.
Now if you ask:
"Why can you declare and initialize and use a variable like that?"
It is valid because, the C++ standards says so. The if-statement, the syntax
attr(option... |
68,876,968 | 68,879,511 | Return value from function in "function pointer mode" | First, sorry for my English. I'm brazilian still trying to learn (english,and programming).
I'm trying to create a firmware application (STM32 uc), that access other firmware (my address was divided in BL + FWA + FWB), but I have one problem and can't find the reason.
FWB needs to access a function on FWA, to use less ... | Try:
uint (*fun_ptr)(void) = (uint(*)(void))0x8006001;
because all function pointers on this architecture must be odd.
The address is the real address of the first instruction (which is always even) plus one. The last bit indicates that the instruction uses the "thumb" instruction set, not the "arm" instruction set w... |
68,877,430 | 68,877,454 | C++ primer 5th edition. Union and members of class type | I have this text from C++ primer 5th edition. ch 19.6 Union:
class Token {
public:
Token(): tok(INT), ival{0} { }
Token(const Token &t): tok(t.tok) { copyUnion(t); }
Token &operator=(const Token&);
~Token() { if (tok == STR) sval.~string(); }
Token &operator=(const std::string&);
Token &operato... | You cannot assign something to an object that was never constructed. In C++, any object, any object all, needs to be constructed first, before anything happens to it. This is one of the fundamental rules of C++, without any exceptions or alternatives.
Attempting to use an object in any way, before it is constructed, re... |
68,877,498 | 68,877,653 | Destructor is not called for shared_ptr derived class | I want to implement the Mediator design pattern using shared_ptr for all the program.
Here is the Mediator interface:
class Mediator
{
public:
Mediator(){ print("Mediator()"); }
virtual void Notify(std::shared_ptr<BaseComponent> sender) const = 0;
};
Here is the ExampleMediator:
class ExampleMediat... |
What can be the cause for this issue?
Shared pointers destroy their owned resource when the pointer is the last owner pointing to the resource. When local variable eC is destroyed on return of main, there is still another owner mM.eC so the resource won't be destroyed. Similarly, when the local mM is destroyed, its r... |
68,877,737 | 68,877,758 | How to get shape (dimensions) of an Eigen matrix? | I'm coming over from Python & Numpy to C++ & Eigen.
In Python I can get the shape (dimensions) of a Numpy array/matrix using the .shape attribute, like so:
import numpy as np
m = np.array([ [ 1, 2, 3], [10, 20, 30] ])
print(m)
# [[ 1 2 3]
# [10 20 30]]
print(m.shape)
# (2, 3)
Now, when I use Eigen, there doesn't ... | You can retrieve the number of rows and columns from an Eigen matrix using the .rows() and .cols() methods, respectively.
Below is a function get_shape() that returns a string representation of the matrix shape; it contains information analogous to Numpy's .shape attribute.
The EigenBase type allows the function to acc... |
68,878,564 | 68,878,652 | missing `typename` in gcc 11.1.0 ranges header | I'm using clang-12.0.1 and libstdc++ from gcc-11.1.0. When including <ranges>, I get the following error:
[build] /usr/local/bin/../lib/gcc/x86_64-pc-linux-gnu/11.1.0/../../../../include/c++/11.1.0/ranges:3392:19: error: missing 'typename' prior to dependent type name 'iterator_traits<iterator_t<_Base>>::iterator_categ... | Clang has not implemented P0634R3 yet, as per the current posted status.
So to answer your question:
Is this a library bug?
Nope! Since the ranges library is only available in C++20, GCC's implementation is free to use syntax that is only available as per that version of the standard.
|
68,878,601 | 68,879,349 | how to read and write non-fixed-length structs to biniary file c++ | I have vector of structs:
typedef struct
{
uint64_t id = 0;
std::string name;
std::vector<uint64_t> data;
} entry;
That I want to write to file:
FILE *testFile = nullptr;
testFile = fopen("test.b", "wb");
However the normal method for read/write
fwrite(vector.data(), sizeof vector[0], vector.size(), testF... | When dealing with non-fixed size data it's important to keep track of the size somehow. You can simply specify the amount of fixed size elements or byte size of whole structure and calculate needed values when reading the struct. I'm in favour of the first one though it can sometimes make debugging a bit harder.
Here i... |
68,878,624 | 68,878,862 | How do I convert from arrays to STL vectors? | In my class we recently got introduced to STL vectors. My professor has given us a program that uses arrays, and we are to convert it to use std::vectors instead. He would like us to use iterators, so we're not allowed to use square brackets, the push_back member function, or the at member function. Here's one of the f... | Probably your professor wants you to write something like this:
void readData(std::vector<Highscore>& highScores)
{
for (auto it = highScores.begin(); it != highScores.end(); ++it) {
cout << "Enter the name for score #" << std::distance(highScores.begin(), it) << ": ";
cin.getline(it->name, MAX_NAME... |
68,878,706 | 68,878,712 | Passing in unspecialized class as a template parameter | I have a class that looks like this:
template <typename T> struct myclass;
template <typename T> struct myclass {
T value;
vector< unique_ptr<myclass<T>> > children;
};
This works great, but what I'd really like is to be able to specify vector as a template parameter:
template <typename T, typename Container> stru... | Sure, those are called template-templates. It's a mouthful of a name, but the syntax is roughly what you want it to be.
template <typename T, template <typename> typename Container>
struct MyClass {
T value;
Container< unique_ptr<MyClass<T, Container>> > children;
}
MyClass<int, std::vector> x;
|
68,878,805 | 68,879,051 | Is there a way to convert local_iterator to const_iterator or iterator? | How can we change unordered_multimap::local_iterator to unordered_multimap::iterator or unordered_multimap::const_iterator?
I need the change because we cannot erase elements using local_iterator, and erasing can only be done using iterator/const_iterator. If there is any other way of erasing using local_iterator, plea... | Kinda labor intensive, but you can iterate through the result of equal_range() until you find the correct iterator:
template<typename Cont>
typename Cont::iterator local_to_regular_iterator(Cont& c, typename Cont::local_iterator local_ite) {
auto range = c.equal_range(local_ite->first);
for(auto ite = range.first;... |
68,878,859 | 68,878,914 | Why I can't use append() to add a variable to a string? | I have a piece of code:
char temp = word[0];
word.erase(0, 1);
word.append(temp); //word.push_back(temp); is fine
I got an error:
error: no matching member function for call to 'append'
My question is why I can't use append() here? Thanks in advance!
| I am going to assume that word is a std::string.
If you look at the documentation for std::basic_string::append(), you'll see that it has a bunch of overloads, but all of them are for strings or repeated characters. There simply is not any overload that accepts a single character.
That's all there is to it.
push_back()... |
68,879,005 | 68,879,047 | Need help understanding the output | I have following code
#include <iostream>
using namespace std;
class Base {
private:
Base() {
cout<<"Base ctor has been called "<<endl;
};
public:
int a;
};
class Derived: public Base {
};
int main() {
Base* b1;
Derived d1();
cout<<d1;
return 0;
}
I am n... | Inside your main function, Derived d1(); is actually a declaration of a function called d1 that takes no arguments and returns a Derived. As for why this prints 1, std::ostream has no overload for a Derived (*)() (which d1 is implicitly converted to) so it converts it to the only suitable type, which is a bool. Try rep... |
68,879,171 | 68,879,190 | how can I test the result of "dynamic_cast" without causing segment fault | I'm writing a class using both polymorphism and template, it's like:
class base {
virtual ~base() = default;
};
template <typename T>
class derived : public base {
T a;
void save(T a_) { a = a_; }
};
so when I wanna use function derived::save(), basicly, I need dynamic_cast, but it cannot check if it's a goo... | You can check result of the dynamic cast:
void test() {
base* p = new derived<float>();
// good case
if (auto* d = dynamic_cast<derived<float>*>(p))
d->save(1); // called
if (auto* d = dynamic_cast<derived<int>*>(p))
d->save(1); // not called
delete p;
}
Making save virtual in the... |
68,880,018 | 68,881,923 | Distance to representative in Disjoint set union data structure | From cp-algorithms website:
Sometimes in specific applications of the DSU you need to maintain the distance between a vertex and the representative of its set (i.e. the path length in the tree from the current node to the root of the tree).
and the following code is given as implementation:
void make_set(int v) {
... | A disjoint set structure should typically use union by rank or size and path compression, like yours does, or it becomes very slow.
These operations change the path lengths in ways that have nothing to do with whatever your problem is, so it's hard to imagine that the remaining path length information is useful for any... |
68,880,061 | 68,880,165 | Is there a built-in function that quickly counts how many bits an int takes up? | I am trying to count how many bits an int takes up,e.g. count(10)=4,count(7)=3,count(127)=7 etc.
I have tried brute-forcing(<<ing a 1 until it's strictly bigger than the number) and using floor(log2(v))+1,but both are too slow for my needs.
I know that there exists a __builtin_popcnt function that quickly count how man... | You can use the GCC built-in function __builtin_clz, which gives the leading zero's:
#include <climits>
constexpr unsigned bit_space(unsigned n)
{
return (sizeof n * CHAR_BIT) - __builtin_clz(n);
}
|
68,880,190 | 68,880,924 | Use of recursion in strings? | I am a beginner in coding and I attended a placement assessment and I kept trying to arrive at a logic of this one question.Even after assessment I tried to refer and solve but then I couldn't.Some help would be appreciated...
I don't remember the constraints etc , but the question goes like.
They have given two string... | Perhaps someone can suggest improvements to this at some point, but here is what I could quickly put together.
First observation: The actual strings don't matter. All we need to store are the number of zeros and the number of ones, which we can do in a POD struct.
Second observation: This looks a lot like a variation o... |
68,880,805 | 68,881,014 | Can I get examples for static keyword in header file? | static.h
static int y = 20;
static int& f(){
static int x = 0;
return x;
}
general.h
int x = 10;
int& g(){
static int x = 0;
return x;
}
outer.h
#include"general.h"
#include"static.h"
void h(){
x = 20;//static
y = 20;//non static
f() = 20;//static
g() = 20;//non static
}
main.cpp
#i... | In the example you've shown there's only one .cpp file.
.h files don't actually count as "Translation Units", only .c and .cpp files are translation units.
The reason for that is that .h files are added to a program using #include.
#include literally copy-pastes the specified file into the current file, making it just ... |
68,880,942 | 68,881,196 | Why is the camera view matrix not changing the position of the point | glm::vec3 Position(0, 0, 500);
glm::vec3 Front(0, 0, 1);
glm::vec3 Up(0, 1, 0);
glm::vec3 vPosition = glm::vec3(Position.x, Position.y, Position.z);
glm::vec3 vFront = glm::vec3(Front.x, Front.y, Front.z);
glm::vec3 vUp = glm::vec3(Up.x, Up.y, Up.z);
glm::mat4 view1 = glm::lookAt(vPosition, vPosition + vFront, vUp);
... | To get a Cartesian coordinate, you need to divide the x, y, and z components by the w component. You have to print finalPositionMin.x/finalPositionMin.w.
Likely you confuse "window" coordinates and "world" coordinates. In your example, finalPositionMin is not in world space, it is in clip space. To get a world space co... |
68,881,411 | 68,881,798 | Aggregate initialization of a union in C++ with `{}` | In the following program the union U has two fields a and b, each with distinct default value. If one creates a variable of type U using aggregate initialization {} what are the value and the active member of the union?
#include <iostream>
struct A { int x = 1; };
struct B { int x = 0; };
union U {
A a;
B b;
... | Clang is correct, GCC is wrong
As per [dcl.init.aggr]/1:
An aggregate is an array or a class ([class]) with
(1.1) no user-declared or inherited constructors ([class.ctor]),
(1.2) no private or protected direct non-static data members ([class.access]),
(1.3) no virtual functions ([class.virtual]), and
(1.4) no virtual... |
68,881,971 | 68,885,654 | Why does this linker warning and segment fault happen? | I recently upgraded some external library version from librdkafka 1.3.0 to librdkafka 1.6.1.
After building the external library, it was linked as a shared object.
Then the following warning occurred when my program was linked.
/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld:
Warning: type of symbol ... |
I wonder why this is happening
You have two separate object files: memoryUtil.cpp.o and tinycthread.o, defining the same symbol: mtx_lock. One of them defines it as a function, the other as a variable.
Normally this should result in "multiply defined" symbol error at link time, but you get a warning instead. I am not... |
68,882,039 | 68,882,167 | 2D grid travel (Dynamic Programming) - recursive solution working but not memoized one | Problem Statement - there's a 2D grid of dimensions m x n ,you are at the top left corner, find in how many ways you can reach the bottom right when you can only move down or right.
The code uses unordered map where the keys are strings like so "2,3" , "1,2" (the nodes in the tree) and their values are integers (no.of ... | You need to add a breaker and initialization condition in function gridTravelerMemo
Update:
Another problem is, you are initialization unordered map every time in the
gridTravelerMemo function so you need to remove this also from the function and initialize it as a global.
Code:
#include<bits/stdc++.h>
unsigned gridTr... |
68,882,215 | 68,882,351 | Get value from std::tuple by std::type_identity | I am trying to write a function that will get a value out of a tuple by a special type that multiple types can be flag as by inheriting std::type_identity<special_type>.
I want to get the Things::GetThing() to be working below.
Using C++20 is fine.
Is this possible?
#include <type_traits>
#include <tuple>
template<typ... | Find the index first, then use std::get<index>(tuple) to get the right element.
One way to obtain the index is using a fold expression over && or ||. Note the use of an immediately-invoked lambda to turn index into a compile-time constant.
constexpr std::size_t index = []{
std::size_t index = 0;
((std::is_base_... |
68,882,311 | 68,882,444 | why n*(n+1)/2 % 2 is equivalent to bitwise operation (n+1) & 2 in if condition? | update again:sorry to put a wrong link which requires to login...you can see the code now
update:sorry to mislead...already edited the title
there is a problem :
divide the sequence 1 ... n into 2 sequences which have the same sum, such as... you can divide [1 2 3 4 5 6 7] into [1 6 7] and [2 3 4 5], but not all sequ... | n*(n+1)/2 % 2 == 0 effectively tests whether n or n+1 is divisible by 4; whether it can be divided by 2 twice. Indeed, there are two possibilities; if n is even, then n+1 is odd, so the only way to divide by 2 twice is to have n divisible by 4. Similarly, if n is odd, then n+1 is even and must be divisible by 4 for the... |
68,882,421 | 68,894,430 | Using a pack expansion with an index - is it UB? | The code below "seems" to work - however, I'm a little concerned that I'm in the realms of unspecified behaviour at the marked point. If I am, can someone please throw me a bone so that I can ensure that I'm not going to have it suddenly break when I change compiler?
The intent (in case it isn't clear) is that I want ... | auto convertedArgs = std::make_tuple(ConvertArg<Args>(args, count++)...);
the increments are indeterminately sequenced relative to each other. Compilers are free to do them in any order, and change the order because a butterfly flaps its wings. (Prior to c++17 the guarantees where worse than this)
In c++20 there is ... |
68,882,657 | 68,882,744 | unable to print string while concatenation using toupper() function | I am facing issues while using toupper() function :
Code :
#include <iostream>
#include <string>
using namespace std;
int main (){
string input {"ab"};
string output {""};
cout << output + toupper(input[0]);
return 0;
}
the error is :
no operator "+" matches these operands -- operand types are: std:... | toupper's return value is an int, and you can't add an std::string and an int due to no existing operator+(int). Your char temp implicitly converts the int return value to char during its initialization, and since std::string has an operator+(char) overload, this works. Though you can replicate the same behavior with a... |
68,882,767 | 68,882,808 | UE4 error compiling due to unknown function EditAnywhere | I've been working on an Unreal Engine 4 game using C++ and I've been working on a dash function, however I followed a YouTube tutorial and I noticed that in the video, they use the function "EditAnywhere" but when I tried to code that my self, my UE4 says that EditAnywhere is unknown function.
Do I need to meet some sp... | You can not have the EditAnywhere for functions!
The EditAnywhere is a property declaration meant only for the variables.
Properties are declared using standard C++ variable syntax, preceded by the UPROPERTY macro which defines property metadata and variable specifiers.
UPROPERTY([specifier, specifier, ...], [meta(key... |
68,882,799 | 68,885,092 | How can I get the data inside a beast::flat_buffer? | I'm connecting to a websocket using the boost/beast libraries and writing the data into a beast::flat_buffer. My issue is that I'm having trouble getting the data from buffer. I have a thread-safe channel object that I can to write to, but I'm not sure how to pull the most recently received message from the buffer.
bea... | The interface for flat_buffer is documented here: https://www.boost.org/doc/libs/1_77_0/libs/beast/doc/html/beast/ref/boost__beast__flat_buffer.html
As you can see it is a rich interface that lends itself to a number of different usage patterns, including reading and writing blocks in FIFO style.
Now, if you are using ... |
68,883,573 | 68,883,882 | Initialization in return statements of functions that return by-value | My question originates from delving into std::move in return statements, such as in the following example:
struct A
{
A() { std::cout << "Constructed " << this << std::endl; }
A(A&&) noexcept { std::cout << "Moved " << this << std::endl; }
};
A nrvo()
{
A local;
return local;
}
A no_nrvo()
{
A lo... | You have to be careful with cppreference.com when diving into such nitty-gritty, as it's not an authoritative source.
So which object exactly is copy-initialized as described at cppreference.com for return statements?
In this case, none. That's what copy elision is: The copy that would normally happen is skipped. The... |
68,884,565 | 68,884,716 | How do you express -1 nanosecond in a timespec structure? | The timespec structure is defined as:
struct timespec {
time_t tv_sec; /* seconds */
long tv_nsec; /* nanoseconds [0 .. 999999999] */
};
The two fields are signed numbers. I can easily define "now" as something such as:
timespec now{ 1'629'659'718, 564'223'121 };
I can also define a null timesp... | You can't actually use a negative time with any system/library call, so if you just want a notion of a negative time (eg, that you can add to an absolute time or an interval to get a positive time), you can use any representation you like -- having just the tv_sec field be (possibly) negative and having the tv_nsec alw... |
68,884,590 | 68,884,737 | declval<T> vs declval<T&> | I'm trying to understand the difference between declval<T>() and declval<T&>()? Is there an example where T& can be used while T cannot?
#include <type_traits>
#include <utility>
struct X {
X() = delete;
int func();
};
int main()
{
// works with both X as well as X& within declval
static_assert(std::is_same_v<d... | Apart from ref-qualified member functions (which are used rarely), a more common use-case for std::declval<T&>() is to create an lvalue reference (it creates an rvalue-reference otherwise).
#include <type_traits>
#include <utility>
struct X {};
int func(X&);
int main() {
static_assert(std::is_same_v<decltype(func(... |
68,884,636 | 68,884,675 | How to remove element from unordered_set without elements being freed | As the title says, I want to remove elements from an unordered_set without it's destructors being called. In my case, I'm storing a collection of MyObject pointers in an unordered set, however I also want to remove them from the unordered set without them being freed/cleaned up. When calling erase however, the elements... | You can extract the node that contains the element without destroying the element of the set.
I'm storing a collection of MyObject pointers
In this case, how about considering just making a copy of the pointer before erasing it from the set?
|
68,884,706 | 68,884,794 | Printing and replacing numbers and percentages in C++ | So I am new to coding in C++
and I want to make a loading number.
like, I want to print 1% then after some time delete it and replace it with 2% on the same place as the 1% was.
I know about the sleep command but I do not know how to replace the previous number% with a new number% I would like to be able to repeat it u... | This might help you:
#include <iostream>
#include <unistd.h>
int main() {
std::cout << 'a'; // so we have something to delete
for (int i = 0 ; i < 5 ; i++) {
std::cout << '\b' << i << std::flush;
sleep(1);
}
return 0;
}
You know how '\n' is newline? '\b' is backspace.
Edit for 100:
#inc... |
68,884,714 | 68,884,918 | C/C++ android 11 code crash at strstr api call | I got below strstr api call crash:
pid: 6640, tid: 6640, name: demoapp >>> /vendor/bin/demoapp <<<
uid: 0
signal 11 (SIGSEGV), code 2 (SEGV_ACCERR), fault addr 0x7b8a91c000
x0 b400007b8a91bf70 x1 0000000000000000 x2 000000000000002f x3 b400007b8a91c000
x4 0000000000000020 x5 0000000040100401 x6 000... | The most common causes for function strstr() to crash are:
if one of the provided char* is nullptr,
if one of the provided char* points to string that has no '\0' terminator.
if one of the provided char* was subject of a buffer overflow.
There are plenty of other possible causes. If this does not help, provide the ... |
68,884,950 | 68,885,041 | Flatten a nested type hierarchy into a linear sequence of types for std::function | Consider this (not working) code.
template<class A, class B>
struct Param {
typedef A A_t;
typedef B B_t;
};
template<class P>
struct FuncType
{
typedef std::function<void(typename P::A_t, typename P::B_t)> Func_t;
};
void foo(float a, float b,float c)
{
}
int main()
{
// this doesn't work, as 2nd paramet... | Something along these lines, perhaps:
template<class A, class B>
struct Param {
typedef A A_t;
typedef B B_t;
};
template <typename T>
struct FlattenParam {
using type = std::tuple<T>;
};
template <typename A, typename B>
struct FlattenParam<Param<A, B>> {
using type = decltype(std::tuple_cat(
std... |
68,885,466 | 69,692,461 | OpenSSL SSL_connect SYSCALL error with Netty tcnative | I am connecting to a Java (netty-tcnative) server using Berkeley sockets and OpenSSL 1.1.1k on Windows using C++. Sometimes during the connection phase, I'll receive a SSL_ERROR_SYSCALL from SSL_connect. If I attempt to get more information from this SYSCALL error (per OpenSSL documentation) using ERR_get_error I get a... | After a lot of debugging I finally have an answer to this question.
Is there a flag or boolean I can set to enable debug logging on OpenSSL side or a way for me to verify my suspicions that OpenSSL is attempting to resume the TLS session?
If you are using BoringSSL and not the Netty-tcnative OpenSSL dynamic library, ... |
68,885,502 | 68,885,520 | Unable to create 2D vector in CPP std::vector<std::vector<uint8_t>> by just giving the size | I was creating empty 2D vector in a header file by just providing size but unable to create it.
class Grid
{
public:
int rows = 5/0.05;
int cols = 6/0.05;
std::vector<std::vector<uint8_t>> grid(rows, std::vector<uint8_t>(cols, 0));
};
I am getting below error
... | You have used two different integer types uint8_t and int.
You should change it as
std::vector<std::vector<uint8_t>> grid(rows, std::vector<uint8_t>(cols, 0));
As A Class Member
To initialize the vector as a class member that is also dependent on other class members you can use the class constructor. The following cod... |
68,885,697 | 70,505,444 | Template class specialization with different concepts gives redefinition error | I'm writing some code using std::hash and a Hashable concept. However I can't define specializations with two different concepts even if I don't have an ambiguous instance of them.
#include <ranges>
#include <concepts>
#include <functional>
namespace ranges = std::ranges;
template <typename T>
concept Hashable = requ... | This is known GCC bug [concepts] redefinition error when using constrained structure template inside namespace: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=92944
A simpler example is as follows:
#include <concepts>
#include <functional>
template <std::convertible_to<int> T>
struct std::hash<T> {};
template <std::con... |
68,885,793 | 68,885,817 | Why is the modification of string literal allowed via char*, despite the fact that it points to a read-only memory? | Well I have been doing a lot of programming recently, but this simple question never crossed my mind.
Suppose I have the following snippet of code.
#include <iostream>
int main()
{
char* p="hello";
p[0]='y';
std::cout<<p;
}
I am aware that by the C++ standard(section 2.14.5 paragraph 11) it is stated that t... |
As far as I am aware, string literals are allocated in read-only memory.
Then I would suggest the possibility that you are not totally aware :-)
The standard doesn't actually mandate that string literals are read-only, just that attempting to modify them is undefined behaviour (UB).
One of the possible outcomes of UB... |
68,885,851 | 68,886,089 | Is there a way to initialize a class by function parameter in c++? | I want to have a parent class which it stores all child class and the child class can have a derived classes which each classes is unique.
that's why I want to initialize class in a function but a class is a parameter. I don't know what to describe but let's look at the code.
I'm beginner btw.
class Child {
string ... | As I understand, there is really two questions here:
How to get addChild("Harry") to find the right child class and register it.
How to have certain functions which only work for particular child classes.
Number one is a fairly standard factory/registrar class, which might be good to read up on (here, but you can fin... |
68,886,164 | 68,886,260 | Why can the type constraint `std::convertible_to` be used with only one template argument? | I've scrolled and searched through the standard and cppreference for hours to no avail, would really appreciate if someone could explain this occurance for me:
I am looking at the standard concept std::convertibe_to. Here's a simple example that I do understand
class A {};
class B : public A {};
std::convertible_to<A,... | void foo( constraint<P0, P1, P2> auto x );
this translates roughly to
template<contraint<P0, P1, P2> X>
void foo( X x );
which translates roughly to
template<class X> requires constraint<X, P0, P1, P2>
void foo( X x );
notice how the type X is prepended to the template arguments of the constraint.
So in your case,
t... |
68,886,217 | 68,886,238 | wprintf behaviour with MingW64 | I've been scratching my head on a very odd issue.
See sample code below:
test_c.c
#include <wchar.h>
#include <stringapiset.h>
int main (int argc, char **argv)
{
const char mystr[] = "The brown fox jumped over the lazy dog";
wchar_t wideName[MAX_PATH];
int len = MultiByteToWideChar(CP_UTF8, 0, mystr, -... |
Am I doing something wrong ? Is there a way to fix this ?
Yes. %s is for printing char*. To print wchar_t*, use %ls.
|
68,886,293 | 68,887,292 | How to use multiple shader states? | For example, if I want to use ID3D11RasterizerState with CullMode set to D3D11_CULL_BACK, and then I want to change it to D3D11_CULL_FRONT during runtime, what is the best approach? I was creating one state for each option and setting the right one during runtime, but this is very troublesome, as I need to set a lot of... | Generally you create a rasterizer state for each combination of states you want to use. Setting the active state is a pretty cheap operation--it's creating the state object that's expensive.
Note in DirectX 12 you have to put all states into each Pipeline State Object so that means every possible permutation of states... |
68,886,297 | 68,896,942 | Vector Subscript Out of Range C++ SFML | I'm trying to make a program that randomly generates a user-defined number of circles on the screen (using SFML), but when I choose a number of circles above 6, I get the Vector Subscript Out of Range error. Any number = to or below 6 works as expected.
I've tried looking up the error message, but none of the answers i... | Because you initiate person(size) with size = 5 and the loop is going up to numPeople = 10. You probably wanted to write:
std::vector<sf::CircleShape> person(numPeople);
|
68,886,352 | 68,886,618 | return an array from subscripting operator overload | I'm getting started with c++ and I have this method where I overload the subscript operator "[ ]" but I need to return an array from that method, In the method, I'm trying to return a sub array from a bigger array but I can't seem to return a whole array since I can only return a single element from an array, how can I... |
I need to return an array from that method
int& PagedArray::operator [] (int position)
The return type that you've given for your function does not match what you need to return. This function returns a reference to an integer; not an array.
A problem with what you need is that you cannot return an array in C++; tha... |
68,886,601 | 68,892,941 | (C/C++) Inline Assembly "add dword ptr [address]" increments the address instead of it's value | I'm trying to increment the value at an address stored by a DWORD iNumAddr using Inline Assembly and I've noticed that it increments the address instead of the value it contains. Eg.
->iNumAddr = 57D03390
->addstuff() runs..
->iNumAddr = 57D033C2
The address is correct, I've tested it.
void addstuff()
{
_asm {
... | If you declare a variable DWORD iNumAddr in a high-level language such as C++, then the symbol iNumAddr in assembly-language code takes the value of the address of the high-level language variable iNumAddr. (This address is usually assigned by the linker.)
So the instruction add dword ptr [iNumAddr], 50 will increment ... |
68,886,747 | 68,887,927 | Converting text file into bin/hex/dec | Ive beenn attempting to make a program that reads from a file, and if it reads a B it means the next line is binary and it will translate that next line from binary, into hex and dec and print out binary, then move on to the next line. I am having trouble with #1, going to the next line and #2 having my functions trans... | There are some problems.
YOu make your life overly complicated. You can use existing conversion functions.
But then, you also have some mistakes in the code. You always read a line and, in this line is already the letter. Then you read again and want to have the letter. But here you read already the next line. And so, ... |
68,886,809 | 68,886,859 | Overloading operator whose parameter is not class or enum | I want to overload operator like this:
fraction operator / (int a, int b) // error here
{
return fraction(a,b);
}
(Not inside fraction class).
But the compiler says:
[Error] 'fraction operator/(int, int)' must have an argument of class or enumerated type.
Can I get around this? (Just want when I write like 1/3 to con... |
I want to overload operator like this:
fraction operator / (int a, int b) // error here
You may not do what you want, as the compiler says.
Can I get around this?
Want something else. There's no way to change division of two int in C++.
You can just write fraction(1, 3). If you would like something shorter to writ... |
68,886,961 | 68,893,538 | How to use linked list ADT in a function? | I am trying to copy a queue from another queue but the function gives the following compile errors:
'class Node' has no member named 'isEmpty'
'class Node' has no member named 'enqueue'
'class Node' has no member named 'getFirst'
'class Node' has no member named 'dequeue'
'cannot convert 'operations*' to 'Node*' in ret... | The signature of your first function is not correct. It is supposed to take a queue and return a queue, but you have specified Node for both.
So change:
Node* copyQueue(Node* q1)
to:
operations* copyQueue(operations* q1)
Some other things to correct:
In main you have not declared q2. Also, it does not capture the re... |
68,887,054 | 68,887,497 | Is this recursive implementation of bubble sort inefficient, and how could it be improved if possible? | Yesterday I came across a recursive implementation of bubble sort, which looks elegant at first glance:
template <class T> void bubblesort_recursive(T data[], const int n){
if(n==1) return;
else{
bubblesort_recursive(data+1, n-1);
if(data[1]<data[0]) swap(data[1],data[0]);
bubblesort_rec... |
which leads to exponential time complexity.
True.
However, bubble sort usually leads to n^2 time complexity.
True.
how could it be improved?
If you are looking for a recursive implementation of bubble sort that has O(²) complexity, then we need to distinguish two processes:
One sweep of bubbling
Repeating this w... |
68,887,210 | 68,890,783 | How to make a contiguous linked list? | I have a custom data structure for a circular linked list. Its purpose is very niche, so I want to know if there is a way to make each node point to an address in a contiguous block of memory to achieve random access. The list won't be modified (inserted/deleted) at all after initial population, so a contiguous block i... |
How can I achieve this?
You could use a standard list container using a custom allocator.
However, I'm rearranging the pointers by O(n), whereas I believe I can rearrange the pointers by O(1) via pointer arithmetic if I use a contiguous memory space.
All lists can do rotations in constant time using the splice oper... |
68,887,384 | 68,892,391 | How to import matrix into armadillo using binary files? | I am trying to import a matrix generated in MATLAB into armadillo. For example, I have a matrix "A" which is 100x1 double. I used information from a previous question on stackoverflow to generate a binary file using MATLAB:
% Generate LocalX.bin
name = 'LocalX.bin';
[F,err] = fopen(name,'w');
if F<0,error(err);end
fwri... | If you know the dimensions (ROWS,COLS) beforehand you can add LocalX.reshape(ROWS,COLS) after you have loaded the matrix.
|
68,887,614 | 68,893,886 | Is reduction of `constexpr` object lifetime legal in C++? | For ordinary objects (even for const ones), it is permissible to end their lifetime by explicitly calling the destructor. Later, for example, the program can start another object lifetime in the same memory location using placement new.
But is it legal to call the destructor of a constexpr object? Can it result in some... |
[dcl.constexpr] A constexpr specifier used in an object declaration declares the object as const.
You can do with such an object whatever you can do with any other const object. constexpr, apart from implying constness of the declared object, doesn't seem to affect anything about the object itself. It only affects st... |
68,889,009 | 68,903,178 | No auto build of QT Cmake project after update to VS 2019 16.11.1 | I've just update a Visual Studio 2019 to version 16.11.1 and my project stop to auto build when I try to debug it. I must run building before debuging on my own. I've checked my settings but everything looks ok. Build when project is out of date i sellect to Always build.
Have you got this problem before and have got a... | Indeed, a bug was introduced in 16.11.1 (https://developercommunity.visualstudio.com/t/CMake-cache-generation-hangs-after-upg/1505033). Microsoft is aware of it and preparing a fix.
|
68,889,056 | 68,889,153 | How to find the true height of a QWidget inside a layout with Qt expanding policy? | My Qt program has a window, and inside the window, there is a QVBoxLayout layout. I added a QLabel to the layout with the Qt::Expanding size policy. here is the code.
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QWidget* window = new QWidget();
QVBoxLayout* main_layout = new QVBoxLayout(... | The problem is that QWidget::resize doesn't resize your widget immediately if the widget is hidden:
If the widget is visible when it is being resized, it receives a
resize event (resizeEvent()) immediately. If the widget is not
currently visible, it is guaranteed to receive an event before it is
shown.
So, when the w... |
68,889,432 | 68,893,871 | writing struct to .txt file | I'm trying to store my struct into txt file using boost but unable to do it. I'm using boost library.
example structure
struct Frame
{
uint32_t address{ 0 };
uint16_t marks{ 0 };
uint16_t age{ 0 };
char gender{ 'M' };
std::string userName;
};
for binary there is simple code
boost::archive::binary_o... | As others have commented you will have to provide serialization helpers that tell Boost how to member-wise serialize.
If you have only aggregates like this, you can automate the generation of this function to a degree with Boost PFR:
pfr::for_each_field(s, [&](auto&& f) { ar & f; });
Here's an example:
... |
68,889,666 | 68,889,813 | best way to concatenating and splitting uint32_t to/from uint64_t | How about this code
#include <cstdio>
#include <cinttypes>
#include <type_traits>
#include <cstddef>
#include <iostream>
int main()
{
uint64_t tsc = 0xdeaddeadc0dec0de;
uint32_t MSB = *((uint32_t*)&tsc+1);
uint32_t LSB = *((uint32_t*)&tsc);
std::printf("low %x high %x \n", LSB,MSB);
uint64_t MLSB... | If you think you have to deal with endianness in your code, you are doing it totally wrong.
uint64_t tsc = 0xdeaddeadc0dec0de;
uint32_t MSB = tsc >> 32;
uint32_t LSB = tsc;
uint64_t MLSB = LSB | (static_cast<uint64_t>(MSB)) << 32;
uint64_t LMSB = MSB | (static_cast<uint64_t>(LSB)) << 32;
This is all you need. Numbers ... |
68,889,979 | 68,890,333 | Extern "C" and C++ structure and typedef | I have started using C++ for win32. As we know C++ struct is same as class but default public member etc... Now I want is simple C struct that has no default constructor or copy or move operation or any other magic. Because I want to store it in file also perform memcpy, use as BYTE array etc... So I thought of definin... |
But struct still compile as cpp struct if in cpp file or as C struct if in C file
You can't compile some code as C using a C++ compiler. A C++ compiler compiles everything as C++ code.
Fortunately the C++ language guarantees that "standard-layout" classes are layout-compatible with C. So you have nothing to worry abo... |
68,890,693 | 68,890,862 | Why is GCC wrongly detecting shift count overflow? | I am trying to make a compile-time set of tags at most 8 chars out of constant string. For example, "abc" should become 0x6162630000000000, "" should become 0, etc.
For this, I thought I should use the fact that references to arrays do not decay to pointers and I can capture the N (size) of the const array with this:
t... |
Why is GCC wrongly detecting shift count overflow?
It isn't.
When N=1, the code
if ((N-1) < 8) {
result = result << (8 * (8 - (N-1)));
}
results in a 64-bit shift.
If you don't want that code compiled for N=1, make it explicit:
if (N > 1 && (N-1) < 8) {
result = result << (8 * (8 - (N-1))... |
68,891,696 | 68,891,767 | how to deduce return type from lambda? | here is the sample code
#include <iostream>
template<typename T>
T foo(T(*fp)())
{
return fp();
}
int main()
{
std::cout<<foo([]->int{ return 1; });
}
when I compiled the code above, compiler says it cannot deduce the template argument,
but I have specified the return type of lambda.
| foo takes function pointer while you're passing a lambda, but implicit conversion (from lambda to function pointer) won't be considered in template argument deduction for T, which makes the invocation failing.
Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the ... |
68,892,508 | 68,893,235 | unicode utf-16 surrogate pair print problem | In Visual Studio /C++ declared a wstring c and filled it with a surrogate pair ( Unicode 0001F01C = Mahong tile )
std::cout << std::hex << 16;
std::cout << "Hello World!\n";
std::wstring c = L"\U0001F01C";
wchar_t* ctest = &c[0];
std::cout << "Checking value: " << *ctest << ".." << en... | You just need to do the reverse operation that creates a UTF-16 surrogate pair.
U+10000 to U+10FFFF
0x010000 is subtracted from the code point, leaving a 20-bit number in the range 0..0x0FFFFF.
The top ten bits (a number in the range 0..0x03FF) are added to 0xD800 to give the first 16-bit code unit or high surrogate, w... |
68,892,550 | 68,893,086 | How to generate date::local_time from std::chrono_time_point | I'm using Howard Hinnant's time zone library.
https://howardhinnant.github.io/date/tz.html
My question: Is it possible to construct a date::local_time object from a std::chrono::time_point?
What I want to to:
// 'tp' exists and is some std::chrono::time_point object
auto locTime = date::local_time<std::chrono::millise... | This is a two part answer ...
Part 1
My question: Is it possible to construct a date::local_time object from a std::chrono::time_point?
I'm going to assume that std::chrono::time_point refers to std::chrono::system_clock::time_point (each clock has its own family of std::chrono::time_point).
Yes, it is possible. Bac... |
68,893,282 | 68,894,442 | C++ Builder, pass argument to onClick button event | I'm using C++Builder to create a GUI.
I dynamically create a button, this button has an OnClick event:
TButton* exportLongitudinalButton = new TButton(infoGroupBox);
exportLongitudinalButton->Parent = infoGroupBox;
exportLongitudinalButton->Caption = "Export DXF";
exportLongitudinalButton->OnClick = frmConcreteWidth ->... | What you are asking for is generally not possible, at least not the way you want.
The OnClick event has a very distinct signature that you cannot change. So you will simply have to store your x/y values somewhere else that onDXFExport() can access when needed.
There are many different ways to approach this.
For example... |
68,893,545 | 68,893,593 | How returning a string_view of a local literal works | Consider this snippet:
#include <iostream>
#include <string>
#include <string_view>
using namespace std::literals;
class A
{
public:
std::string to_string() const noexcept
{
return "hey"; // "hey"s
}
std::string_view to_stringview() const noexcept
{
return "hello"; // "he... |
but both g++ and clang say nothing, so this code seems legit and works.
You cannot deduce latter from the former. A lot of non-legit code produces no warnings.
That said, string literals have static storage duration, so there is no problem with their lifetime. to_stringview is legit indeed.
P.S. String literals are a... |
68,893,559 | 68,893,696 | std::is_same for a loop statement | I have two structures with methods returning iterators on begin and end of object collection they own. Methods have different names (this may seem like a bad app architecture, but this is only a simplified model):
struct A {
std::vector<int>::iterator a_begin() { return v.begin(); }
std::vector<int>::iterator a_end... | I'm taking your claim about naming and complexity at face value, so abstract and bridge.
namespace detail {
inline auto foo_begin(A& a) { return a.a_begin(); }
inline auto foo_end (A& a) { return a.a_end(); }
inline auto foo_begin(B& b) { return b.b_begin(); }
inline auto foo_end (B& b) { return b.b... |
68,893,688 | 68,893,763 | error: binding 'const ...' to reference of type '...&' discards qualifiers | I am trying to save an instance of my custom class to a vector, but I get the following error during compilation:
error: binding 'const anil::cursor_list' to reference of type 'anil::cursor_list&' discards qualifiers
{ ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }
Could you help me figure what I'm doing w... | push_back() makes a copy, but your copy-constructor expects a cursor_list& copied_cursor_list parameter.
The parameter should be const cursor_list& copied_cursor_list.
(See the documentation, the parameter for push_back() is const &).
Actually, the problem is similar with the copy-assign operator (should be cursor_list... |
68,894,305 | 68,895,898 | reason why this code is considered optimized? | I am working on optimization of some code and came across this, could someone tell me why this piece of code is more 'optimized'
for (i = 0; i < 1000; i+=2){
float var = numberOfEggs*arrayX[i] + arrayY[i];
arrayY[i+1] = var;
arrayY[i+2] = numberOfEggs*arrayX[i+1] + var;
}
than this version?
for(long i = 0... | The first example is performing two assignments per iteration. You can tell by the increment statement.
This is called loop unrolling. By performing two assignments per iteration, you are removing half of the branches.
Most processors don't like branch instructions. The processor needs to determine whether or not to... |
68,894,506 | 72,316,407 | Unreal Engine 4 blueprints how to disable ESC key? | I've been trying to figure out how to disable ESC or any other key in UE4 blueprints or C++, doesn't matter for me.
Do someone know how to disable ESC key in Blueprints or C++?
Thank you for answer
|
Check if it is bound to ESC in the input setting of the project setting on the blue print.
In the C++ project, search for Key=Esc with ctrl+shift+f. Clear the value of the setting directly, or unbind it to the c++ base of the actor file you want to control.
|
68,894,574 | 68,898,644 | Unable to modify an array inside of a class in C++ | I am new to C++. I just wrote this program in Visual Studio Code, but I am receiving two errors which I haven't found an explanation for.
This is the code:
#include <iostream>
using namespace std;
class net{
public: bool isConv = false;
public: int structure[2];
structure[0] = 1;
};
int main() {
n... | In a class, you define all the variables and functions, but what you're trying to do is that you try to make an operation within the class. You can make them only inside functions, so the best way to solve your problem would be to make the operation inside the constructor of the class. Constructor is a function, which ... |
68,894,846 | 68,894,951 | What is the difference between given two lines of dynamic memory allocation in C++ ? Do they both create 10 sized array? | int *arr = new int(10);
int *arr = new int[10];
It is the code of dynamic memory allocation in c++.
But I am not getting What is the difference between these two.
| For a simple example, let's talk about what happens on the stack.
int x(10)
This generally means assigning an value to an int named x.
int x[10]
This generally means creating an array named x of 10 elements.
So, when it come to dynamic memory, it's the same thing.
int* x=new int(10)
This creates a single integer on the... |
68,895,133 | 68,896,283 | Is the compiler required to inline functions in the base class that are both virtual and final? | In a CppCon talk by Nicolai Josuttis (see here starting at 34:10), one of his suggestions for the use of the specifiers virtual, override, and final, is to mark either all functions virtual (for a polymorphic class) or none of them (for a standard class).
His rational for doing this is that it allows you to write funct... |
Is the compiler required to inline functions...
No. There are no cases where the compiler would be required by the C++ language to expand a function call inline.
|
68,896,415 | 68,898,059 | how to read content in a .txt file that is limited by two words in C ++ | I am new with C++,
I have a file that contains the following lines:
~~ 13!-!43??
CaKnX5H83G
~~ 107!-!22??
~~ 140!-!274??
~~ 233!-!75??
begin
~~ 143!-!208??
143
~~ 246!-!138??
~~ 79!-!141??
vC5FxcKEiN
~~ 60!-!201??
83
end
~~ 234!-!253??
~~ 51!-!236??
I want to read the content between the two words (begin, en... | #include <iostream>
#include <fstream>
int main()
{
std::ifstream my_file("file.txt");
if (!my_file) {
std::cout << "No such file";
exit(1);
}
std::string qlline;
bool insideSection = false;
while (getline(my_file, qlline))
{
// I have correctly read a line from th... |
68,896,659 | 68,897,929 | Problem : "String subscript out of range" C++ | Please help me debug this code. It gives me an error "String subscript out of range"
I can't figure out why. The program needs to find numbers of substring in a string.
Here is the code :
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1;
string s2;
int count = 0;
int m ... | You are not looping through the strings correctly, so you end up going out of bounds, causing undefined behavior. You should not be using character values to know when you have reached the end of a string, use indexes instead.
Try something more like this:
#include <iostream>
#include <string>
using namespace std;
in... |
68,896,706 | 68,896,765 | std::sort of vector of lowercase strings appears to be comparing against an empty string | #include <iostream>
#include <vector>
#include <string>
int main(int argc, char const *argv[])
{
std::vector<std::string> lst{"cat", "dog", "dogs", "chicken", "chickens", "cats", "dogs"};
std::sort(lst.begin(), lst.end(), [](const auto &lhs, const auto &rhs)
{
int i = 0;
int n = lhs.size();
int m = r... |
if(i == n && i == m) return true; // same exact word
That's not a valid strict weak ordering.
|
68,897,183 | 68,897,931 | How to build an array with dimensions determined in the class | I am trying to create a 2 dimensional array of chars as an attribute for my class, but the dimensions of this array are determined by a .txt file the script is reading in the constructor of the class, and I can't manage to initialize an attribute in the constructor.
I used the template for a class from the Qt creator a... | I see some problems with your code and style:
Your data class Grid should not handle file accesses and parsing of any kind of protocol since you then bind it to this protocol
As drescherjm wrote in this comment the comma operator doesn't work like in python where you can return multiple values. See this answer for det... |
68,897,342 | 68,901,674 | What causes the following linking error with the boost c++ libraries? | Hi I get a linking error when compiling my program with the gcc compiler on cygwin. The first picture is a simple sample program from the boost filesystem libraries tutorial page where I have included filesystem.hpp in the boost folder. Beneath that is the picture of my linker error when I try to compile with the follo... |
I get a linking error when compiling my program
No, you don't. You are getting a linking error when linking your program, not when compiling it.
The reason: you didn't supply the library (-L C:/Users/.... tells the linker where to search for libraries; not which libraries to link). Your command line should look somet... |
68,897,664 | 68,898,001 | Can someone explain the last part of this code? | I am a newbie at C++. I have been writing some code for the past 2 hours. It's about finding a solution to a tridiagonal system.
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
float mat[100][100];
int n;
cout << "Enter the dimention of the matrix: ";
cin >> n;
cout << "Enter t... | I think the error is in your implementation of one of the formulas:
Particularly this one:
beta[i] = ((d[i] - a[i] * beta[i - 1]) / alpha[i]);
The correct expression should be (keep reading for another issue):
beta[i] = d[i] - (a[i] * beta[i - 1] / alpha[i]);
This one is also wrong:
x[i] = beta[i] - ((c[i] * x[i + 1]... |
68,897,687 | 68,898,712 | SFINAE for true_type and false_type in std::conditional | What's the best way to make this compile?
// Precondition: Dims is either a pointer or std::map.
using T = std::conditional_t<std::is_pointer_v<Dims>,
std::remove_pointer_t<Dims>,
typename Dims::mapped_type>;
When Dims is a pointer, I am getting:
error: template argument 3 is invalid
How do I make it work in... | template<class T>
struct mapped_type{using type=typename T::mapped_type;};
using T = typename std::conditional_t<std::is_pointer_v<Dims>,
std::remove_pointer<Dims>,
mapped_type<Dims>>::type;
we defer the "execution" until after the condition.
|
68,897,811 | 68,898,139 | define map<ivec3, my_custom_class*> | I am trying to define a map that has the key glm::ivec3 and the value Chunk* which is a class I created:
Main.cpp looks like this:
#include <map>
#include <Chunk.h>
std::map<glm::ivec3, Chunk*> chunks;
Chunk.h looks like this:
class Chunk {
public:
Chunk(glm::mat4 transform, glm::ivec3 position) :
transf... | Docs: https://en.cppreference.com/w/cpp/container/map
std::map is a sorted associative container that contains key-value
pairs with unique keys. Keys are sorted by using the comparison
function Compare
If you don't provide a Compare function (to compare keys, so keys are sorted so as to a determinated key can be qui... |
68,897,925 | 68,897,960 | SQL-database output in Qt | I have such task:
I need to make a console wrap for SQLite database. Input ios a query, output is result or error
Code is below. There's a problem with output: all ID's are 0 and names are blank. Suggest, how to make a correct output.
int main()
{
QSqlDatabase myDb = QSqlDatabase::addDatabase("QSQLITE");
myDb... | The thing is that values are carried not by Record, but by Query. So there's correct output:
while(query.next()){
std::cout << std::setiosflags(std::ios::left);
for(int j = 0; j < rec.count(); j++){
std::cout << std::setw(10)
<<query.value(j).toString().toStdString();
}
std::cout << std... |
68,898,411 | 68,898,490 | How does C++ determine this should be a string_view? | Consider the following code:
#include <optional>
#include <string_view>
int main() {
std::optional<std::string_view> opt { "abc" };
std::cout << opt.value();
return 0;
}
It compiles and when run outputs "abc" to the console. Why does it compile? The first line of code in main should be:
std::optional<std... |
How does the compiler know to make a call to the string_view constructor with the literal?
std::optional has a constructor with the form of
template < class U = T >
constexpr optional( U&& value );
This is used to directly initialize the underlying object only if T can be constructed from U, which it can in this cas... |
68,898,599 | 68,899,004 | what is a blacklist in C++? | what is a blacklist in C++ (thread) and how can it be deleted
When I run the program it just loads and nothing happens, I use a thread function. I heard that I have a blacklist and that I should delete it. I've debugged the code and after int valueSQLQuery = f.get (); nothing happens anymore.
int qstate;
int SQLQuery(... | There is no C++ specific meaning for "blacklist".
In general, "blacklist" typically means a list of entities that are to be excluded.
|
68,899,010 | 68,899,185 | Why can't I update the QTableView model inside a thread automatically? | Introduction:
I'm using QT5 and I want to update a TableView where my model for the TableView is updated inside a thread.
*Method
I create a table like this and set it's columns and rows.
/* TableView */
QStandardItemModel* looping_terminal_model = new QStandardItemModel(4, 2);
looping_terminal_model->setHeader... | No, you cannot and should not. Models are intensively used by the view so they must live (and be modified) in the same thread as the view as they are not thread-safe. The solution is to send the information to the main thread using signals and there just update the model.
|
68,899,042 | 68,899,550 | Efficiently iterating through a database row (libpqxx), assigning values to a struct | I'm grabbing a row from a database using libpqxx and assigning the fields within the pqxx::row to a struct specifically designed to hold those values:
struct driveOperationRecord
{
long int id = 0;
long int drive_operator_id = 0;
long int operator_operation_index = 0;
long int specific_operation_id = 0;... | for (auto field : entry)
{
if (!field.is_null()) record.<if only i could dynamically reference using field.name()> = field.as<somehow magically find appropriate type>();
}
This is entirely feasible, although not quite like this.
Let's just assume we can have some record of what fields driveOperationRecord (hencefo... |
68,899,578 | 68,899,839 | In C++, Is there a way to define template behavior based on whether the input class is abstract? | Background:
I've inherited a large system that makes use of templates to store meta data about classes, that may have colored some of the assumptions inherent in this question.
I'm making use of a template registration system that is partially based on an answer found here: Is there a way to instantiate objects from a ... | Use std::is_abstract:
If T is an abstract class (that is, a non-union class that declares or inherits at least one pure virtual function), provides the member constant value equal to true. For any other type, value is false.
|
68,899,814 | 68,900,034 | C++ Primer 5th edition unions and members of class type | Hello I have this from C++ primer 5th edition ch 19.6 unions:
class Token {
public:
// copy control needed because our class has a union with a string member
// defining the move constructor and move-assignment operator is left as an exercise
Token(): tok(INT), ival{0} { }
Token(const Token &t): tok(t.to... | The book is wrong. Since there is no default member initialiser for any variant member, and since there is no member initialiser for any variant member, there is no initialisation for any of the variant members. The first variant member is not active (nor any of the others).
|
68,900,001 | 68,900,419 | Non uniform texture access in vulkan glsl | I am trying to write a compute shader that raytraces an image, pixels on the right of the yz plane sample from image A, those on the left from image B.
I don't want to have to sample both images so I am trying to use non uniform access by doing:
texture(textures[nonuniformEXT(sampler_id)], vec2(0.5));
and enabling the ... | You have to enable the feature at device creation.
You can check for support of the feature by calling vkGetPhysicalDeviceFeatures2 and following the pNext chain through to a VkPhysicalDeviceVulkan12Features, and checking that shaderSampledImageArrayNonUniformIndexing member is to VK_TRUE.
After that when creating the... |
68,900,397 | 68,900,406 | What is " int x,y,z = 1 " doing, if not assigning 1 to each? | I am new to C/C++ and I noticed my program calculating wrong values. I found the problem to be my understanding of how the declaration of variables works in C/C++.
x,y,z = 1,2,3 works fine in Python where as x,y,z = 1 does not.
int x,y,z = 1,2,3 doesnt not work in C/C++ but int x,y,z = 1 does, kind of, since cout << x;... | It is shorthand for:
int x;
int y;
int z = 1;
x and y are left unassigned.
|
68,900,702 | 68,900,737 | Visual studio gives me an error when I give a string to char pointer | struct {
char* engine;
}car1,car2;
int main(void) {
car1.engine = "engine a";
car2.engine = "engine 2";
}
I'm learning thru a video on youtube about structs, and I tried running this code which was shown as an example. But VS would give me an error saying "a value of type 'const char*' cannot be assigne... |
But isnt c code supposed to work in c++?
Indeed not. Although there is some overlap between them, C and C++ are separate languages. Some C programs aren't C++ programs and some C++ programs aren't C programs.
I don't know why this happens.
The error message explains the problem. String literals are arrays of const ... |
68,901,016 | 68,901,056 | stdint types vs native types: long vs int64_t, int32_t | Has there been a change in type equivalency of uint64_t, uint32_t, long and int (i.e. the stdint and native compiler types). Or have I run into a g++ bug?
The following code in g++ 8.3 with c++17 options compiles without error. Architecture is arm 32-bit.
std::stringstream os;
void write(long value)
{
os << value;... | Yes, different CPU architectures have different sizes of fundamental types, and the fixed width aliases map to different types. This differs across operating systems as well; not just architecture. This is normal, not a bug, and generally doesn't change between compiler versions.
To avoid this problem, either provide o... |
68,901,122 | 68,902,304 | Convert IP address from String to IPAddress (Arduino) | I have an IP address that I receive as String (192,168,1,1) and I would like to put it in an object of type IPAddress. How do I do this conversion?
| Arduino core class IPAddress has method fromString.
Example:
String s = "192.168.1.55";
IPAddress ip;
ip.fromString(s);
Serial.println(ip);
|
68,901,448 | 68,901,454 | OpenCV matrix element-wise division gives all-zero result | I use OpenCV by cocoapod on iOS C++ code. When running my app, I find it works abnormally. Finally, after digging down, I can give the following reproducible sample:
{
Mat a = (Mat_<uchar>({10, 20, 30, 40, 50, 60, 70, 80})).reshape(1, 1);
Mat b = (Mat_<uchar>({4, 5, 6, 7, 8, 9, 10, 11})).reshape(1, ... | I find the answer later. Thus I post it here as a self-QA, in order to help people who have the same problem as me.
Solution: Upgrade OpenCV from 4.1 to 4.3! Then it is ok!
Actually, as you can see from the photo below, OpenCV >=4.2.0 is only available as cocoapod since 3 months ago (even if now it is 4.5.0 already)...... |
68,901,770 | 68,967,684 | C++ logical conditions inside if statements | int a = 2;
if((a = a-3 && --a ) || a--)
cout<<a<<endl;
The doubt I have is, ( a = a-3 && --a) would make a = -1 because a-3 = -1. What does the left side evaluate to? And if the compiler does go to the right side of OR does it take the original value of a (i.e. 2) or the modified value of a from the left side
Ho... |
( a = a-3 && --a) would make a = -1 because a-3 = -1.
You've missed the order of operations here, where && is evaluated before assignment. (Assignment is almost the last thing evaluated, which makes sense when it is used outside conditionals.) It is true that a-3 is -1, but that value is not assigned to a. Rather, th... |
68,901,844 | 68,902,225 | Code runs perfectly but ends with a segmentation fault after running | I've determined that my remove function for removing nodes from a linked list is the problem, but I cant see why.
void LinkedList::remove(string license){
moveToHead();
while(currentPtr != NULL){
if(getCurrent().get_licence() == license){
if(currentPtr == headPtr){
removeFromHead();
}else if... | Just looking at the logic, you are calling forward(); and listLength--; even if if(getCurrent().get_licence() == license){ is true? Shouldn't you return if the correct license is found and removed?
|
68,901,878 | 68,902,302 | How to input a string from a structure using getline? | Im currently going through C++ Basics in data structure and have a small doubt regarding strings
I am trying to input a string value from the main function by creating an instance of a structure object in the main function.
#include<iostream>
#include<sstream>
#include<string>
using namespace std;
struct StudentData ... | When you get to getline(cin, s1.name); , is is compiled to an address which contains the start of an array of string objects so the computer tries to write a string of characters to the location of a String class in memory.
This will not work because the memory is allocated to not just hold an ascii character.
I believ... |
68,902,271 | 68,903,666 | Loading a .wav into memory then playing it in C++ | None of the other answers I could find seem to work for me. I have put the contents of the sound.wav into a variable like so in order to embed the sound data into the executable without dealing with resource files:
sound.h:
std::string sound = R"(RIFFÆø^ WAVEfmt ...)";
Due to this sound file is about 30 seconds long, ... | The std::string constructor you are invoking constructs a std::string object from the source sequence up to the first NUL character.
WAVE files use the Resource Interchange File Format. After the RIFF chunk identifier, there's a 4-byte sequence designating the length. For files smaller than ~16.4MiB, the fourth byte is... |
68,902,788 | 68,902,962 | Why isn't placement new keyword/operator/function recognised without header? | In the following:
int main()
{
new int; // Works
int* pmem = 0;
new (pmem) int;// Doesn't recognize new keyword/operator/function???
}
It won't recognise 'new' in this case without including the < iostream > header. Why is that? Why doesn't 'new' require a header but placement new does? If 'new... | Placement new isn't just for "no-op" allocation. It's a general term for providing extra arguments to new beyond the object size. A standard example would be std::nothrow.
Since we are providing arguments, the compiler has to do overload resolution to choose an appropriate operator new function. And that means that ove... |
68,902,821 | 68,903,907 | Change Platform Toolset when compiling from CMD | I would like to compile a C++ program via Visual Studio command line tools. I would like to target the executable for 32 bit Windows XP. Tried compiling it the usual way, using x86 Native Tools Command Prompt for VS 2019, but it doesn't work on Windows XP, though runs fine on my Windows 10 machine.
Steps I take:
Open ... | I suggest you could try to set the PlatformToolset property:
msbuild myProject.vcxproj /p:PlatformToolset=…
For more details, I suggest you could refer to the Doc:MSBuild command-line reference
|
68,903,555 | 68,904,074 | constexpr function params for not known at compile time booleans C++ | I need to run a function with N boolean variables, I want to make them constexpr in order to exterminate comparisons and save the code from branch prediction failure.
What I mean is:
templateFunc<b1, b2, b3, b4 ...>(args...);
as the b1..bn variables are just boolean variables and may have only 2 states, I could write ... | With std::variant (C++17), you might do the dynamic dispatch via std::visit:
// helper
std::variant<std::false_type, std::true_type> to_boolean_type(bool b)
{
if (b) return std::true_type{};
return std::false_type{};
}
and then
std::visit([&](auto... bs){templateFunc<bs...>(args...);},
to_boolean_ty... |
68,903,601 | 68,903,646 | Calling a functor "pointed to" by an iterator inside a template function | The template function apply_all below takes an iterator range (itBegin -> itEnd) for a sequence of binary function objects stored in a vector. As I iterate, I want each functor to be called with the two given arguments a and b. The result is to be written to the Output Iterator (outIt), but I have no idea how to call a... | In C++17, simply using std::invoke
*outIt = std::invoke(*it, a, b);
or plain (if not a pointer to member function)
*outIt = (*it)( a, b);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.