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 |
|---|---|---|---|---|
70,382,263 | 70,382,486 | Conjunction of concepts before auto? | I'm learning C++20 concepts. Is there a way to do a conjunction of concepts in-place before an auto? For example, If I have a MutableGraph<G> concept and a VertexListGraph<G> concept, I could define
template <typename G>
concept MutableVertexListGraph = MutableGraph<G> && VertexListGraph<G>;
and do
MutableVertexListGraph auto g = ...;
but it's annoying to name the concept when it's just that I want it to model both concepts. It would be nice if I could do
MutableGraph && VertexListGraph auto g = ...; // && not allowed here.
or even something like
template <typename T, concept... Concepts> // <- "concept" not allowed here.
concept ModelsAll = (Concepts<T> && ...);
...
ModelsAll<MutableGraph, VertexListGraph> auto g = ...;
I can of course do
MutableGraph auto g = ...;
requires { MutableGraph<decltype(g)>; };
which lacks symmetry, or
auto g = ...;
requires { MutableGraph<decltype(g)>; MutableGraph<decltype(g)>; };
which lacks the concept on the declaration line.
| No, there is no way to combine concepts when applying constraints to a deduced variable definition's type.
ConceptName auto variable = ...; is fairly readable. The ConceptName is probably pretty self-explanatory, and it leaves plenty of room for the variable definition.
Concept1 && Concept2 && Concept3 auto variable = ...; is a lot less readable. At that point, the sequence of concepts crowds out the actually important parts of the statement: the variable declaration. As such, splitting it into multiple statements makes a lot more sense:
auto variable = ...;
static_assert(Concept1<decltype(variable)> && Concept2<decltype(variable)> && Concept3<decltype(variable)>);
This involves a very unfortunate amount of decltype usage (which an additional using statement could avoid), but it does separate the concerns, making the variable declaration itself more readable.
|
70,383,288 | 70,456,840 | How is optional assignment constexpr in C++ 20? | To the internal content of an optional, doesn't the optional require placement new in order to reconstruct the internal in place storage or union? Is there some new feature like placement new in C++ 20 that allows for constexpr assignment of std::optional?
template< class U = T >
optional& operator=( U&& value );
(since C++17)
(until C++20)
template< class U = T >
constexpr optional& operator=( U&& value );
(since C++20)
|
To the internal content of an optional, doesn't the optional require placement new in order to reconstruct the internal in place storage or union?
For assignment, yes it does.
But while we still cannot do actual placement new during constexpr time, we did get a workaround for its absence: std::construct_at (from P0784). This is a very limited form of placement new, but it's enough to get optional assignment working.
The other change was that we also needed to be able to actually change the active member of a union - since it wouldn't matter if we could construct the new object if we couldn't actually switch. That also happened in C++20 (P1330).
Put those together, and you get a functional implementation of optional assignment: P2231. An abbreviated implementation would look like this:
template <typename T>
struct optional {
union {
T value;
char empty;
};
bool has_value;
constexpr optional& operator=(T const& rhs) {
if (has_value) {
value = rhs;
} else {
// basically ::new (&value) T(rhs);
// except blessed for constexpr usage
std::construct_at(&value, rhs);
}
has_value = true;
return *this;
}
};
|
70,383,755 | 70,390,174 | How to save triangulation object(Constrained_Delaunay_triangulation_2) to file(vtk, vtu, msh etc) in CGAL | Created simple program based on 8.3 Example: a Constrained Delaunay Triangulation. And just wanna to export it to some common mesh file format like vtk, msh etc, to be able open it in GMesh or ParaView. To do so I found that most straightforward way is to use write_VTU. And at the beginning and at the end of example code I added next:
#include <CGAL/IO/write_VTU.h>
#include <fstream>
...
//example 8.3
...
std::ofstream mesh_file("mesh.VTU");
CGAL::write_vtu(mesh_file, cdt);
mesh_file.close();
...
As a result getting such compile time error:
[build] In file included from /home/oleg/Документи/riversim/source/../include/RiverSim.hpp:5,
[build] from /home/oleg/Документи/riversim/source/main.cpp:1:
[build] /usr/local/include/CGAL/IO/write_VTU.h: In instantiation of ‘void CGAL::IO::internal::write_VTU_with_attributes(std::ostream&, const CDT&, std::vector<std::pair<const char*, const std::vector<double>*> >&, CGAL::IO::Mode) [with CDT = CGAL::Constrained_Delaunay_triangulation_2<CGAL::Epick, CGAL::Default, CGAL::Exact_predicates_tag>; std::ostream = std::basic_ostream<char>]’:
[build] /usr/local/include/CGAL/IO/write_VTU.h:395:38: required from ‘void CGAL::IO::write_VTU(std::ostream&, const CDT&, CGAL::IO::Mode) [with CDT = CGAL::Constrained_Delaunay_triangulation_2<CGAL::Epick, CGAL::Default, CGAL::Exact_predicates_tag>; std::ostream = std::basic_ostream<char>]’
[build] /usr/local/include/CGAL/IO/write_VTU.h:406:16: required from ‘void CGAL::write_vtu(std::ostream&, const CDT&, CGAL::IO::Mode) [with CDT = CGAL::Constrained_Delaunay_triangulation_2<CGAL::Epick, CGAL::Default, CGAL::Exact_predicates_tag>; std::ostream = std::basic_ostream<char>]’
[build] /home/oleg/Документи/riversim/source/../include/RiverSim.hpp:44:47: required from here
[build] /usr/local/include/CGAL/IO/write_VTU.h:358:13: error: ‘class CGAL::Constrained_triangulation_face_base_2<CGAL::Epick, CGAL::Triangulation_face_base_2<CGAL::Epick, CGAL::Triangulation_ds_face_base_2<CGAL::Triangulation_data_structure_2<CGAL::Triangulation_vertex_base_2<CGAL::Epick, CGAL::Triangulation_ds_vertex_base_2<void> >, CGAL::Constrained_triangulation_face_base_2<CGAL::Epick, CGAL::Triangulation_face_base_2<CGAL::Epick, CGAL::Triangulation_ds_face_base_2<void> > > > > > >’ has no member named ‘is_in_domain’
[build] 358 | if(fit->is_in_domain()) ++number_of_triangles;
[build] | ~~~~~^~~~~~~~~~~~
[build] make[2]: *** [source/CMakeFiles/river.dir/build.make:63: source/CMakeFiles/river.dir/main.cpp.o] Помилка 1
[build] make[1]: *** [CMakeFiles/Makefile2:96: source/CMakeFiles/river.dir/all] Помилка 2
[build] make: *** [Makefile:84: all] Помилка 2
[build] Build finished with exit code 2
What is wrong with my ussage of write_vtu or more generally: How to export mesh object(constrained) into the file(msh, vtk, vtu etc).
UPD: Example 8.4 gives same error.
| As documented here the face type of the triangulation must be a model of DelaunayMeshFaceBase_2. You can for example use Delaunay_mesh_face_base_2 like in this example.
|
70,384,034 | 70,384,271 | Override parameter pack declaration and expansion loci | I have a simple interface setter:
template<typename Interface>
struct FrontEnd
{
virtual void inject(Interface*& ptr, Client* client) = 0;
}
I want to implement these interfaces through parameter packs like this:
template<typename ... Is>
struct BackEnd : public FrontEnd<Is>...
{
void inject(Is*& ptr, Client* client) override
{
ptr = someStuff<Is>.get(client);
}
};
However this fails with parameter pack not expanded with '...'. I couldn't find something similar to this in cppref. I have no clue where the expansion loci should go (assuming this is even legal, which I'm leaning toward no). Any idea how to provide overrides for every type in a parameter pack?
| You probably want something like this
template<typename Is>
struct OneBackEnd : public FrontEnd<Is>
{
void inject(Is*& ptr, Client* client) override { /* whatever */ }
};
template<typename ... Is>
struct BackEnd : public OneBackEnd<Is>...
{
using OneBackEnd<Is>::inject...;
};
|
70,384,319 | 70,386,903 | Define boost variant type to pass explicitly empty values | I want to have boost::variant with empty state. So I define a boost::variant with boost::blank as the first alternative. But then I want to pass this as function parameter:
void f(Variant v);
...
void g()
{
f(boost::blank{});
}
It does not look nice due to braces. Seem to be better if it accepted boost::none:
void g()
{
f(boost::none);
}
But I don't think I have seen boost::variant<boost::none_t, ...> anywhere. boost::none_t is a satellite of boost::optional. Is it fine to use with boost::variant?
| You can just default construct, which will initialize the first element type.
Alternatively you can define your own constant of type boost::blank:
Live On Wandbox
#include <boost/variant.hpp>
#include <iostream>
using Variant = boost::variant<
boost::blank,
int,
std::string>;
void foo(Variant v = {}) {
std::cout << "foo: " << v.which() << "\n";
}
int main()
{
foo();
foo({});
foo(Variant{});
foo(boost::blank{});
static constexpr boost::blank blank;
foo(blank);
foo(42);
foo("LtUaE");
}
Prints
foo: 0
foo: 0
foo: 0
foo: 0
foo: 0
foo: 1
foo: 2
|
70,384,353 | 70,385,637 | How to assign N tasks to M threads max.? | Im new to C++, and trying to get my head around multithreading. I’ve got the basics covered. Now imagine this situation:
I have, say, N tasks that I want to have completed ASAP. That‘s easy, just start N threads and lean back. But I’m not sure if this will work for N=200 or more.
So I’d like to say: I have N tasks, and I want to start a limited number of M worker threads. How do I schedule a task to be issued to a new thread once one of the previous threads has finished?
Or is all this taken care of by the OS or runtime, and I need not worry at all, even if N gets really big?
|
I have N tasks, and I want to start a limited number of M worker threads.
How do I schedule a task to be issued to a new thread once
one of the previous threads has finished?
Set your thread pool size, M, taking into account the number of threads available in your system (hardware_concurrency).
Use a counting_semaphore to make sure you don't launch a task if there is not an available thread pool slot.
Loop through your N tasks, acquiring a thread pool slot, running the task, and releasing the thread pool slot. Notice that, since tasks are launched asynchronously, you will be able to have M tasks running in parallel.
[Demo]
#include <future> // async
#include <iostream> // cout
#include <semaphore> // counting_semaphore
#include <vector>
static const size_t THREAD_POOL_SIZE_DEFAULT{ std::thread::hardware_concurrency() };
static const size_t THREAD_POOL_SIZE_MAX{ std::thread::hardware_concurrency() * 2 };
static const size_t NUM_TASKS_DEFAULT{ 20 };
template <typename F>
void run_tasks(
F&& f,
size_t thread_pool_size = THREAD_POOL_SIZE_DEFAULT,
size_t num_tasks = NUM_TASKS_DEFAULT)
{
thread_pool_size = std::min(thread_pool_size, THREAD_POOL_SIZE_MAX);
std::counting_semaphore task_slots(thread_pool_size);
auto futures{ std::vector<std::future<void>>(num_tasks) };
auto task_results{ std::vector<int>(num_tasks) };
// We can run thread_pool_size tasks in parallel
// If all task slots are busy, we have to wait for a task to finish
for (size_t i{ 0 }; i < num_tasks; ++i)
{
// Wait for a task slot to be free
task_slots.acquire();
futures[i] = std::async(
std::launch::async,
[i, &f, &task_result = task_results[i], &task_slots]() {
// Execute task
task_result = std::forward<F>(f)(i);
// Release the task slot
task_slots.release();
}
);
}
// Wait for all the tasks to finish
for (auto& future : futures) { future.get(); };
for (auto& result: task_results) { std::cout << result << " "; }
}
int main()
{
run_tasks([](int i) { return i * i; }, 4, 20);
}
|
70,384,919 | 70,385,299 | Parsing does not work: terminate called after throwing an instance of "std::invalid argument" | I want to have a function which returns a vector of 2 integers. The input is a string.
The layout of the string that is inserted should always be like this: "COORDINATES 123 456" with the coordinates being integers of any length.
If the string is "COORDINATES 123" or "COORDINATES 123 456 789", the function should return an empty vector.
#include <iostream>
#include <string>
#include <vector>
std::vector<int> getCoordinates(std::string string){
auto count = 0;
std::string coordinates;
int coordinatesInt;
std::vector<int> vector;
int i, j = 0;
for(int i = 0; i < string.size(); i++){
if(string.at(i) == ' '){
count++;
j = 1;
while(string.at(i+j) != ' ' && string.at(i+j) <= string.length()){
coordinates.push_back(string.at(i+j));
j++;
}
coordinatesInt = std::stoi(coordinates);
vector.push_back(coordinatesInt);
}
}
if(count != 2){
vector.clear();
}
std::cout << count << std::endl;
return vector;
}
int main()
{
std::string coordinates = "COORDINATES 123 456";
std::vector<int> vectorWithCoordinates = getCoordinates(coordinates);
std::cout << vectorWithCoordinates[1] << std::endl;
//vectorWithCoordinates should now contain {123, 456}
return 0;
}
However, when I run this code, I get an error message saying:
terminate called after throwing an instance of "std::invalid argument"
| #include <iostream>
#include <string>
#include <vector>
std::vector<int> getCoordinates(std::string string){
auto count = 0;
std::string coordinates;
int coordinatesInt;
std::vector<int> vector;
for(unsigned i = 0; i < string.size(); i++){
if(string.at(i) == ' '){
count++;
unsigned j = 1;
while(i+j<string.size() && string.at(i+j) != ' '){ //checks that you do not go out of range before checking the content of the string
coordinates.push_back(string.at(i+j));
j++;
}
coordinatesInt = std::stoi(coordinates);
vector.push_back(coordinatesInt);
}
coordinates.clear();//clears the string in order to have two different integers
}
if(count != 2){
vector.clear();
}
std::cout << count << std::endl;
return vector;
}
int main()
{
std::string coordinates = "COORDINATES 123 456";
std::vector<int> vectorWithCoordinates = getCoordinates(coordinates);
for(auto i : vectorWithCoordinates)
std::cout<<i<<"\n";
//vectorWithCoordinates should now contain {123, 456}
return 0;
}
The problem in the code was that you tried to access the content of the string at position i+j without being sure that that position is not out of range. I made minimal modifications to your code to obtain the right output (I think).
|
70,385,287 | 74,393,300 | CMake boost_python not found | Hi I'm having some problems with using cmake to build this example. This is what I have:
├── _build
│ ├── CMakeCache.txt
│ ├── CMakeFiles
│ ├── cmake_install.cmake
│ └── Makefile
├── CMakeLists.txt
├── hello_ext.cpp
└── README.md
CMakeLists.txt:
cmake_minimum_required(VERSION 3.16.3)
project(test)
# Find python and Boost - both are required dependencies
find_package(PythonLibs 3.8 REQUIRED)
find_package(Boost COMPONENTS python38 REQUIRED)
# Without this, any build libraries automatically have names "lib{x}.so"
set(CMAKE_SHARED_MODULE_PREFIX "")
# Add a shared module - modules are intended to be imported at runtime.
# - This is where you add the source files
add_library(hello_ext MODULE hello_ext.cpp)
# Set up the libraries and header search paths for this target
target_link_libraries(hello_ext ${Boost_LIBRARIES} ${PYTHON_LIBRARIES})
target_include_directories(hello_ext PRIVATE ${PYTHON_INCLUDE_DIRS})
hello_ext.cpp:
#include <boost/python.hpp>
char const* greet()
{
return "hello, world";
}
BOOST_PYTHON_MODULE(hello_ext)
{
using namespace boost::python;
def("greet", greet);
}
When I run cmake .. I get the following:
CMake Error at /usr/local/lib/cmake/Boost-1.77.0/BoostConfig.cmake:141 (find_package):
Could not find a configuration file for package "boost_python" that exactly
matches requested version "1.77.0".
The following configuration files were considered but not accepted:
/usr/lib/x86_64-linux-gnu/cmake/boost_python-1.71.0/boost_python-config.cmake, version: 1.71.0
/lib/x86_64-linux-gnu/cmake/boost_python-1.71.0/boost_python-config.cmake, version: 1.71.0
Call Stack (most recent call first):
/usr/local/lib/cmake/Boost-1.77.0/BoostConfig.cmake:258 (boost_find_component)
/usr/share/cmake-3.16/Modules/FindBoost.cmake:443 (find_package)
CMakeLists.txt:7 (find_package)
I've tried the answers on this question.
I don't really know what is going wrong. It seems like I don't have boost_python-1.77.0, does that even exist? Maybe I need to tell CMake to use boost 1.71?
Any help is appreciated.
| As Tsyvarev posted in the comments I just had to removed the config file in /usr/local/lib/cmake/Boost-1.77.0/BoostConfig.cmake and rebuild my project.
|
70,385,806 | 70,385,866 | How fix this : error: no member named 'setBackgroundColor' in 'QTableWidgetItem'? | ui -> tablica -> item(i, j) -> text().toInt(&f1);
if(f1)
{
ui -> tablica -> item(i, j) -> setBackgroundColor(Qt::white);
}
Error with method setBackgroundColor.
| Use: void QTableWidgetItem::setBackground(const QBrush &brush)
See here why:
https://doc.qt.io/qt-5/qtablewidgetitem-obsolete.html#setBackgroundColor
void QTableWidgetItem::setBackgroundColor(const QColor &color)
This function is obsolete. It is provided to keep old source code working. We strongly advise against using it in new code.
This function is deprecated. Use setBackground() instead.
See also backgroundColor().
|
70,385,996 | 70,386,402 | How to update comboBox items when the database is being changed? | I fill the comboBox with items from database. When I try to add new item, erasing all items and adding them again, if db is being changed, I see these errors:
QSqlDatabasePrivate::addDatabase: duplicate connection name 'qt_sql_default_connection', old connection removed.
QSqlDatabasePrivate::addDatabase: duplicate connection name 'qt_sql_default_connection', old connection removed.
QSqlQuery::value: not positioned on a valid record created
terminate called after throwing an instance of 'std::invalid_argument' what(): stoi
21:41:04: Debugging of C:\Users\79107\Downloads\build-food_calculator-Desktop_Qt_6_2_2_MinGW_64_bit-Debug\debug\food_calculator.exe has finished with exit code 3.
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
MainWindow::foodListConstructor();//function, that fills the comboBox
}
void MainWindow::foodListConstructor()
{
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("food_list.db");
db.open();
QSqlQuery query("SELECT food_name FROM food", db);
if(query.isActive())
{
while(query.next())
{
ui->comboBox->addItem(query.value(0).toString());
}
}
}
void MainWindow::on_action_3_triggered()
{
AddFood af(this);// in this new window a user writes what he wants to add
af.setModal(true);
af.exec();
this->ui->comboBox->clear();
this->ui->comboBox->addItem("test");
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("food_list.db");
db.open();
QSqlQuery query1("SELECT food_name FROM food", db);
if(query1.isActive())
{
while(query1.next())
{
ui->comboBox->addItem(query1.value(0).toString());
}
}
How to make it work and not to dupliacte items (this happens if I remove "this->ui->comboBox->clear();")?
| If you call foodListConstructor() multiple times, you are going to be calling addDatabase() multiple times. Which is perfectly fine, per the documentation:
Adds a database to the list of database connections using the driver type and the connection name connectionName. If there already exists a database connection called connectionName, that connection is removed.
So it would seem you are simply seeing debug messages being output internally by Qt. This is not a real error, so just ignore it. Although, there is no point in adding the same database over and over. I would suggest just adding it once, and then use QSqlDatabase::database() to access it when needed.
The QSqlQuery error is pretty self-explanatory. You tried to read a field value when the query was not on an active record. Again, that appears like another internal debug message, not a real error. Per the documentation:
An invalid QVariant is returned if field index does not exist, if the query is inactive, or if the query is positioned on an invalid record.
Why are you getting an invalid QVariant from an inactive SQL record? That I couldn't say. You will have to figure that out for yourself.
But it explains the final terminate message, which is a real error. You are calling toString() on an invalid QVariant:
Calling QVariant::toString() on an unsupported variant returns an empty string.
Somewhere along the way, std::stoi() is being called with a string that doesn't represent an integer value (ie, likely the empty string you are adding to the comboBox), so it throws a std::invalid_argument exception that you are not catching, which is escaping out of your app's main function, causing the C++ runtime to call std::terminate() to exit the app.
Where is std::stoi() being called? You need to search your code for that. Do you have some event handler hooked up to the comboBox?
With that said, try something more like this:
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("food_list.db");
foodListConstructor();
}
void MainWindow::foodListConstructor()
{
ui->comboBox->clear();
QSqlDatabase db = QSqlDatabase::database("QSQLITE");
QSqlQuery query("SELECT food_name FROM food", db);
while (query.next())
{
QVariant v = query.value(0);
if (v.isValid())
ui->comboBox->addItem(v.toString());
}
}
void MainWindow::on_action_3_triggered()
{
AddFood af(this);
af.setModal(true);
af.exec();
foodListConstructor();
}
|
70,386,101 | 70,386,256 | Thread pool not completing all tasks | I have asked a simpler version of this question before and got the correct answer: Thread pools not working with large number of tasks
Now I am trying to run tasks from an object of a class in parallel using a thread pool. My task is simple and only prints a number for that instance of class. I am expecting numbers 0->9 get printed but instead I get some numbers get printed more than once and some numbers not printed at all. Can anyone see what I am doing wrong with creating tasks in my loop?
#include "iostream"
#include "ThreadPool.h"
#include <chrono>
#include <thread>
using namespace std;
using namespace dynamicThreadPool;
class test {
int x;
public:
test(int x_in) : x(x_in) {}
void task()
{
cout << x << endl;
}
};
int main(void)
{
thread_pool pool;
for (int i = 0; i < 10; i++)
{
test* myTest = new test(i);
std::function<void()> myFunction = [&] {myTest->task(); };
pool.submit(myFunction);
}
while (!pool.isQueueEmpty())
{
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
cout << "waiting for tasks to complete" << endl;
}
return 0;
}
And here is my thread pool, I got this definition from "C++ Concurrency in Action" book:
#pragma once
#include <queue>
#include <future>
#include <list>
#include <functional>
#include <memory>
template<typename T>
class threadsafe_queue
{
private:
mutable std::mutex mut;
std::queue<T> data_queue;
std::condition_variable data_cond;
public:
threadsafe_queue() {}
void push(T new_value)
{
std::lock_guard<std::mutex> lk(mut);
data_queue.push(std::move(new_value));
data_cond.notify_one();
}
void wait_and_pop(T& value)
{
std::unique_lock<std::mutex> lk(mut);
data_cond.wait(lk, [this] {return !data_queue.empty(); });
value = std::move(data_queue.front());
data_queue.pop();
}
bool try_pop(T& value)
{
std::lock_guard<std::mutex> lk(mut);
if (data_queue.empty())
return false;
value = std::move(data_queue.front());
data_queue.pop();
return true;
}
bool empty() const
{
std::lock_guard<std::mutex> lk(mut);
return data_queue.empty();
}
};
class join_threads
{
std::vector<std::thread>& threads;
public:
explicit join_threads(std::vector<std::thread>& threads_) : threads(threads_) {}
~join_threads()
{
for (unsigned long i = 0; i < threads.size(); i++)
{
if (threads[i].joinable())
{
threads[i].join();
}
}
}
};
class thread_pool
{
std::atomic_bool done;
threadsafe_queue<std::function<void()> > work_queue;
std::vector<std::thread> threads;
join_threads joiner;
void worker_thread()
{
while (!done)
{
std::function<void()> task;
if (work_queue.try_pop(task))
{
task();
}
else
{
std::this_thread::yield();
}
}
}
public:
thread_pool() : done(false), joiner(threads)
{
unsigned const thread_count = std::thread::hardware_concurrency();
try
{
for (unsigned i = 0; i < thread_count; i++)
{
threads.push_back(std::thread(&thread_pool::worker_thread, this));
}
}
catch (...)
{
done = true;
throw;
}
}
~thread_pool()
{
done = true;
}
template<typename FunctionType>
void submit(FunctionType f)
{
work_queue.push(std::function<void()>(f));
}
bool isQueueEmpty()
{
return work_queue.empty();
}
};
| There's too much code to analyse all of it but you take a pointer by reference here:
{
test* myTest = new test(i);
std::function<void()> myFunction = [&] {myTest->task(); };
pool.submit(myFunction);
} // pointer goes out of scope
After that pointer has gone out of scope you will have undefined behavior if you later do myTest->task();.
To solve that immediate problem, copy the pointer and delete the object afterwards to not leak memory:
{
test* myTest = new test(i);
std::function<void()> myFunction = [=] {myTest->task(); delete myTest; };
pool.submit(myFunction);
}
I suspect this could be solved without using new at all, but I'll leave that up to you.
|
70,386,516 | 70,386,661 | Exception in constructor initialization list | Lets say I have the following code
class B
{ /* implementation*/ };
class A
{
B b;
char * c;
A() : b(), c(new char[1024])
{}
~A()
{
delete[] c;
}
};
int main()
{
A* a = nullptr;
try
{
a = new A();
}
catch(...)
{
}
}
I want to understand what will happen if c(new char[1024]) will throw exception? Will b correctly destroyed? Can caller catch this exception? If yes, what will be the value of a? Will ~A() be called? Is it good practice to call functions in the constructor initialization list that can throw an exception?
|
I want to understand what will happen if c(new char[1024]) will throw exception? Will b correctly destroyed?
Yes. When a constructor throws, any already-constructed members and base classes are destructed automatically.
Can caller catch this exception?
Yes.
If yes, what will be the value of a?
nullptr, because that is what you initialized a with, and the exception is thrown before you can assign a new value to a.
Will ~A() be called?
No. If A() does not complete cleanly, the ~A() destructor is not called. And you are not calling delete on any fully constructed A object, either.
Is it good practice to call functions in the constructor initialization list that can throw an exception?
That is perfectly fine. Just make sure that any previously constructed members are cleaned up properly to avoid any leaks.
For example:
class A
{
B * b;
char * c;
B* getB() { return new B; }
char* getC() { return new char[1024]; }
public:
A() : b(getB()), c(getC())
{}
~A()
{
delete b;
delete[] c;
}
};
b is initialized before c, so if getC() throws then the memory that b is pointing at will be leaked.
You can fix that in one of two ways:
moving the allocations into the constructor body and using normal exception handling:
class A
{
B * b;
char * c;
B* getB() { return new B; }
char* getC() { return new char[1024]; }
public:
A()
{
b = getB();
try
{
c = getC();
}
catch(...)
{
delete b;
throw;
}
}
~A()
{
delete b;
delete[] c;
}
};
using smart pointers:
class A
{
std::unique_ptr<B> b;
std::unique_ptr<char[]> c;
std::unique_ptr<B> getB() { return std::make_unique<B>(); }
std::unique_ptr<char[]> getC() { return std::make_unique<char[]>(1024); }
public:
A() : b(getB()), c(getC())
{}
~A() = default;
};
|
70,387,136 | 70,387,307 | Iterating over first n elements of a container - std::span vs views::take vs ranges::subrange | So with c++ 20 we get a lot of new features with ranges, spans and so on. Now if i need to iterate over a container, but only the first n elements, what would be the most appropriate way and is there any practical difference going on behind the scenes? Or is it perhaps a better idea to just go back to regular for loops with indexes as these examples might be less performant?
for (const auto &e: elements | std::ranges::views::take(n)) {
// do stuff
}
for (const auto &e: std::span(elements.begin(), n)) {
// do stuff
}
for (const auto &e: std::ranges::subrange(elements.begin(), elements.begin() + n)) {
// do stuff
}
|
views::take is the most generic, it is suitable for almost any range, such as input_range, output_range, and more refined ranges.
std::span only applies to contiguous_range.
Although ranges::subrange is also generic, but since you need to obtain the bound of iterator through elements.begin() + n, this requires that the elements must be a random_access_range.
It is also worth noting that after P1739, views::take will get an "appropriate" range type according to the type of range, that is, when the range is span, it will return span, and when it is string_view, it will return string_view, and when it is subrange, it will return subrange, and when it is iota_view, it will return iota_view.
|
70,387,151 | 70,745,139 | Fully embedding python into Qt application | I am looking for a way of fully embedding python into a Qt application. With this, I mean that I want to build a Qt application that executes python code and I can fully distribute without having to care about which python version is installed in the target machine, or without having to ask the future user to install python by him/herself.
I've checked the libraries PythonQt, PyBind11, Boost.Python, and the native python libraries, and they are good to link C++ to Python, but any of them do what I want to do.
I have tried the following in Linux, and I was planning to do the same (or at least a similar approach) on Windows and Mac:
Download source code of Python (In my case, Python 3.9).
Build python.
mkdir build
cd build
../configure --enable-optimizations --enable-shared
make
make install DESTDIR=installed/
Copy contents of installed into the dependencies folder of my projects. The contents of installer are the following folders:
- bin: Contains python executable and some tools like pip.
- include: Contains all of the headers of python.
- lib: Contains the .so libraries and the python modules (if you install a new python module using pip, it will be installed here in python3.9/site-packages/).
- shared: Contains the man entries of python.
Having Python3.9 build, I have not installed any library yet, to test if this is the python that C++ is calling.
I have linked it from my Qt application in my .pro file like this:
INCLUDEPATH += $$PWD/../dependencies/python3.9/linux/include/python3.9
DEPENDPATH += $$PWD/../dependencies/python3.9/linux/include/python3.9
LIBS += -L$$PWD/../dependencies/python3.9/linux/lib/ -lpython3.9
Once linked, I call python like this:
Py_SetPythonHome(L"/link/to/dependencies/python3.9/linux/lib/python3.9/");
Py_SetPath(L"/link/to/dependencies/python3.9/linux/lib/python3.9/");
wchar_t *program = Py_DecodeLocale("", NULL);
if (program == NULL) {
fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
exit(1);
}
Py_SetProgramName(program); /* optional but recommended */
Py_Initialize();
PyRun_SimpleString("import pgmpy");
if (Py_FinalizeEx() < 0) {
exit(120);
}
PyMem_RawFree(program);
In this code, I am importing the library pgmpy. This package is not installed in the version of python I have build. However, it is installed in my local version of python, meaning that it is not using the python I have build, even when this is the one linked.
Is there any configuration step or something that I have missing? Is this ever feasible? I am more interested in solutions that are not specific to Qt, but can be applied to any C++ project, that is one of the reasons why I am using pybind11 and not pythonQt
Thank you.
| I finally found a workaround.
I executed the python interpreter from terminal, and printed sys.path, showing the correct paths.
Then, in C++, I appended the correct paths to sys.path, removing the wrong ones.
|
70,387,327 | 70,387,486 | cout operator << doesn't work for vector<char> | Why doesn't this vector print out?
void str_read(std::vector<char> str);
int main() {
std::vector<char> str;
str_read(str);
std::cout << str << std::endl;
return -1;
}
void str_read(std::vector<char> str) {
while (1) {
char ch;
scanf("%c", &ch);
if (ch == '\n');
break;
}
}
I get an error:
error: no type named 'type' in 'struct std::enable_if<false, void>'
| You get the error because there is no standard operator<< defined for std::vector. If you want that, you have to implement it yourself.
Even so, str_read() takes in a std::vector by value, so it receives a copy of the caller's vector, and thus any modifications it makes will be to that copy and thus lost when str_read() exits. That means the vector in main() is never populated.
Try this instead:
#include <iostream>
#include <vector>
#include <string>
std::ostream operator<<(std::ostream &out, const std::vector<char> &vec) {
for(auto ch : vec) {
out << ch;
}
return out;
/* alternatively:
return out.write(vec.data(), vec.size());
*/
}
void str_read(std::vector<char> &str) {
char ch;
while (cin.get(ch) && ch != '\n') {
str.push_back(ch);
}
}
int main() {
std::vector<char> str;
str_read(str);
std::cout << str << std::endl;
}
That being said, why not just use std::string instead of std::vector<char>? There is a standard operator<< defined for std::string, and a standard std::getline() function for reading characters into std::string until '\n':
#include <iostream>
#include <string>
int main() {
std::string str;
std::getline(cin, str);
std::cout << str << std::endl;
}
|
70,387,840 | 70,477,519 | Does something wrong with Widget&& var1 = someWidget;? | recently, i began to learing something about universal reference https://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers and it says that Widget&& var1 = someWidget; //here, "&&" means rvalue reference. i know that "&&" can be universal reference or rvalue reference,but i thought somewidget must be a lvalue, and there is no deduce here, so Widget&& && must be rvalue reference, and here is the question. can rvalue reference accept a lvalue, i have learnt that lvalue reference can accept lvalue, and const lvalue reference can accept rvalue, but rvalue reference can only accept rvalue, so is there something wrong with this statement ? or something i miss
| I found that blog post to be confusing. I'd recommend reading a good chapter in a book or the standard itself instead of that post. Part of the problem is that the blog post is 10 years old, so people were still thinking about the new features and how to teach them. I don't think that code even compiles though. I tested int a = 5; int &&b = a; and got a compile-time error as expected. I think he meant something like widget{} by someWidget. int &&j = int{5}; compiles fine.
However, if you have a template function like void f(T &&t), it can turn into an lvalue reference or an rvalue reference, depending on what is passed to it. The main point of that is to implement perfect forwarding. The old way to do that was to innumerate all possible combinations of arguments, which is exponential in the number of arguments taken. Now, you can write one function that can call other functions with as much efficiency as possible, using the fact something is an rvalue if it is one. Consider the following example:
struct W
{
W(int &, int &) {}
};
struct X
{
X(int const &, int &) {}
};
struct Y
{
Y(int &, int const &) {}
};
struct Z
{
Z(int const &, int const &) {}
};
template <typename T, typename A1, typename A2>
T* factory(A1 &&a1, A2 &&a2)
{
return new T(std::forward<A1>(a1), std::forward<A2>(a2));
}
int main()
{
int a = 4;
int b = 5;
W *pw = factory<W>(a, b);
X *px = factory<X>(2, b);
Y *py = factory<Y>(a, 2);
Z *pz = factory<Z>(2, 2);
delete pw;
delete px;
delete py;
delete pz;
}
|
70,387,878 | 70,400,473 | Does using sigwait and signalfd concurrently in a multithreaded program result in a race condition? | I am writing a multi-threaded program where, among other things, I have a thread listening to a socket for incoming network connections. To allow this to be interrupted, I am using poll in combination with signalfd (rather than a raw await call). However, I also have other threads that I need to be able to notify of potential interrupts, so I am using a sigwait call in a dedicated thread to wait for signals. My attempt to get the race to occur is in the code below:
int main()
{
int sigval = 0;
sigset_t mask;
sigemptyset (&mask);
sigaddset (&mask, SIGINT);
pthread_sigmask(SIG_BLOCK, &mask, nullptr);
int sfd = signalfd(-1, &mask, SFD_NONBLOCK);
auto handler = std::thread([&] {
int signal;
sigwait(&mask, &signal);
sigval = signal;
});
pollfd pfd[1] = {{.fd=sfd, .events=POLLIN}};
int ret = poll(pfd, 1, -1);
std::cout << "Poll returned with revents = " << pfd[0].revents << std::endl;
handler.join();
std::cout << "Handled thread set sigval to: " << sigval << std::endl;
return 0;
}
Every time I run this and kill it with SIGINT, it appears to work, in that the poll call returns, and sigval is set by the handler thread. However, my understanding is that sigwait consumes the signal, while signalfd does not. So, if somehow sigwait was called before signalfd received notification of the signal, this program could potentially hang forever (with poll waiting for a signal that isn't coming). I assume since I can't manage to get the program to hang that there is something on beneath the hood that prevents this from happening, but can I guarantee that this will always be true?
| I have looked into the linux source code, and have come up with an answer to my own question: there is no race condition, as the signalfd watchers are explicitly notified before the signal is sent, so they will always be notified before the signal is sent (and caught). Specifically, in linux/kernel/signal.c, we see:
out_set:
signalfd_notify(t, sig); // <-- signalfd notified
sigaddset(&pending->signal, sig);
...
complete_signal(sig, t, type); // <-- sends the signal
so it is not possible for sigwait to consume the signal before signalfd is notified about the signal.
|
70,387,906 | 70,388,124 | How and when does the mem size of a parameter in a function, in c++, will be a concern? | Recently I received a feedback on a issue with the following warning from a colleague, who uses Coverity, a static analysis tool.
Passing the value of a large parameter (PASS_BY_VALUE)
pass_by_value: Passing parameter parameter_name of type class_name (size 184 bytes) by value, which exceeds the low threshold of 128 Passing parameter
This led me to wonder about how the size of the parameter will affect the quality of the application, and when will it be a major concern if the size of the parameter get out of hand?
And what is a good rule of thumb to keep it in check?
|
Pass by value
Pass by reference
Advantage
cost of passing the argument
copy object
copy pointer
by value, if sizeof(T) <= sizeof(T*),by ref, if sizeof(T) > sizeof(T*)
object access
direct
indirect
by value
can alias
no the optimizer can do more access optimizations
yesoptimizer is restricted in access optimization
by value
For object smaller or equal in size to the size of a pointer it's a no brainer: pass by value has no disadvantages compared to pass by ref, only advantages.
As you consider bigger objects the cost of copying will eventually outweigh the disadvantages of pass by ref. Where that line is it's difficult to tell. And that line differs on different architectures and calling conventions. For your environment Coverity draws the line at 128 bytes, which I am sure is arrived at by smart people with experience and from doing relevant tests. You can use that limit, you can use another one if you want or you can profile your application to see what applies to your case.
|
70,387,962 | 70,387,994 | Does declaring a constructor '= default' in a header file break the ODR | If I define the destructor (or any autogenerated constructor) as default like this:
struct A {
~A() = default;
};
And then include this in several translation units, does this break the ODR? Can someone walk me through the steps at on the ODR page? Because i am struggling to understand if the compiler generated destructor will be inline or some other effect to prevent it from breaking the ODR.
| No ODR violation. Member functions are implicitly inline if they are defined, defaulted or deleted inside a class definition.
https://en.cppreference.com/w/cpp/language/inline
The implicitly-generated member functions and any member function
declared as defaulted on its first declaration are inline just like
any other function defined inside a class definition.
// header file
// OK, implicit inline
struct A {
~A() {}
};
// header file
// OK, implicit inline
struct A {
~A() = default;
};
// header file
struct A {
~A();
};
// NOT ok, ODR violation when header is included in more than 1 TU
A::~A() {};
// header file
struct A {
~A();
};
// NOT ok, ODR violation when header is included in more than 1 TU
A::~A() = default;
|
70,388,077 | 70,388,217 | Working with std::unique_ptr and std::queue | Maybe it's my sinuses and that I fact that I just started learning about smart pointers today I'm trying to do the following:
Push to the queue
Get the element in the front
Pop the element (I think it will automatically deque once the address out of scope)
Here is the error
main.cpp:50:25: error: cannot convert ‘std::remove_reference&>::type’ {aka ‘std::unique_ptr’} to ‘std::unique_ptr*’ in assignment
50 | inputFrame = std::move(PacketQueue.front());
| ~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~
| |
| std::remove_reference<std::unique_ptr<MyObject::Packet>&>::type {aka std::unique_ptr<MyObject::Packet>}
Here is the code
#include <iostream>
#include <memory>
#include <queue>
using namespace std;
class MyObject
{
public:
struct Packet
{
uint8_t message;
uint8_t index;
};
void pushToQueue(void);
void FrontOfQueue(std::unique_ptr<Packet> *inputFrame);
private:
std::queue<std::unique_ptr<Packet>> PacketQueue;
};
void MyObject::pushToQueue(void)
{
Packet frame;
static int counter = 1;
frame.message = counter;
frame.index =counter;
counter++;
std::unique_ptr<Packet> passthru_ptr = std::make_unique<Packet>(std::move(frame));
PacketQueue.push(std::move(passthru_ptr));
cout<<"Pushed to queue\n" ;
}
void MyObject::FrontOfQueue(std::unique_ptr<Packet> *inputFrame)
{
inputFrame = std::move(PacketQueue.front());
}
int main()
{
cout<<"Hello World\n";
MyObject object;
object.pushToQueue();
object.pushToQueue();
{
// Scope
std::unique_ptr<MyObject::Packet> *frame;
object.FrontOfQueue(frame);
cout<< frame << endl;
}
{
// Scope
std::unique_ptr<MyObject::Packet> *frame2;
object.FrontOfQueue(frame2);
cout<< frame2 << endl;
}
return 0;
}
Link to the code (Online Compiler)
| If I got your aim correctly, you definitely want
std::unique_ptr<MyObject::Packet> MyObject::FrontOfQueue()
{
auto rv = std::move(PacketQueue.front());
PacketQueue.pop();
return rv;
}
// ...
std::unique_ptr<MyObject::Packet> frame = object.FrontOfQueue();
Notice, no raw pointers are used.
I think it will automatically deque once the address out of scope.
This assumption is wrong. Nothing is dequeued until .pop() is called.
|
70,388,341 | 70,388,386 | Why am I unable to use a variable when using the map() function? | int main()
{
unsigned int num = 2;
string map[num][3] = {{"c","d","s"}, {"A", "u", "p"}};
for(int y = 0; y < 2; y++)
{
for(int x = 0; x < 3; x++)
{
cout << map[y][x];
}
cout << endl;
}
}
I'm using Xcode and it gives me an error saying "Variable-sized object may not be initialized". Am I simply doing it wrong or is the map function unable to take in variables as arguments?
|
You can declare an array only with constant size, which can be deduced
at compile time.
source: variable-sized object may not be initialized c++
SO, change the line:
unsigned int num = 2;
to this:
unsigned const num = 2;
|
70,388,370 | 70,391,110 | How to make the conversion from 'int' to 'char' reasonable under -Werror=conversion option? c++11 | error: conversion from ‘int’ to ‘char’ may change value [-Werror=conversion]
build cmd example:
g++ -std=c++11 test.cpp -o a.out -Werror=conversion
auto index = 3;
char singleChar = 'A' + index; // I want to get A-Z
I hope sigleChar is dynamically assigned.
could you pls help me to solve this error report without using switch?
How would it be better to write code?
| 'A' + index; // I want to get A-Z would only works for ASCII, not EBCDIC for example.
A more portable solution (and not int to char conversion involved) is array indexing:
char singleChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[index];
|
70,388,536 | 70,395,182 | Boost.Asio async_read a string from a socket | I'm trying to write a function async_read_string_n to asynchronously read a string of exactly n bytes from a socket with Boost.Asio 1.78 (and GCC 11.2).
This is how I want to use the function async_read_string_n:
void run() {
co_spawn (io_context_, [&]() -> awaitable<void> {
auto executor = io_context_.get_executor();
tcp::acceptor acceptor(executor, listen_endpoint_);
auto [ec, socket] = co_await acceptor.async_accept(as_tuple(use_awaitable));
co_spawn(executor, [&]() -> awaitable<void> {
auto [ec, header] = co_await async_read_string_n(socket, 6, as_tuple(use_awaitable));
std::cerr << "received string " << header << "\n";
co_return;
}
, detached);
co_return;
}
, detached);
}
Here is my attempt to write async_read_string_n, following the advice in
https://www.boost.org/doc/libs/1_78_0/doc/html/boost_asio/reference/asynchronous_operations.html#boost_asio.reference.asynchronous_operations.automatic_deduction_of_initiating_function_return_type
https://www.boost.org/doc/libs/1_78_0/doc/html/boost_asio/overview/core/cpp20_coroutines.html#boost_asio.overview.core.cpp20_coroutines.error_handling
(I don't care about memory copying. This isn't supposed to be fast; it's supposed to have a nice API.)
template<class CompletionToken> auto async_read_string_n(tcp::socket& socket, int n, CompletionToken&& token) {
async_completion<CompletionToken, void(boost::system::error_code, std::string)> init(token);
asio::streambuf b;
asio::streambuf::mutable_buffers_type bufs = b.prepare(n);
auto [ec, bytes_transferred] = co_await asio::async_read(socket, bufs, asio::transfer_exactly(n), as_tuple(use_awaitable));
b.commit(n);
std::istream is(&b);
std::string s;
is >> s;
b.consume(n);
init.completion_handler(ec, s);
return init.result.get();
}
Edit
(I had a syntax error and I fixed it.) Here is the compiler error in async_read_string_n which I'm stuck on:
GCC error:
error: 'co_await' cannot be used in a function with a deduced return type
How can I write the function async_read_string_n?
| You don't have to use streambuf. Regardless, using the >> extraction will not reliably extract the string (whitespace stops the input).
The bigger problem is that you have to choose whether you want to use
co_await (which requires another kind of signature as your second link correctly shows)
or the async result protocol, which implies that the caller will decide what mechanism to use (a callback, future, group, awaitable etc).
So either make it:
Using Async Result Protocol:
#include <boost/asio.hpp>
#include <boost/asio/awaitable.hpp>
#include <boost/asio/experimental/as_tuple.hpp>
#include <boost/asio/use_awaitable.hpp>
#include <iostream>
#include <iomanip>
namespace net = boost::asio;
using net::ip::tcp;
using boost::system::error_code;
template <typename CompletionToken>
auto async_read_string_n(tcp::socket& socket, int n, CompletionToken&& token)
{
struct Op {
net::async_completion<CompletionToken, void(error_code, std::string)>
init;
std::string buf;
Op(CompletionToken token) : init(token) {}
};
auto op = std::make_shared<Op>(token);
net::async_read(socket, net::dynamic_buffer(op->buf),
net::transfer_exactly(n), [op](error_code ec, size_t n) {
op->init.completion_handler(ec, std::move(op->buf));
});
return op->init.result.get();
}
int main() {
net::io_context ioc;
tcp::socket s(ioc);
s.connect({{}, 8989});
async_read_string_n(s, 10, [](error_code ec, std::string s) {
std::cout << "Read " << ec.message() << ": " << std::quoted(s)
<< std::endl;
});
ioc.run();
}
Prints
NOTE This version affords you the calling semantics that you desire in your sample run() function.
OR Use co_await
Analogous to the sample here:
boost::asio::awaitable<void> echo(tcp::socket socket)
{
char data[1024];
for (;;)
{
auto [ec, n] = co_await socket.async_read_some(boost::asio::buffer(data),
boost::asio::experimental::as_tuple(boost::asio::use_awaitable));
if (!ec)
{
// success
}
// ...
}
}
|
70,388,731 | 70,389,273 | How to Use std::any as mapped_type | I am trying to solve the problem asked yesterday on SO based on this answer.
I have modified the code given here to use std::any instead of void*. The code that i currently have is as follows:
#include <iostream>
#include <map>
#include <vector>
#include <any>
#include <typeindex>
struct cStreet{};
struct cHouse{};
struct cComputer{};
struct cBook{};
class cPlayer
{
public:
struct Properties
{
std::vector<cStreet*> Streets;
std::vector<cHouse*> Houses;
std::vector<cComputer*> Computers;
std::vector<cBook*> Book;
};
cPlayer(std::string name) : m_name{name}{};
~cPlayer(){};
std::string m_name{};
Properties m_Properties;
std::map<std::type_index, std::any> myMap{{typeid(cStreet*), m_Properties.Streets}, {typeid(cHouse*), m_Properties.Houses}, {typeid(cComputer*), m_Properties.Computers}, {typeid(cBook*), m_Properties.Book}};
template<typename T> void buy(T& Arg);
};
template<typename T> void cPlayer::buy(T& Arg)
{
std::cout << m_name.c_str() << " : Do you want buy this ?" <<typeid(Arg).name() << std::endl;
//Todo: Decision (here yes)
std::any_cast<std::vector<decltype(&Arg)>>(myMap.at(typeid(&Arg))).push_back(&Arg); //THIS DOESN'T ADD ELEMENTS INTO THE VECTORS BECAUSE STD::ANY HAS A COPY OF THE ORIGINAL VECTORS
}
int main()
{
//create objects
cStreet S;
cHouse H;
cComputer C;
cBook B;
cPlayer c("anoop");
//lets test our code
c.buy(S);
c.buy(H);
c.buy(C);
c.buy(B);
}
The problem is that when i wrote
std::any_cast<std::vector<decltype(&Arg)>>(myMap.at(typeid(&Arg))).push_back(&Arg);
this does not adds(push_back) element into the original vectors but a copy of it.
How can i add element into the original vectors m_Properties.Streets, m_Properties.Houses etc? I tried using std::ref but i was not able to successfully do it using std::ref.
| Based on this answer, redefine your myMap as:
std::map<std::type_index, std::any> myMap{
{typeid(cStreet*), std::ref(m_Properties.Streets)},
{typeid(cHouse*), std::ref(m_Properties.Houses)},
{typeid(cComputer*), std::ref(m_Properties.Computers)},
{typeid(cBook*), std::ref(m_Properties.Book)}
};
Then cast any to the corresponding reference_wrapper type according to T to access the original vector:
template<typename T>
void cPlayer::buy(T& Arg) {
// ...
using mapped_type = std::reference_wrapper<std::vector<T*>>;
std::any_cast<mapped_type>(myMap.at(typeid(T*))).get().push_back(&Arg);
// ...
}
|
70,389,159 | 70,389,578 | How to convert GL_RED to GL_RGBA format | This is the code for the fragment shader.
in vec2 TexCoord;
uniform sampler2D texture1;
out vec4 OutColor;
void main()
{
OutColor = texture( texture1 , TexCoord);
}
Whenever any GL_RED format texture is passed the greyscale image outputs as red in color.
I can fix that by using the red parameter of the texture in the shader but is it possible to send GL_RED image as GL_RGBA image to the shader.
unsigned char* image = SOIL_load_image(file, &width, &height, &channels , SOIL_LOAD_AUTO);
// Set The Internal Format
if (channels == 4)
{
texture.Internal_Format = gammaCorrect ? GL_SRGB_ALPHA : GL_RGBA;
texture.Image_Format = gammaCorrect ? GL_SRGB_ALPHA : GL_RGBA;
}
else if(channels == 3)
{
texture.Internal_Format = gammaCorrect ? GL_SRGB : GL_RGB;
texture.Image_Format = gammaCorrect ? GL_SRGB : GL_RGB;
}
else if (channels == 1)
{
texture.Internal_Format = GL_RED;
texture.Image_Format = GL_RED;
}
| Set the texture swizzle parameters with glTexParameter. e.g.:
glBindTexture(GL_TEXTURE_2D, textureObject);
if (channels == 1)
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_RED);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_RED);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, GL_RED);
}
This sets the swizzle that will be applied to a component. With that a component can be taken from a different channel.
|
70,389,233 | 70,395,552 | Changing the center of a gaussian using FFTW in C++ | For a project I need to propagate a gaussian in real space using the Fourier transform of a gaussian centered at the origin using
What I want to calculate
Here is the latex code, since I can't include images yet
N(x | \mu, \sigma) = F^{-1}{F{ N(x |0, \sigma)} e^{-i\ 2\pi \mu\omega} \right},
where \omega is the frequency in Fourier space.
Now the problem I am having is I don't know how to calculate the frequency for some bin after doing the fft with fftw. Here is the code of what I am trying to do.
int main(){
int N = 128; //Number of "pixels" in real space
int N_fft = N/2 + 1;
double *in, *result, *x;
fftw_complex *out;
fftw_plan fw, bw;
in = (double*) fftw_malloc(sizeof(double) * N);
x = (double*) malloc(sizeof(double) * N);
out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N_fft);
result = (double*) fftw_malloc(sizeof(double) * N);
fw = fftw_plan_dft_r2c_1d(N, in, out, FFTW_ESTIMATE);
bw = fftw_plan_dft_c2r_1d(N, out, result, FFTW_ESTIMATE);
double min_x = -9.0, max_x = 9.0; //Limits in real space
for (int i=0; i<N; i++){
x[i] = min_x + 2*max_x*i / (N - 1);
in[i] = std::exp(-(x[i]) * (x[i]));
}
for (int i=0; i<N_fft; i++){
out[i][0] = 0.0;
out[i][1] = 0.0;
}
fftw_execute(fw);
double w;
fftw_complex z;
double w_norm;
for (int i=0; i<N_fft; i++){
w = -2*M_PI*i / (max_x - min_x); //WHAT I DON'T KNOW
// Calculating the product with the exponential for translating the gaussian
z[0] = out[i][0]*std::cos(w) - out[i][1]*std::sin(w);
z[1] = out[i][0]*std::sin(w) + out[i][0]*std::cos(w);
out[i][0] = z[0];
out[i][1] = z[1];
}
fftw_execute(bw);
for (int i=0; i<N; i++){
std::cout << x[i] << " " << result[i]/N << " " << std::exp(-x[i] * x[i]) << std::endl;
}
fftw_destroy_plan(fw);
fftw_free(in);
fftw_free(out);
return 0;
}
For the moment I've tried using w-nth = -2*np.pi * 1/(max_x - min_x) * n, which worked in python, but for some reason it doesn't work in c++
Here is the result I am obtaining with c++
result
Here ref is the gaussian centered at 0, the one I obtaing should be centered at 1.0, but that's clearly is not happening.
Here is the latex code, since I can't include images yet
(Here is the latex code, since I can't include images yet)
| Generally, the more obvious is the mistake, the more time it takes to find it.
This was verified here.
The mistake is simply here:
z[1] = out[i][0]*std::sin(w) + out[i][0]*std::cos(w);
It should be:
z[1] = out[i][0]*std::sin(w) + out[i][1]*std::cos(w);
Besides, I don't know why you didn't use N__ft = N, but I guess it is related the way fftw works.
|
70,389,604 | 70,564,531 | Bitmap fonts not rendering correctly for some characters | I am generating the bitmap font texture from here - https://snowb.org/
The font for "Name - wxyz" is rendering as below -
The code is very much similar to the one posted for this question - Bitmap font rendering issue, so I will only post my code for the quad and texture coordinate calculation for the characters (I am using orthographic projection with identity view matrix)-
// beginOffsetX and beginOffsetY is just some offset where I want the text to appear
// fontAtlasWidth and fontAtlasHeight is size of texture
// texData contains all the parameters that can be read from the font.txt generated from the same bitmap generator website (parameters are described later below)
float xAdvance = 0.0f;
fontVertices.resize(texData.size() * 4);
fontTexCoords.resize(texData.size() * 4);
for (unsigned int i = 0; i < texData.size(); i++)
{
float xcoordBegin = beginOffsetX + xAdvance;
float xcoordEnd = beginOffsetX + xAdvance + texData[i].width;
float ycoordBegin = beginOffsetY;
float ycoordEnd = beginOffsetY + texData[i].height;
fontVertices[4u * i + 0] = geometry_utils::vec3{ xcoordBegin, ycoordEnd, 0.0f };
fontVertices[4u * i + 1] = geometry_utils::vec3{ xcoordBegin, ycoordBegin, 0.0f };
fontVertices[4u * i + 2] = geometry_utils::vec3{ xcoordEnd, ycoordEnd, 0.0f };
fontVertices[4u * i + 3] = geometry_utils::vec3{ xcoordEnd, ycoordBegin, 0.0f };
float xtexcoordBegin = texData[i].x;
float xtexcoordEnd = texData[i].x + texData[i].width / fontAtlasWidth;
float ytexcoordBegin = texData[i].y;
float ytexcoordEnd = texData[i].y + texData[i].height / fontAtlasHeight;
fontTexCoords[4u * i + 0] = geometry_utils::vec2{ xtexcoordBegin, ytexcoordBegin };
fontTexCoords[4u * i + 1] = geometry_utils::vec2{ xtexcoordBegin, ytexcoordEnd };
fontTexCoords[4u * i + 2] = geometry_utils::vec2{ xtexcoordEnd, ytexcoordBegin };
fontTexCoords[4u * i + 3] = geometry_utils::vec2{ xtexcoordEnd, ytexcoordEnd };
xAdvance += texData[i].width;
}
Issue -
As you can see some of the fonts are not rendering correctly. Small case 'y' is appearing as capital 'Y', hyphen '-' is appearing as '_', and space ' ' is not appearing at all.
The font text file generated from https://snowb.org/ contains these parameters for every character from ascii 32 to 125, below is one example-
char id=33 x=331 y=52 width=14 height=42 xoffset=-1 yoffset=-1 xadvance=13 page=0 chnl=15
Out of these, as you can see in the above code, I am using only x,y, width, height and xAdvance. Attempting to use xOffset/fontAtlasWidth and yoffset/fontAtlasHeight in the texture coordinates did not fix these issues and also further messed up the other characters.
Could you please guide me as to what I need to modify in my calculations to get all the characters to render correctly?
Edit:
Adding the y-offset as this,
float xtexcoordBegin = texData[i].x;
float xtexcoordEnd = texData[i].x + texData[i].width / fontAtlasWidth ;
float ytexcoordBegin = texData[i].y - texData[i].yOffset / fontAtlasHeight;
float ytexcoordEnd = texData[i].y + texData[i].height / fontAtlasHeight;
results in image like this
This is if the yoffset is added instead -
| The thing that worked for me with the code I have added to the question was to modify the y vertex coordinate as such
float ycoordBegin = beginOffsetY - texData[i].height - texData[i].yOffset;
float ycoordEnd = beginOffsetY - texData[i].yOffset;
With this modification the text appears correctly as below -
|
70,389,630 | 70,389,631 | "LNK1104: cannot open file mclmcrrtd.lib" Error in Qt Creator | I generated *.dll dynamic-link library file by compiling the application I developed in MATLAB using MRC (MATLAB Runtime Compiler). I'm using the MSVC compiler and qmake toolset in the Qt Creator environment to distribute and/or use the procedures in the application I developed in MATLAB in the Windows OS environment. But I'm having trouble adding the dynamic-link libraries (for example mclmcrrt.lib, libmx.lib, libmex.lib, libmat.lib, libfixedpoint.lib, etc.) shared by the MATLAB Runtime Compiler to my project. When I build the project in the Qt Creator environment, I get the following error:
* LNK1104: cannot open file 'mclmcrrtd.lib'
* U1077: "\VS\Tools\MSVC\{Version}\bin\HostX86\x64\link.EXE": return code '0x450'
* U1077: "\VS\Tools\MSVC\{Version}\bin\HostX86\x64\nmake.exe": return code '0x2'
How do I solve this problem?
| 1. Definition of Error
I tested this bug by starting a similar project. When I compile the project in Qt Creator I got the following error:
LNK1104: cannot open file 'mclmcrrtd.lib'
2. Steps To Fix The Error
Follow the steps below to fix the problem:
I didn't add dependencies manually in QT Creator. I added a dynamic library by right-clicking on the project name and going to Add Library > External Library. I used the following settings in the External Library window in QT Creator, I added files and directories using these settings:
* Linkage: Dynamic
* Mac: Library
* [✔] Library inside "debug" or "release" subfolder
* [ ] Add "d" suffix for debug version
* [ ] Remove "d" suffix for release version
I examined how the window opened in the second step transfers information about the dynamic library to the *.pro file. I selected the mclmcrrt.lib file in the ~/lib/win64/ directory and clicked the Next button in the External Library window on Qt Creator. I saw that the mclmcrrt.lib library was named differently in Win32, Win64 and Unix systems when imported to Qt Creator in this way (like lmclmcrrt, lmclmcrrtd, lmclmcrrt).
win32:CONFIG(release, debug|release): LIBS += -L$$PWD/'../../../../Program Files/MATLAB/R2018B/extern/lib/win64/microsoft/' -lmclmcrrt
else:win32:CONFIG(release, debug|release): LIBS += -L$$PWD/'../../../../Program Files/MATLAB/R2018B/extern/lib/win64/microsoft/' -lmclmcrrtd
else:unix: LIBS += -L$$PWD/'../../../../Program Files/MATLAB/R2018B/extern/lib/win64/microsoft/' -lmclmcrrt
INCLUDEPATH += $$PWD/'../../../../Program Files/MATLAB/R2018B/extern/lib/win64/microsoft'
DEPENDPATH += $$PWD/'../../../../Program Files/MATLAB/R2018B/extern/lib/win64/microsoft'
This is how I learned how to properly import files and directories into my project file. I added all the requirements manually myself; I didn't use the interface to avoid file and directory confusion.
win32:CONFIG(release, debug|release): LIBS += -L$$PWD/'../../../../Program Files/MATLAB/R2018B/extern/lib/win64/microsoft/' -lmclmcrrt
else:win32:CONFIG(release, debug|release): LIBS += -L$$PWD/'../../../../Program Files/MATLAB/R2018B/extern/lib/win64/microsoft/' -lmclmcrrtd
else:unix: LIBS += -L$$PWD/'../../../../Program Files/MATLAB/R2018B/extern/lib/win64/microsoft/' -lmclmcrrt
INCLUDEPATH += $$PWD/'../../../../Program Files/MATLAB/R2018B/extern/include'
INCLUDEPATH += $$PWD/'../../../../Program Files/MATLAB/R2018B/extern/include/win64'
INCLUDEPATH += $$PWD/'../../../../Program Files/MATLAB/R2018B/extern/lib/win64/microsoft'
DEPENDPATH += $$PWD/'../../../../Program Files/MATLAB/R2018B/extern/lib/win64/microsoft'
When using the Build > Rebuild All Projects command in Qt Creator to compile the project, I got the error LNK1104: Cannot open file 'mclmcrrtd.lib' again. I found out that this is because the old MATLAB Compiler Runtime (MCR) is only suitable for x86 architecture. For this reason, I discovered that many sample QT-Matlab Compiler Runtime projects on the internet use the win32 tag in the descriptions in *.pro files. However, I thought it would not be correct to use the win32 tag because of the phrase HostX64\x64 when called from the C:\Program Files(x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\{Version}\bin\HostX64\x64\cl.exe directory of the current MSVC. The final configuration in the *.pro file containing the relevant code block is as follows and successfully
LIBS += -L$$PWD/'../../../../Program Files/MATLAB/R2018B/extern/lib/win64/microsoft/' -lmclmcrrt
INCLUDEPATH += $$PWD/'../../../../Program Files/MATLAB/R2018B/extern/include'
INCLUDEPATH += $$PWD/'../../../../Program Files/MATLAB/R2018B/extern/include/win64'
INCLUDEPATH += $$PWD/'../../../../Program Files/MATLAB/R2018B/extern/lib/win64/microsoft'
DEPENDPATH += $$PWD/'../../../../Program Files/MATLAB/R2018B/extern/lib/win64/microsoft'
3. Resources
MCR - Install and Configure MATLAB Compiler Runtime
MSVC - Linker Tools Error LNK1104
Qt Creator - Adding Libraries to Projects
Qt Creator - Creating Project Files (QMake)
|
70,389,922 | 70,390,793 | Content of class method determined by the template value | By using c++ 14 or c++11, do we have an elegant approach to do the following task? Number of members and type of operations are determined by the template input value 'count'
template<int count>
class show{
public:
run(){
if (count == 1){
int x;
} else if(count ==2){
int x, y;
}else if(count ==3){
int x, y, z;
}
if (count == 1){
printf("res: %d \n", x);
} else if(count ==2){
printf("res: %d \n", x+y);
}else if(count ==3){
printf("res: %d \n", x+y+z);
}
}
};
Update: can we use partial specialization or something related to the template in this case?
| Yes, you can use specialization:
template<int count>
class show;
template<>
class show<1>{
int x;
public:
show(int _x):x{_x}{}
void run(){
std::cout << "val of x " << x << std::endl;
}
};
template<>
class show<2>{
int x,y;
public:
show(int _x, int _y):x{_x}, y{_y}{}
void run(){
std::cout << "add " << x+y << std::endl;
}
};
But you also can have it more generic:
template <int count>
class simply
{
std::array<int, count> arr;
public:
template < typename ... T >
simply( T ... in ): arr{ in... } {}
void run()
{
std::cout << [this](){ int sum=0; for( auto el: arr ){ sum+=el; } return sum; }() << std::endl;
}
};
To use all the stuff above:
int main() {
show<1> s1(10);
show<2> s2(100,200);
s1.run();
s2.run();
simply<4> si( 1,2,3,4 );
si.run();
}
Remarks:
You should add some more stuff to simply to check that all parameters of type int with sfinae or static_assert. But his is another question ...
|
70,389,931 | 70,395,999 | Using OpenDDS with Qt6 | Can someone guide me on how to use OpenDDS with Qt6? I need to make a Chatroom application on Qt with the help of OpenDDS and I can't find any learning material for that.
| OpenDDS has a demo used to demonstrate interoperability with other DDS implementations that uses Qt that could serve as an example. It's Qt 5 though, we haven't updated it to Qt 6 yet. There's also some more information about OpenDDS and Qt listed here.
|
70,390,677 | 70,391,192 | Adding Decimal Numbers | Adding decimal numbers were my exam question.
Our teacher said the right code is this (Look below), but it doesn't work what's the problem
This is the question: 9/10-11/12+13/14-15/16+....49/50 Write a c++ program to calculate this question
Here is the code:
#include <iostream>
using namespace std;
int main()
{
double x;
int p = 1;
double s = 0;
for (x = 9.0; x < 49.0; x + 2.0)
{
s = s + x / (x + 1) * p;
}
p = -p;
cout << "Total: " << s << endl;
}
| First of all, your code's first bug is that in the for-loop, you have typed x + 2.0 which is not an assignment statement. So it really doesn't add 2 to the value of x. Instead, you have to write x += 2.0. And the second bug is that you have to place p = -p; inside the loop. Otherwise, it won't have any effects.
Now by fixing these two flaws it gives the result as Total: -0.0447071 which is not correct and it should be 0.935293. And the reason for that is that your for-loop iterates 19 times instead of 20 because you have forgotten to type <= instead of < in x < 49.0; and thus x is incremented up until 47.0 and not 49.0 so your loop doesn't add the last number to the sum.
Well, this may be what you want:
#include <iostream>
int main( )
{
int sign { 1 };
double sum { };
for ( std::size_t x = 9; x <= 49; x += 2 )
{
std::clog << "sum == " << sum << '\n';
// here you have to cast both x and x+1 to double
sum += static_cast<double>( x ) / static_cast<double>( x + 1 ) * sign;
sign = -sign;
}
std::cout << "\nTotal: " << sum << '\n';
}
Also, don't use anything except integral types for the initialization variable of a for-loop. For example, use std::size_t or int or int64_t, etc. based on your circumstances.
The output:
sum == 0
sum == 0.9
sum == -0.0166667
sum == 0.911905
sum == -0.0255952
sum == 0.918849
sum == -0.0311508
sum == 0.923395
sum == -0.0349387
sum == 0.9266
sum == -0.0376859
sum == 0.928981
sum == -0.0397693
sum == 0.930819
sum == -0.0414032
sum == 0.932281
sum == -0.042719
sum == 0.933471
sum == -0.0438013
sum == 0.93446
sum == -0.0447071
Total: 0.935293
As you can see, in this case after 20 iterations (because (49-9)/2 == 20), the total/sum will be 0.935293 so I hope this is what your teacher had in his/her mind.
|
70,390,882 | 70,391,022 | is_trivially_copyable behaves differently between the constructor I implemented and the default | There is a demonstrative code for std::is_trivially_copyable
https://en.cppreference.com/w/cpp/types/is_trivially_copyable
void test()
{
struct A {
int m;
A(const A& o):m(o.m){}
};
struct D {
int m;
D(D const&) = default; // -> trivially copyable
D(int x) : m(x + 1) {}
};
std::cout << std::is_trivially_copyable<A>::value << '\n';
std::cout << std::is_trivially_copyable<D>::value << '\n';
}
A is not trivially copyable, D does. I implement A's copy constructor with the default behavior. What does cause the difference?
| This is how it is defined in c++:
https://en.cppreference.com/w/cpp/language/copy_constructor#Trivial_copy_constructor
Trivial copy constructor
The copy constructor for class T is trivial if all of the following are true:
it is not user-provided (that is, it is implicitly-defined or
defaulted) ;
T has no virtual member functions;
T has no virtual base classes;
the copy constructor selected for every direct base of T is trivial;
the copy constructor selected for every non-static class type (or array of class type) member of T is trivial;
A trivial copy constructor for a non-union class effectively copies every scalar subobject (including, recursively, subobject of subobjects and so forth) of the argument and performs no other action. However, padding bytes need not be copied, and even the object representations of the copied subobjects need not be the same as long as their values are identical.
TriviallyCopyable objects can be copied by copying their object representations manually, e.g. with std::memmove. All data types compatible with the C language (POD types) are trivially copyable.
|
70,391,370 | 70,391,958 | How to read from multiple lines in a file? | I am learning C++ and am having a bit of a hard time with files. This is a little exercise that I am trying to do. The program is meant to read from a file and set it to its proper variables. The text file is as so:
Adara Starr 94
David Starr 91
Sophia Starr 94
Maria Starr 91
Danielle DeFino 94
#include <fstream>
#include <iostream>
using namespace std;
const int MAXNAME = 20;
int main()
{
ifstream inData;
inData.open("grades.txt");
char name[MAXNAME + 1]; // holds student name
float average; // holds student average
inData.get(name, MAXNAME + 1);
while (inData)
{
inData >> average;
cout << name << "has an average of " << average << endl;
//I'm supposed to write something here
}
return 0;
}
When I try to run the code, only the first line is being read and displayed and then the program ends. More specifically, the output is
Adara Starr has an average of 94
Adara Starr has an average of 0
How do I read the next line from the txt file? I've also done while (inData >> average) in place of the inData condition but it also does the same thing minus the second "Adara Starr has an average of 0"
| I hope this helps:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
const int MAXNAME = 20;
int main() {
ifstream inData("input.txt");
string str = "";
while (!inData.eof()) {//use eof=END OF FILE
//getline(inData, str); use to take the hole row
/*can use string also
string firstName;
string lastName;
string avg;*/
char firstName[MAXNAME];
char lastName[MAXNAME];
float avg;
//you can read from a file like you read from console(cin)
inData >> firstName >> lastName >> avg;//split the row
cout << firstName << " " << lastName << " " << avg<<"\n";
}
inData.close();
return 0;
}
Output:
Adara Starr 94
David Starr 91
Sophia Starr 94
Maria Starr 91
Danielle DeFino 94
|
70,392,385 | 70,392,576 | Having trouble printing a series | Here's the problem statement for what I'm supposed to do:
Write a program to print the following series up to the term input by user.
0, 1, 1, 2, 3, 5, 8, 13, ….
Where 0 is 1st term and 13 is 8th term.
Hint: 0, 1
0+1 = 1
0, 1, 1
1+1 = 2
0, 1, 1, 2
And here's my code:
int prev_i = 0;
cout << "Enter a number: " << endl;
cin >> number;
for (i = 0; i <= number; i++)
{
cout << prev_i + i << " ,";
prev_i = i;
}
I do get what is wrong with my code though. It adds i to prev_i then prev_i is set to i. So in the next iteration when i is 1 thats i + prev_i = 1 so now prev_i = 1 and here's the problem i is 2 now so i + prev_i = 3. And I really can't seem to figure out how to get 1 instead of 3 as the output here and so on.
Oh and don't worry about i not declared properly. I just didn't copy that part.
pls help!
| You're trying to generate a fibonacci sequence (starts with two terms (0,1), and each subsequent term is the addition of the prior two). Therefore, i should not be part of the calculation; it is only there to control looping.
A simple generation of the first ten numbers in the sequence is simply this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a=0, b=1;
for (int i=0; i<10; ++i)
{
printf("%d ", a);
int c = a+b;
a = b;
b = c;
}
fputc('\n', stdout);
return EXIT_SUCCESS;
}
That's it. The code above will generate the following:
0 1 1 2 3 5 8 13 21 34
I leave applying the above logic to generate whatever your final requirements are up to you, but that's how the sequence is iteratively generated.
PS: Apologies in advance for writing C code. I totally spaced the language tag, but nonetheless the algorithm is the same.
|
70,392,665 | 70,392,751 | Why can't I access a std::vector<std::pair<std::string, std::string>> through vec[i].first()? | I am attempting to print data from a std::vector<std::pair<std::string,std::string>> via a for loop. MSVC says that I can't call make a call through this vector. I tried it with std::vector<std::pair<int, int>> as well and got the same error. I tried iterating with a for loop on a std::vector<int> and it worked fine. I haven't tried on another compiler.
Sample code
std::vector<std::pair<std::string, std::string>> header_data = get_png_header_data(file_contents);
for (unsigned int i = 0; i < header_data.size(); i++)
{
std::cout << header_data[i].first(); //throws an error on this line "call of an object of a class type without an appropriate operator() or conversion functions to pointer-to-function type
}
I would appreciate an alternative way to access my vector or another storage type that I could use.
Thanks :)
| Your std::pair is basically (in a manner of speaking):
struct std::pair {
std::string first;
std::string second;
};
That's what std::pairs are. first and second are ordinary class members, not methods/functions. Now you can easily see what's happening: .first() attempts to call first's () operator overload. Obviously, std::strings have no such overloads. That's what your C++ compiler's error message is telling you. If you reread your compiler's error message it now becomes crystal clear.
You obviously meant to write std::cout << header_data[i].first;.
|
70,393,722 | 70,394,102 | Can we use two different mutex when waiting on same conditional variable? | Consider below scenario:
Thread 1
mutexLk1_
gcondVar_.wait(mutexLk1);
Thread 2
mutexLk2_
gcondVar_.wait(mutexLk2);
Thread 3
condVar_
gcondVar_.notify_all();
What I observe is that notify_all() does not wake up both the threads but just one on the two. If i were to replace mutexLk2 with mutexLk1. I get a functional code.
To reproduce the issue consider below modified example from cppref
#include <iostream>
#include <condition_variable>
#include <thread>
#include <chrono>
std::condition_variable cv;
std::mutex cv_m1;
std::mutex cv_m; // This mutex is used for three purposes:
// 1) to synchronize accesses to i
// 2) to synchronize accesses to std::cerr
// 3) for the condition variable cv
int i = 0;
void waits1()
{
std::unique_lock<std::mutex> lk(cv_m);
std::cerr << "Waiting... \n";
cv.wait(lk, []{return i == 1;});
std::cerr << "...finished waiting. waits1 i == 1\n";
}
void waits()
{
std::unique_lock<std::mutex> lk(cv_m1);
std::cerr << "Waiting... \n";
cv.wait(lk, []{return i == 1;});
std::cerr << "...finished waiting. i == 1\n";
}
void signals()
{
std::this_thread::sleep_for(std::chrono::seconds(1));
{
std::lock_guard<std::mutex> lk(cv_m);
std::cerr << "Notifying...\n";
}
cv.notify_all();
std::this_thread::sleep_for(std::chrono::seconds(1));
{
std::lock_guard<std::mutex> lk(cv_m);
i = 1;
std::cerr << "Notifying again...\n";
}
cv.notify_all();
}
int main()
{
std::thread t1(waits), t2(waits1), t3(waits), t4(signals);
t1.join();
t2.join();
t3.join();
t4.join();
}
Compilation command
g++ --std=c++17 t.cpp -lpthread
Interesting thing here is that the above code gets stuck on either of the waits (sometimes waits1 runs sometime waits) on a centos 7.9 System with g++ 9.3 version (same behavior with g++ 10 on this system) but with a ubuntu 18.04 system (with g++ 9.4) this works without any issues
Any idea what is the expected behaviour or ideal practice to follow? Because in my used case I need two different mutex to protect different data structures but the trigger is from same conditional variable.
Thanks
| It seems you violate standad:
33.5.3 Class condition_variable [thread.condition.condvar]
void wait(unique_lock& lock);
Requires: lock.owns_lock() is true and lock.mutex() is locked by the
calling thread, and either
(9.1) — no other thread is waiting on this condition_variable object
or
(9.2) — lock.mutex() returns the same value for each of the lock
arguments supplied by all concurrently waiting (via wait, wait_for, or
wait_until) threads.
Cleary two threads are waiting and lock.mutex() does not return same.
|
70,394,305 | 70,394,899 | Sort function is giving error in C++ code of merge sort | #include <iostream>
using namespace std;
// merging two sorted array
void merge1(int a[], int b[], int m, int n)
{
int c[m + n];
for (int i = 0; i < m; i++)
c[i] = a[i];
for (int i = 0; i < n; i++)
c[m + i] = b[i];
sort(c, c + m + n);
for (int i = 0; i < (m + n); i++)
cout << c[i] << " ";
}
int main()
{
int a[] = {10, 15, 20, 20};
int b[] = {1, 12};
merge1(a, b, 4, 2);
}
Error :
error: 'sort' was not declared in this scope; did you mean 'qsort'?
21 | sort(c, c + m + n);
| ^~~~
| qsort
| The program works but on higher versions of clang and gcc, which implies a higher version of the standard being required. This problem can be reproduced if you drop the version of the compiler being used. If you drop the compiler version, you will need to include <algorithm> and the program will work fine.
Take a look.
For gcc @8.3 - https://wandbox.org/permlink/2qsicDDWFvRHoWMa will throw an error
For gcc@9.1 - https://wandbox.org/permlink/xoqhbDdoVAyNP6hq works fine.
For gcc@7.2 - https://wandbox.org/permlink/rFekziKv36YoqJua will work okay too.
My best guess is either the compiler somehow recognizes the function at compile-time, or the function is visible in higher C++ standard versions via some hidden includes in the <iostream> or headers that it includes.
You can see a similar story on clang++ side too.
Notes
You need to check the version of the compiler you are using and in general, observe if the function you are using is supported by the standard you are running.
Also, please include proper header files when you run something like this.
Also, please for crying out loud stop doing using namespace std;. Please.
|
70,394,783 | 70,394,837 | C++11 Check if at least one element in vector is not in another vector | I wrote the following code in order to check if at least one element in vector is not in another vector.
There are no duplicates in the vectors. Only unique elements
Is there a more elegant way to do it by using the stl?
// Online C++ compiler to run C++ program online
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool areVectorsDifferent(vector<int> &a, vector<int> &b){
if(a.size() != b.size()){
return true;
}
std::sort(a.begin(),a.end());
std::sort(b.begin(),b.end());
for(int i = 0; i < a.size();i++){
if(a[i] != b[i]) {
return true;
}
}
return false;
}
int main() {
bool isDifferent = false;
vector<int> a = {1,2,3,5};
vector<int> b = {4,3,2,1};
std::cout << areVectorsDifferent(a,b) << std::endl;
return 0;
}
| It depends on your definition of "different", but:
bool areVectorsDifferent(const vector<int> &a, const vector<int> &b){
return a.size() != b.size()
|| std::set<int>{a.cbegin(), a.cend()} != std::set<int>{b.cbegin(), b.cend()};
}
|
70,394,812 | 70,394,940 | Sending user inputted commands to an arduino in c++ using system() on a linux terminal | Using a c++ program i can successfully send commands to an arduino. The code uses the command:
system("$echo [command] > dev/ttyACM0");
Currently i must manually input the commands into this space, I was wondering if it's possible for a user to input the command, and for it to then be added to the string within system()?
| This is an approximation of what I think you want:
#include <fstream>
#include <iostream>
#include <string>
int main() {
std::string command;
if(std::getline(std::cin, command)) { // read user input
std::ofstream ard("/dev/ttyACM0"); // open the device
if(ard) {
ard << command << '\n'; // send the command
}
} // here `ard` goes out of scope and is closed automatically
}
Note that you do not need the unsafe system() command at all here. Just open the device and send the string directly.
|
70,395,502 | 70,396,041 | Erasing duplicates from two vectors using only iterators | How can I delete duplicates from two vectors of strings (delete them from both vectors) using only iterators?
I suppose it doesn't work because if values are already deleted they can't be compared, but I can not think of any other solution, only if I had one function to erase both elements at the same time.
void obrisiIsteRijeci(std::vector<std::string>& v1, std::vector<std::string>& v2){
for(auto it = v1.begin(); it != v1.end(); it++){
auto it1 = it;
for(auto it2 = v2.begin(); it2 != v2.end(); it2++){
if((*(it2) == *(it1)) && (*(it1) == *(it2))){
v1.erase(it1);
v2.erase(it2);
}
}
}
}
| I can suggest the following approach. In the demonstration program below I am using vectors of the type std::vector<int> for simplicity.
#include <iostream>
#include <vector>
#include <iterator>
$include <algorithm>
int main()
{
std::vector<int> v1 = { 1, 2, 1, 2, 3, 4 }, v2 = { 1, 2, 3, 5 };
for (auto first = std::begin( v1 ); first != std::end( v1 ); )
{
auto it = std::find( std::begin( v2 ), std::end( v2 ), *first );
if (it != std::end( v2 ))
{
v2.erase( std::remove( it, std::end( v2 ), *first ), std::end( v2 ) );
auto value = *first;
auto offset = std::distance( std::begin( v1 ), first );
v1.erase( std::remove( first, std::end( v1 ), value ), std::end( v1 ) );
first = std::next( std::begin( v1 ), offset );
}
else
{
++first;
}
}
for (const auto &item : v1)
{
std::cout << item << ' ';
}
std::cout << '\n';
for (const auto &item : v2)
{
std::cout << item << ' ';
}
std::cout << '\n';
}
The program output is
4
5
|
70,395,538 | 70,395,648 | Illegal hardware instruction on a c program compiled on Mac | I am getting an illegal hardware instruction error when compiled on mac. Appreciate any pointers.
#include<iostream>
using namespace std;
int * fun(int * x)
{
return x;
}
int main()
{
int * x;
*x=10;
cout << fun(x);
return 0;
}
| Pointers are just pointers. In your code there is no integer that you could assign a value to.
This
int * x;
Declares x to be a pointer to int. It is uninitialized. It does not point anywhere. In the next line:
*x=10;
You are saying: Go to the memory that x points to and assign a 10 to that int. See the problem? There is no int where x points to, because x doesnt point anywhere. Your code has undefined behavior. Output could be anything.
If you want to assign 10 to an int you need an int first. For example:
#include<iostream>
using namespace std;
int * fun(int * x)
{
return x;
}
int main()
{
int y = 0;
int * x = &y;
*x=10;
cout << fun(x);
return 0;
}
This assigns 10 to y. The cout is still printing the value of x, which is the adress of y. It does not print the value of y. Not sure what you actually wanted.
|
70,396,126 | 70,409,760 | C++ How to set pixel colors | I created a code which change a certain pixels on the screen but when i want to change more pixels the performance of program will slow down.
You will see glitches and it's not that pretty as it should be.
Question:
How can i inprove performance of the code.
If I want to change more pixel or eventually all pixels on the screen.
I thought about using SETBITMAPBITS but I'm not sure how to it works. I have no experience with it.
Is there any other solution?
Example of my code: < Console app >
#define _WIN32_WINNT 0x601
#include <windows.h>
#include <stdio.h>
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
HDC dng = GetDC(NULL);
while (true)
for (int i = 0; i <= 200; i++)
for (int j = 0; j <= 500; j++)
SetPixel(dng, i, j, RGB(0, 0, 255));
ReleaseDC(NULL, dng);
getchar();
}
| If I understand correctly, you are trying to draw outside a window.
Every time you SetPixel you send a WM_PAINT message, which repaints the whole window.
That dramatically slows down your program. What you should do is use GDI, GDI+ or Direct2D to create a bitmap or a rectangle to then draw it at once.
Drawing outside a window is never a good idea. You have no control on what you just drew, and it will disappear when something interrupts it.
If you want a blue block without a title bar, create a layered window, then create a rectangle and draw it.
Microsoft's documentation might not be a tutorial, but it is informative.
Here is the Direct2D documentation:
https://learn.microsoft.com/en-us/windows/win32/direct2d/getting-started-with-direct2d
And here is how to create a layered window:
https://learn.microsoft.com/en-us/windows/win32/winmsg/window-features#layered-windows
Edit:
Comment said that SetPixel doesn't send WM_PAINT. What I am saying is SetPixel repaints the window.
|
70,396,216 | 70,396,562 | Trying to understand cause of increased compile time going from C++11 to C++14 | Migrating from C++11 to C++14, I have a source file that usually compiles in ~20s in C++11 mode, but when compiling the same file in C++14 mode the compile time increase to ~340s. That's an increase of about 17 times. The size of the generated object code doubles.
So the clarify my question, I'm trying to understand both what in the code and why the compilers takes that much longer for the same code by changing the -std=c++11/c++14 flag for g++.
To make a fair comparison ran the pre-processor over the code (in C++11 mode) and compiled the output with both the C++11 and C++14 flags. E.g.,
g++ -E -std=c++11 -g -O2 -o spaghetti.E spaghetti.cpp
g++ -c -std=c++11 -g -O2 -o spaghetti-11.o -x c++ spaghetti.E
g++ -c -std=c++14 -g -O2 -o spaghetti-14.o -x c++ spaghetti.E
The file in question does have lots of fixed size arrays of objects in template form like
template<typename T, std::size_t N>
struct Object {
std::array<T,N> storage{};
std::vector<T> counters;
};
Symbols involving Object do double when compiled with C++14 over C++11 (among others).
So, what motivates the compiler to take 17 times longer to compile the same file?
And what should change to reduce this?
I should note that if I change the Object implementation
template<typename T, std::size_t N>
struct Object {
std::vector<T> storage{}; // was std::array above, N used in other members
std::vector<T> counters;
};
It will compile quickly under both C++11 and C++14.
| Seems like this is known bug in gcc but isn't getting much traction.
Did you try to switch over to clang++?
PS from comment: Removing the {} behind the storage{} and manually initializing works.
|
70,396,339 | 70,396,635 | Shortest path algorithm in graph for queries | I have a weighted undirected Graph. Its vertices are part of two sets - S and T. Firstly, the edges are entered. Then it's specified which vertices are part of the T set (the rest are part of the S set). Then q queries follow. For every query(consists of a source vertex), the program must print the shortest path between the specified source vertex and any vertex of the set T.
I implemented the program using Dijkstra's algorithm. I call it for each query on the source vertex(dijkstra returns the distance between source and all other vertices) and then return the minimum of these numbers.
const int M = 1000000;
std::unordered_set<int> T;
class Node {
public:
int endVertex; // stores the second vertex of the edge
int weight; // stores the weight required, it is the weight of the edge
Node(int end, int weight) {
this->endVertex = end;
this->weight = weight;
}
};
struct NodeComparator {
bool operator()(const Node &first, const Node &second) {
return first.weight > second.weight;
}
};
class Graph {
private:
std::unordered_map<int, std::vector<Node>> adjacencyList; // it's a vector because there may be repeated Nodes
int numberOfVertices;
std::vector<int> dijkstra(int source) {
std::priority_queue<Node, std::vector<Node>, NodeComparator> heap;
std::vector<int> distances(this->numberOfVertices, M);
std::unordered_set<int> visited;
// distance source->source is 0
distances[source] = 0;
heap.emplace(source, 0);
while (!heap.empty()) {
int vertex = heap.top().endVertex;
heap.pop();
// to avoid repetition
if (visited.find(vertex) != visited.end()) {
continue;
}
for (Node node: adjacencyList[vertex]) {
// relaxation
if (distances[node.endVertex] > distances[vertex] + node.weight) {
distances[node.endVertex] = distances[vertex] + node.weight;
heap.emplace(node.endVertex, distances[node.endVertex]);
}
}
// mark as visited to avoid going through the same vertex again
visited.insert(vertex);
}
return distances;
}
int answer(int source) {
std::vector<int> distances = this->dijkstra(source);
std::set<int> answer;
for (int i: T) {
answer.insert(distances[i]);
}
return *answer.begin();
}
// other methods
};
// main()
However, my solution does not pass half the tests due to timeout. I replaced my dijkstra method with a Floyd-Warshall algorithm, which directly overrides the starting adjacency matrix, because I thought that the method would be called only once, and then each query would just find the minimum element in the source line of the matrix. This time the timeouts are even worse.
Is there a specific algorithm for efficient queries on shortest path? How can I improve my algorithm?
| You can reverse all edges and find the shortest path from the set of T (run Dijkstra from all T vertices together) to some vertex S. And precalculate all distances to each S and answer to query in O(1).
|
70,396,570 | 70,398,951 | mismatched types 'std::chrono::_V2::steady_clock' and 'std::chrono::_V2::system_clock' | I'm trying to build my program in mingw64 (GCC v11.2). I have the following struct:
In a header file:
struct Timer
{
std::chrono::time_point< std::chrono::steady_clock > start;
std::chrono::time_point< std::chrono::steady_clock > end;
Timer( );
~Timer( );
};
In a source file:
util::Timer::Timer( )
: start( std::chrono::high_resolution_clock::now( ) )
{
}
util::Timer::~Timer( )
{
end = std::chrono::high_resolution_clock::now( );
std::chrono::duration< double, std::milli > duration_ms { end - start };
std::clog << "\nTimer took " << duration_ms.count( ) << " ms\n";
}
But this happens:
error: no matching function for call to 'std::chrono::time_point<std::chrono::_V2::steady_clock, std::chrono::duration<long long int, std::ratio<1, 1000000000> > >::time_point(std::chrono::_V2::system_clock::time_point)'
8 | : start( std::chrono::high_resolution_clock::now( ) )
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from pch.h:23:
c:\mingw64\include\c++\11.2.0\chrono:871:21: note: candidate: 'template<class _Dur2, class> constexpr std::chrono::time_point<_Clock, _Dur>::time_point(const std::chrono::time_point<_Clock, _Dur2>&) [with _Dur2 = _Dur2; <template-parameter-2-2> = <template-parameter-1-2>; _Clock = std::chrono::_V2::steady_clock; _Dur = std::chrono::duration<long long int, std::ratio<1, 1000000000> >]'
871 | constexpr time_point(const time_point<clock, _Dur2>& __t)
| ^~~~~~~~~~
c:\mingw64\include\c++\11.2.0\chrono:871:21: note: template argument deduction/substitution failed:
Util.cpp:8:3: note: mismatched types 'std::chrono::_V2::steady_clock' and 'std::chrono::_V2::system_clock'
8 | : start( std::chrono::high_resolution_clock::now( ) )
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Why is this happening? How to fix it?
| Thanks to the information provided in the comments, I came up with the following solution:
In the header file:
struct Timer
{
std::chrono::time_point< std::chrono::steady_clock > start;
std::chrono::time_point< std::chrono::steady_clock > end;
Timer( );
~Timer( );
};
In the source file:
util::Timer::Timer( )
: start( std::chrono::steady_clock::now( ) )
{
}
util::Timer::~Timer( )
{
end = std::chrono::steady_clock::now( );
std::clog << "\nTimer took " << std::chrono::duration< double, std::milli >( end - start ).count( ) << " ms\n";
}
So in short, I switched from std::chrono::high_resolution_clock::now( ) to std::chrono::steady_clock::now( ) because high_resolution_clock has different implementations on different compilers according to high_resolution_clock. On some of them it returns std::chrono::time_point<std::chrono::steady_clock> and in some others it returns std::chrono::time_point<std::chrono::system_clock>. And that caused problems for me.
A note from cppreference:
Notes
The high_resolution_clock is not implemented consistently across different standard library implementations, and its use should be avoided. It is often just an alias for std::chrono::steady_clock or std::chrono::system_clock, but which one it is depends on the library or configuration. When it is a system_clock, it is not monotonic (e.g., the time can go backwards). For example, for gcc's libstdc++ it is system_clock, for MSVC it is steady_clock, and for clang's libc++ it depends on configuration.
Generally one should just use std::chrono::steady_clock or std::chrono::system_clock directly instead of std::chrono::high_resolution_clock: use steady_clock for duration measurements, and system_clock for wall-clock time.
|
70,397,103 | 70,397,466 | unable to compile googletest in eclipse | I am trying to compile googletest (git clone https://github.com/google/googletest.git -b release-1.11.0) but keep getting 1000+ linker errors.
I am running windows 10, eclipse CDT (latest), mingw (latest) gcc. I created an eclipse c++ project (executable, empty project).
added include paths to:
googletest
googletest/includes
googlemock
googlemock/includes
added source location to:
googletest/src
googlemock/src
All is compiled without problems, but linking fails with 1000+ errors. Eg.
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe:
googletest\gtest.o: in function `testing::IsNotSubstring(char const*, char const*, wchar_t const*, wchar_t const*)':
C:\dev\unode\eclipse\unit_tests\Debug/../../googletest/googletest/src/gtest.cc:1821: multiple definition of `testing::IsNotSubstring(char const*, char const*, wchar_t const*, wchar_t const*)';
googletest\gtest-all.o:C:/dev/unode/eclipse/googletest/googletest/src/gtest.cc:1821: first defined here
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe:
googletest\gtest.o: in function `testing::IsSubstring(char const*, char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)':
C:\dev\unode\eclipse\unit_tests\Debug/../../googletest/googletest/src/gtest.cc:1827: multiple definition of `testing::IsSubstring(char const*, char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)';
googletest\gtest-all.o:C:/dev/unode/eclipse/googletest/googletest/src/gtest.cc:1827: first defined here
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe:
googletest\gtest.o: in function `testing::IsNotSubstring(char const*, char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)':
I am reading googletests readme.md to figure out what I am doing wrong but getting nowhere. Some help would be greatly appreciated
| Ah, there is a file
googletest/src/gtest-all.cc
which includes all source files. so all source files are compiled twice, deleting this file solves my problem
|
70,397,158 | 70,397,495 | Whats the difference between reference to an array and array as a parameters in functions? | What is the difference between functions, which have reference to an array:
// reference to array
void f_(char (&t)[5]) {
auto t2 = t;
}
and simply array:
// just array
void f__(char t[5]) {
auto t2 = t;
}
as a parameters?
The calling code is:
char cArray[] = "TEST";
f_(cArray);
f__(cArray);
char (&rcArr)[5] = cArray;
f_(rcArr);
f__(rcArr);
In both cases t2 is char*, but in first function my VS2019 is showing that t inside function has type char(&t)[] and t inside second function has type char*.
So after all, is there any practical difference between those functions?
| You can specify a complete array type parameter as for example
void f( int ( &a )[N] );
and within the function you will know the number of elements in the passed array.
When the function is declared like
void f( int a[] );
then the compiler adjusts the function declaration like
void f( int *a );
and you are unable to determine the number of elements in the passed array. So you need to specify a second parameter like
void f( int *a, size_t n );
Also functions with a referenced array parameter type may be overloaded. For example these two declarations
void f( int ( &a )[] );
and
void f( int ( &a )[2] );
declare two different functions.
And functions with a referenced array parameter type may be called with a braced list (provided that the corresponding parameter has the qualifier const) like for example
f( { 1, 2, 3 } );
Here is a demonstration program
#include <iostream>
void f( const int ( &a )[] )
{
std::cout << "void f( const int ( & )[] ) called.\n";
}
void f( const int ( &a )[2] )
{
std::cout << "void f( const int ( & )[2] ) called.\n";
}
void f( const int a[] )
{
std::cout << "void f( const int [] ) called.\n";
}
int main()
{
f( { 1, 2, 3 } );
}
The program output is
void f( const int ( & )[] ) called.
|
70,397,382 | 70,436,876 | Build asimple c++ static library of ios(for unity), but cannot find the .a file | As the title mentioned, using macos 12.
example.hpp
extern "C"{
int summation();
}
example.cpp
#include "example.hpp"
extern "C"{
int summation()
{
return 10;
}
}
Then I create an Xcode project->static lib, add example.hpp and example.cpp, configure the build phase to ios only. Click on build, the xcode tell me "build succeeded", but I cannot find any .a file, even in the Xcode/DerivedData/*.
This is the first time I try to build c++ plugin for unity on ios platform, please forgive my ignorance if any.
Edit : I search the .a file shown in the full path(Image 00) but cannot find anything, color of the plugin is red color, weird
| Solution is very simple, I create a new project, add the example.hpp and example.cpp into the project, set build target to ios only, click build, then the .a file is generated, I don't know why this happen, maybe some manipulation ruin the settings.
|
70,397,537 | 70,397,749 | VSCode and C++: Slightly lost with this error | I use the sample helloworld program and get syntax errors that make no sense to me. The strange part is that the program runs just fine, but the red squiggles in the code bother me and I'd like to understand why those are happening.
Code
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> msg {"Hello", "C++", "World", "from", "VS Code", "and the C++ extension!"};
for (const string& word : msg)
{
cout << word << " ";
}
cout << endl;
}
And this is the tasks.json file
{
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "clang++ build active file",
"command": "/usr/bin/clang++",
"args": [
"-std=c++17",
"-stdlib=libc++",
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
One of the underlined errors is the space between msg and the brackets:
no instance of constructor "std::__1::vector<_Tp, _Allocator>::vector [with _Tp=std::__1::string, _Allocator=std::__1::allocator<std::__1::string>]" matches the argument list -- argument types are: (const char [6], const char [4], const char [6], const char [5], const char [8], const char [23])
The next is at the colon in the for loop:
reference variable "word" requires an initializer
And the last one is the closing parenthesis of the for loop (after msg):
expected an expression
What's causing these errors, and how is the program still running? (I should mention that I'm not very familiar with C++, but it would be great to know the reason for these and whether I should be concerned about them)
| Did you configure your c++ VS Code extension?
For example:
{
"configurations": [
{
"name": "Mac",
"includePath": ["${workspaceFolder}/**"],
"defines": [],
"macFrameworkPath": [
"/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks"
],
"compilerPath": "/usr/bin/clang",
"cStandard": "c11",
"cppStandard": "c++17",
"intelliSenseMode": "clang-x64"
}
],
"version": 4
}
The important bits are: "cStandard": "c11",
"cppStandard": "c++17"
|
70,398,439 | 70,398,495 | How do i fix invalid operands of type double in C++? | Trying to do a Lab for school, but i keep getting this same error over and over again, and I am not sure what exactly it means.
First, here is my Code:
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
const double PI = acos(-1); // arccos(-1) produces the value pi
const double SEC_IN_DAY = 86400;
const double MU = 1.3274745e20;
const double R_EARTH = 1.496e11;
double ConvertSecondsToDays(double seconds){
return seconds / SEC_IN_DAY;
}
double CubedSum(double v1, double v2){
return pow(v1,v2);
}
double DirectTime (double rDestination){
return 2.0 * sqrt(fabs(rDestination - 1.496e11) / 10) / 86400.0;
}
double HohmannTime(double r1, double r2){
return PI * sqrt((CubedSum)/ 8.0 * MU);
}
int main() {
return 0;
}
The problem is at line 25, where it give me the following error:
"main.cpp: In function ‘double HohmannTime(double, double)’:
main.cpp:25:31: error: invalid operands of types ‘double(double, double)’ and ‘double’ to binary ‘operator/’
25 | return PI * sqrt((CubedSum)/ 8.0 * MU);
| ~~~~~~~~~~^ ~~~
| | |
| | double
| double(double, double)
I have looked up what this error means, but am not 100% sure what to do on fixing it.
| CubedSum is a function. So it seems you need to write
double HohmannTime(double r1, double r2){
return PI * sqrt((CubedSum( r1, r2 )/ 8.0 * MU);
}
instead of
double HohmannTime(double r1, double r2){
return PI * sqrt((CubedSum)/ 8.0 * MU);
}
where in this statement
return PI * sqrt((CubedSum)/ 8.0 * MU);
there is used the function pointer (due to implicit conversion of the function to a pointer) instead of the result of a function call.
|
70,398,573 | 70,398,753 | C++20 format sys_time with milliseconds precision | I'm trying to write a time string with a millisecond precision in MSVC 19.11 with /stc:c++latest.
With this i get 7 digits accuracy, what i don't want.
auto now = std::chrono::system_clock::now();
std::cout << std::format("{0:%d.%m.%Y %H:%M:%S}", now);
I tried std::cout << std::format("{0:%d.%m.%Y %H:%M:%S.3}", now); and some possibilities of std::setprecision(3) in vain.
Is there a solution to format it there or do i need to change "now"?
| auto now = std::chrono::floor<std::chrono::milliseconds>(std::chrono::system_clock::now());
std::cout << std::format("{0:%d.%m.%Y %H:%M:%S}", now);
or:
auto now = std::chrono::system_clock::now();
std::cout << std::format("{0:%d.%m.%Y %H:%M:%S}", std::chrono::floor<std::chrono::milliseconds>(now));
I.e. the precision of the output is controlled by the precision of the input.
Aside: You can also use %T in place of %H:%M:%S if desired.
|
70,398,668 | 71,787,312 | Is there a way to generate a clang-format file from a C++ code? | Supposing I have a C++ code already written and I want to generate a clang-format file from it, in order to note all the format settings of my code in this file, is there a way of doing it?
| Clang-Format Detector allows to generate clang-format file for the selected files. It also has a very convenient feature of seeing the result and adjusting it. Won't work for entire codebase though.
|
70,398,835 | 70,408,423 | Access is denied - UWP full trust process | I have a UWP C++/WinRT app and a C++/WinRT console application.
The UWP app uses the FullTrustProcessLauncher to launch the console application, and the console application is supposed to launch an arbitrary .exe file on the system, e.g. cmd.exe.
The whole code of the console application is here:
#include "pch.h"
#include <iostream>
int main()
{
winrt::init_apartment();
try
{
winrt::Windows::System::ProcessLauncher::RunToCompletionAsync(L"cmd.exe", L"").get();
}
catch (const winrt::hresult_error& err)
{
std::cout << winrt::to_string(err.message()) << std::endl;
}
std::cin.get();
}
and pch.h includes winrt/Windows.Foundation as well as winrt/Windows.System.h.
The UWP app can successfully launch the console application, but the console application seems unable to launch the .exe file, with E_ACCESSDENIED.
Am I wrong in thinking the console application should be able to launch arbitrary .exe files being a full-trust process?
If not, how can I fix the Access is denied error?
| Not all Windows Runtime APIs are supported in the context of Win32
'classic' desktop apps as they are intended only for use in the "AppContainer" context of the Universal Windows Platform (UWP).
For a Win32 desktop application, the best solution is to use ShellExecuteEx. This function handles User Account Control (UAC) elevation if needed where as CreateProcess will fail if the caller and the target aren't the same.
// Get working directory from executable path.
wchar_t szDirectory[MAX_PATH] = {};
wcscpy_s( szDirectory, szExePath );
PathRemoveFileSpec( szDirectory );
SHELLEXECUTEINFOW info = {};
info.cbSize = sizeof( info );
info.lpVerb = L"open";
info.fMask = SEE_MASK_FLAG_NO_UI | SEE_MASK_NOASYNC | SEE_MASK_NOCLOSEPROCESS;
info.lpFile = szExePath;
info.lpParameters = szExeArgs;
info.lpDirectory = szDirectory;
info.nShow = SW_SHOW;
if( !ShellExecuteExW( &info ) )
// Error
At this point you check wait on the info.hProcess handle or just to check if the target program has finished.
If you need the exit code, use:
DWORD exitCode;
GetExitCodeProcess( info.hProcess, &exitCode );
Be sure to not leak the handle by calling CloseHandle( info.hProcess );. If you don't care about waiting or exit code, just don't use SEE_MASK_NOCLOSEPROCESS. If you want it to be fully asynchronous, don't use SEE_MASK_NOASYNC.
|
70,399,226 | 70,577,833 | Linking C++ OpenCV to an app in Android Studio | I am integrating existing C++ code that uses OpenCV to an Android app, using Android studio. For this purpose, I have installed the package OpenCV-android-sdk and added it as a module to Android studio. I have also created a simple Kotlin app.
So far I have managed to integrate my C++ code into the project. After adding the paths to the OpenCV includes by means of an include_directories statement, the code compiles successfully.
My next step would be to link against the precompiled OpenCV library, to resolve the "undefined symbol" errors. I have no idea how to achieve this/where to specify it. I have tried to find resources on the web, but not two resources tell the same and the solutions seem overly complicated. I am lost in the jungle.
| I finally managed. Here comes the recipe (validated under Windows).
Make sure to download the OpenCV Android SDK and copy it somewhere.
The project must be created as a Native C++ app (Phone and tablet). A cpp folder is automatically created with a native-lib.cpp source file and a CMakeLists.txt.
Add the following lines to the CMakeLists file, after the project line:
set(OpenCV_DIR $ENV{OPENCV_ANDROID}/sdk/native/jni)
find_package(OpenCV REQUIRED)
You must define the environment variable OPENCV_ANDROID and make it point to the folder .../OpenCV-android-sdk that you copied. (Alternatively, you can hard-code the path in the set command.)
Then insert at the bottom
target_link_libraries(app_name ${OpenCV_LIBS})
where OpenCV_LIBS points to the folder .../OpenCV-android-sdk/sdk/native/libs, and app_name is the name you gave when creating your app.
Finally, cross fingers and build.
|
70,399,420 | 70,401,337 | Get enum key from unordered map by string value | I need a function that needs to check if the input (std::string) is unique and return its corresponding enum value.
I already have been able to implement this function with just a simple vector, which checks if the input is unique.
it should return enumE::HELLO.
I tried to adapt the code above for the vector to suit this function, but I am not really getting anywhere.
| Based on the description of your example, here is a quick implementation. Of course, the logic may not be entirely what you wrote, but I am sure you can tweak it.
Why would you iterate through the whole string if std::string has a std::string::find function which will find a substring for you?
Is it necessary to go through all the trouble you wrote above? Does the code need to be that dense and unreadable?
Feel free to play around with that function and implement your logic.
|
70,399,504 | 70,399,581 | Unsure why code is repeating certain outputs | I am doing this for a lab at school, however, in my code i get the correct outputs, but for some reason my inputs are repeating themselves. I am unsure why they are doing this, and have tried editing my code in several different ways in order to fix the problem, but to no avail.
here is my original code:
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
const double PI = acos(-1); // arccos(-1) produces the value pi
double DirectTime (double rDestination) {
return 2.0 * sqrt(fabs(rDestination - 1.496e11) / 10) / 86400.0;
}
const double MU = 1.3274745e20;
const int SEC_IN_DAY = 86400;
const double R_EARTH = 1.496e11;
const double R_VENUS = 1.08e11;
const double R_JUPITER = 7.778e11;
const double R_PLUTO = 5.91e12;
double ConvertSecondsToDays(double seconds);
double CubedSum(double v1, double v2);
double HohmannTime(double r1, double r2);
double ConvertSecondsToDays(double seconds) {
double days = 0;
days = seconds / SEC_IN_DAY;
cout << days;
return days;
}
double CubedSum(double v1, double v2) {
return pow(v1+v2,3);
}
double HohmannTime(double r1, double r2 = R_EARTH) {
return ConvertSecondsToDays( PI * sqrt(CubedSum(r1, r2)/ (8 * MU)));
}
int main() {
printf("%-10s%-15s%-s\n", "Planet", "Hohmann Time", "Direct Time");
printf("%-10s%-15.2f%-.2f\n", "Venus", HohmannTime(R_VENUS, R_EARTH), DirectTime(R_VENUS));
printf("%-10s%-15.2f%-.2f\n", "Jupiter", HohmannTime(R_JUPITER, R_EARTH), DirectTime(R_JUPITER));
printf("%-10s%-15.2f%-.2f\n", "Pluto", HohmannTime(R_PLUTO, R_EARTH), DirectTime(R_PLUTO));
return 0;
}
When all is said and done, it is supposed to output the following:
Planet Hohmann Time Direct Time
Venus 145.88 1.49
Jupiter 996.83 5.80
Pluto 16643.47 17.57
However, mine keeps outputting this:
Planet Hohmann Time Direct Time
145.88Venus 145.88 1.49
996.503Jupiter 996.50 5.80
16643.5Pluto 16643.47 17.57
I'm thinking that the issue is either with what im printing for the functions, or i have them repeating the output somewhere without realizing it.
P.S
This is my first question on stack. I have heard that alot of people ask bad question, so if i am doing something wrong, please let me know so i can do better!!
Thanks for your help!!
| The problem is that your ConvertSecondsToDays function is inadvertently printing its result to stdout via:
cout << days;
That is intermingled with the real output done in main. Remove the cout call and you should be good.
|
70,399,536 | 70,399,694 | why std::function is not executed | I am using std::bind to create a std::function type and typedef it, but its instance would not execute. Following is my code:
void func(int a, const std::string& b)
{
std::cout << a << ", " << b << std::endl;
}
typedef std::function<void (int, const std::string&)> THE_FUNCTION;
THE_FUNCTION f = std::bind(func, 18, std::string("hello world"));
f; // no action at all
f(); // will not compile, term does not evaluate to a function taking 0 arguments
// class does not define an 'operator()' or a user defined conversion operator
// to a pointer-to-function or reference-to-function that takes appropriate number
// of arguments
f.operator(); // will not compile, 'std::_Func_class<_Ret,int,const std::string &>::operator ()'
// : non-standard syntax; use '&' to create a pointer to member
(&the_f)->operator(); // will not compile, 'std::_Func_class<_Ret,int,const std::string &>::operator ()': non-standard syntax; use '&' to create a pointer to member
But if I do this, then the function will get executed:
auto g = std::bind(func, 3, "good morning")
g()
| Change this:
typedef std::function<void (int, const std::string&)> THE_FUNCTION;
with:
typedef std::function<void ()> THE_FUNCTION;
and it will work.
L.E.: When you call bind, it means you have a function that "is very similar" with what you want, and fill the rest of the arguments that are not needed with some provided "values".
https://en.cppreference.com/w/cpp/utility/functional/bind
|
70,400,005 | 70,501,376 | Visual Studio 2019 Freeglut (via nuget) - cannot open "Freeglut.lib" | I've been trying to create a GLUT-compatible Visual Studio 2019 project. Manually installing has caused some extremely complicated issues and breaks the project completely (even after uninstalling it) so I'm just trying to use the Nuget package. The .h files seem to be included correctly after this. However, any use of the line '#include <GL/freeglut.h>' - even in a completely blank project - produces an LNK1104 error:
cannot open file 'freeglut.lib'
Are there additional installation steps I'm missing? The .lib file is present in the folders. Trying to manually link it in project properties changes nothing.
| Resolved by using this method and then adding the line
#include <windows.h>
|
70,400,496 | 70,401,202 | Why does std::poisson_distribution hang when passed a very large mean? | For example, the following code hangs, using my setup with a recent version of g++ and GNU libraries:
#include <random>
#include <cstdio>
std::default_random_engine rng;
int main(){
std::poisson_distribution<long> mine(34387423874230847234.0);
std::printf("%ld\n", mine(rng));
}
Try it online
The description for the min and max functions here seems to suggest that it will clamp the output to the maximum possible value of the type parameter, in this case long. But clearly that's not happening. Is this expected behavior?
Edit: When I link against LLVM libc++, the poisson distribution always returns LLONG_MAX, which is more what I'd expect. Is this a GNU libstdc++ bug?
| We just discussed that libstdc++ normalizes the part of the probability distribution that fits in the output type (so the relative probabilities are correct) whereas libc++ clamps it (so that the mean is as correct as possible). The former approach has greatly increased expected runtime in the case where the parameter is uselessly large, but I would hesitate to call that a bug.
The min and max member functions describe what can happen, and are accurate: they do not imply either mechanism for making that happen.
|
70,400,598 | 70,400,647 | on the line Sort(arr,arr +n ) , how arr+n specifies end position here? | This code is about sorting an array :
#include <bits/stdc++.h>
using namespace std;
int main()
{
int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
int n = sizeof(arr) / sizeof(arr[0]);
sort(arr, arr + n);
cout << "\nArray after sorting using "
"default sort is : \n";
//Here I started printing the array
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
return 0;
}
Unfortunately, I am unable to understand this line :
sort(arr, arr + n);
How arr+n specifies end position here ?
| For arrays, array name arr indicates iterator pointing to first element of array and +n would increment that iterator by n elements. In your case, the sort algorithm should take beginning iterator and iterator pointing to one beyond last element.
arr: beginning iterator
arr+n: ending iterator (one beyond last element)
Typically, algorithms don't count ending iterator in their range, so it's like this.
|
70,400,666 | 70,401,197 | Giving error for wrong return type in C++ | #include<iostream>
using namespace std;
void factor(int n)
{
if(n<=1)
return;
for(int i=2;i*i<=n;i++){
while(n%i==0){
printf(i);
n=n/i;
}
}
if(n>1)
{
return n;
}
}
int main(){
factor(10);
}
Error:
return-statement with a value, in function returning 'void' [-fpermissive]
16 | return n;
| ^
| The problem is that your function factor has a return type of void but it actually returns an int object.
To solve this, you should match the return type of the function factor with what you're actually returning from inside the function as shown below.
Secondly you should also take care of the situation when none of the conditions(like if) are satisfied by adding appropriate return statements as shown below:
int factor(int n) //VOID CHANGED TO INT HERE
{
if(n<=1)
return 0; //CHANGED RETURN TO RETURN 0 HERE
for(int i=2;i*i<=n;i++){
while(n%i==0){
//printf(i);
n=n/i;
}
}
if(n>1)
{
return n;
}
return 0;//ADDED RETURN HERE for the case if none of the if are satisfied and control flow reaches here
}
|
70,400,906 | 70,400,954 | Is performing indirection from a pointer acquired from converting an integer value definitely UB? | Consider this example
int main(){
std::intptr_t value = /* a special integer value */;
int* ptr = reinterpret_cast<int*>(value ); // #1
int v = *ptr; // #2
}
[expr.reinterpret.cast] p5 says
A value of integral type or enumeration type can be explicitly converted to a pointer. A pointer converted to an integer of sufficient size (if any such exists on the implementation) and back to the same pointer type will have its original value; mappings between pointers and integers are otherwise implementation-defined.
At least, step #1 is implementation-defined. For step #2, in my opinion, I think it has four possibilities, which are
The implementation does not support such a conversion, and implementation does anything for it.
The pointer value is exactly the address of an object of type int, the result is well-formed.
The pointer value is the address of an object other than the int type, the result is UB.
The pointer value is an invalid pointer value, the indirection is UB.
It means what the behavior of the indirection through the pointer ptr will be depends on the implementation. It is not definitely UB if the implementation takes option 2. So, I wonder whether this case is not definitely UB or is definitely UB? If it is latter, which provisions strongly state the behavior?
| The standard has nothing more to say on it than what you quoted. The standard only guarantees the meaning of a integer-to-pointer cast if that integer value was taken from a pointer-to-integer cast. The meaning of all other integer-to-pointer conversions are implementation defined.
And that means everything about them is "implementation defined": what they result in and what using those results will do. After all, the pointer-to-integer-to-pointer round trip spells out that you get the "original value" back. The fact that the resulting pointer has the "original value" means that it will behave exactly like you had copied the original pointer itself. So the standard needs say nothing more on the matter.
The behavior of the pointer taken from an implementation-defined integer-to-pointer cast is... implementation-defined. If an implementation says that supports such conversions, it must spell out what the result of supported conversions are. That is, if there is some "a special integer value" for which a cast to an int* is supported by the implementation, it must say what the result of that cast is. This includes things like whether it pointer to an actual int or whatever.
|
70,401,270 | 70,401,302 | This Declaration has no store class -> encounter problem while using bool in classes cpp problem | i was working on a college Project and encountered this problem ->
When I declare the bool a and store value true/false in it, code runs fine
but while I only declare, and stores the value afterwards, like in code, it shows an error, can anyone explain why it is...?
#include <iostream>
class Design{
public:
void welcome(){
std :: cout << "------------------------------------------------------------\n";
std :: cout << " Welcome to Faculty Feedback form. Enter Your credentials\n";
std :: cout << "------------------------------------------------------------\n";
}
};
class Admin: public Design{
};
class Student: public Admin{
};
class Login: public Student{
//bool a = true; Works fine
bool a;
a = true; // Shows error
public:
void authenticate(){
}
};
int main(){
Login LOGIN;
LOGIN.welcome();
LOGIN.authenticate();
return 0;
}
| You must use a constructor. Classes and functions are different.
class Login: public Student{
//bool a = true; Works fine
bool a;
Login() : a(true)
{
}
public:
void authenticate(){
}
};
|
70,401,301 | 70,401,339 | Conversion of Binary to Decimals | I am writing a c++ program where the program takes the t test cases as input and asks the binary input t times, and after that displays the output.
I tried to code but for 1st test case it displays right output in decimal format but for further test cases its not displaying correct output result.
#include<iostream>
#include<cmath>
using namespace std;
int main() {
long int num;
int r=0,i=0,t,dec=0;
cin>>t;
while(t--) {
cin>>num;
while (num!=0) {
r = num% 10;
num /= 10;
dec += r * pow(2, i);
++i;
}
cout<<dec<<"\n";
}
return 0;
}
This code if run for lets say 2 test cases , lets say first one is 101 , it displays 5 which is fine but on the second input , lets say 111 , it displays output 61.
I am not sure where I am getting it wrong.
| You initialize i, dec outside the outer while loop. Initialize them to 0 inside the outer while loop and it works:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int t;
cin >> t;
while(t--)
{
int num, r, dec = 0, i = 0;
cin >> num;
while (num != 0) {
r = num % 10;
num /= 10;
dec += r * pow(2, i);
//cout << r << " " << num << " " << i << " " << dec << endl;
++i;
}
cout << dec << "\n";
}
return 0;
}
|
70,401,391 | 70,401,635 | Create comparator for inserting triplets in min priority queue | I have made a triplet using a class with all members as integers. I want to insert the triplet in min priority queue using STL in C++. I heard that it can be done using a bool comparator function, but don't have any idea about how to use it with 3 elements.
Note: I don't want to use vector pairs for inserting 3 values (I know how to do it ), I only want to use class triplets.
Can someone help me in implementing it?
using namespace std;
#include<bits/stdc++.h>
class triplet{
public:
int element;
int arrIndex;
int elementIndex;
};
priority_queue<triplet, vector<triplet>, greater<triplet>> pq;
| I don`t know why you did std::vector, std::greater but.
#include <queue>
#include <vector>
class triplet {
public:
int element;
int arrIndex;
int elementIndex;
constexpr bool operator>(const triplet& r)
{
return element > r.element;
}
};
int main()
{
std::priority_queue<triplet, std::vector<triplet>, std::greater<>> queue;
triplet a, b;
a.element = 3;
b.element = 5;
queue.push(a);
queue.push(b);
}
This is possible by define a triplet operator.
or
#include <queue>
#include <vector>
class triplet {
public:
int element;
int arrIndex;
int elementIndex;
};
template <>
struct std::greater<triplet>
{
bool operator()(const triplet& l, const triplet& r)
{
return l.element > r.element;
}
};
int main()
{
std::priority_queue<triplet, std::vector<triplet>, std::greater<triplet>> queue;
triplet a, b;
a.element = 3;
b.element = 5;
queue.push(a);
queue.push(b);
}
through template specialization.
|
70,401,545 | 70,406,698 | How to use fltk graphic library with visual studio (community) 2022 for C++ project on Windows 11 PC | I have tried downloading the files from the website
and try using it directing it but it needs to be compile or generated i guess.
I am new to learning C++ and fltk graphic library.
Thanks in advance
| Yes!!! I finally got it.
Step 1
I install vcpkg,
follow the instructions and integrate with visual studio.
Then I download fltk using vcpkg:
vcpkg install fltk.
Step 2
Finally in Visual Studio, Linker>>General>>Additional Library Directories : refer to the lib folder which vcpkg produced during installation.
And C/C++>>General>>Additional Include Directories: refer to the include folder from vcpkg.
That's it. I hope other newbies like me could save many hours. Thanks!
Note: I tried uploading a screenshot for proof but need at least 10 reputations!
|
70,401,573 | 70,401,655 | Invalid Read Of size 8 when passing a string to a function | Im a second year CS student and Im attempting to make a hangman game for fun during my winter break. Ive implemented the beginning of a menu class here, and yes I know this is too much oop for a project of this scope but I intent to reuse all these classes.
Anyways valgrind is telling me an Invalid read of size 8 and it returns the following lines in order:
menu::getName (menu.cpp:13) (this is at menu.cpp\getName()\return name;)
menu::print() (menu.cpp:21) (this is at menu.cpp\print()\cout<<". return to "<getName();)
main (main.cppp:28) (this is at main.cpp\main()\thisMenu->print();)
Im usually very good at solving these types of problems, and I searched the web but I couldnt find a solution and Im completely stumped. I feel like it could be a simple issue and Im missing something but Im not sure. Any help is greatly appreciated! Thanks!
menu.cpp:
#include <vector>
using namespace std;
//contains a list of menus, allowing for us to navigate menus and keep track of where we are via linked list
class menu{
private:
//we will keep track of which menus this one can access via a vector and a parent pointer
vector<menu*> options;
string name="";
menu* parent;
public:
string getName(){
return name;
}
void insert(menu* obj){
options.push_back(obj);
}
//print all the menus this one connects to, i.e. the menus the user can access from here
void print(){
int size=options.size();
**if (parent!=nullptr){
cout<<". return to "<<parent->getName();
}**
for(int i=0; i<size; i++){
cout<<i+2<<". "<<options[i]->getName()<<endl;
}
}
menu* nextMenu(int input){
try{
return(options.at(input));
}
catch(...){
return this;
}
}
menu(string str, menu *parentIn){
parent=parentIn;
name=str;
}
};
main.cpp:
#include "SkipList.h"
#include "menu.cpp"
#include <string>
using namespace std;
int main(int argc, char** argv) {
SkipList *letterBank=new SkipList;
vector<string> wordbank();
//fill the letter bank with all lower case letters
for(char currLetter=97; currLetter<123; currLetter++){
Key currKey=to_string((int)currLetter);
Value currVal=to_string(currLetter);
letterBank->insert(currKey, currVal);
}
menu *MainMenu=new menu(string("Main Menu"), nullptr);
menu *NumOfPlayers=new menu(string("Number of Players"), MainMenu);
menu *PlayerSelect=new menu(string("Player Select"), NumOfPlayers);
menu *Game=new menu(string("Game"), NumOfPlayers);
menu *WordBankMenu=new menu(string("Word Bank Modification"), MainMenu);
MainMenu->insert(NumOfPlayers);
NumOfPlayers->insert(PlayerSelect);
PlayerSelect->insert(Game);
Game->insert(nullptr);
MainMenu->insert(WordBankMenu);
menu *thisMenu= MainMenu;
int input;
while(thisMenu!=nullptr){
thisMenu->print();
cin>>input;
thisMenu=thisMenu->nextMenu(input);
}
}
| If you look at this line:
cout<<". return to "<<parent->getName();
You access the parent's name here;
But for MainMenu, parent is nullptr, therefore it's an invalid access!
The line needs to be made conditional on parent being different from nullptr.
|
70,402,079 | 70,402,579 | tag dispatch based on conditional_t over is_floating_point | I am getting a strange, Call to function 'Equals' that is neither visible in the template definition nor found by argument-dependent lookup, for a simple tag dispatch implementation.
template <typename T>
bool Equals(T lhs, T rhs){
return Equals(rhs, lhs, conditional_t<is_floating_point<T>::value, true_type, false_type>{});
}
template <typename T> // for floating
bool Equals(T lhs, T rhs, true_type){
return abs(lhs - rhs) < 0.01;
}
template <typename T> // for all the other
bool Equals(T lhs, T rhs, false_type){
return lhs == rhs;
}
what am I doing wrong?
| When performing the tag dispatching, you are not instantiating the true_type. But more importantly, you need to change the order of your functions, the tagged functions need to be defined before the function that is performing the dispatching, eg:
template <typename T> // for floating
bool Equals(T lhs, T rhs, true_type){
return abs(lhs - rhs) < 0.01;
}
template <typename T> // for all the other
bool Equals(T lhs, T rhs, false_type){
return lhs == rhs;
}
// moved down here!
template <typename T>
bool Equals(T lhs, T rhs){
return Equals(lhs, rhs, conditional_t<is_floating_point<T>::value, true_type{}, false_type>{});
}
That being said, in C++17 and later, you don't need to use tag dispatching at all, you can use if constexpr instead, eg:
template <typename T>
bool Equals(T lhs, T rhs){
if constexpr (is_floating_point_v<T>)
return abs(lhs - rhs) < 0.01;
else
return lhs == rhs;
}
|
70,402,092 | 70,402,289 | Error passing rapidjson::Value type to another function | I needed to pass a variable with rapidjson::Value type to another function with the following code:
#include "filereadstream.h"
#include "stringbuffer.h"
#include "rapidjson.h"
#include "document.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace rapidjson;
using namespace std;
static void processJsonValue(Value jsonValue) {
if (jsonValue.IsArray() && !jsonValue.Empty()) {
//jsonValue is valid
//json value processing procedure below...
}
}
void main()
{
char* chartFile = "C:\\Users\\DrBlindriver\\Documents\\test.json";
ifstream in(chartFile);
//attempt to open json file
if (!in.is_open()) {
cout << "Failed to access json file!\n";
return;
}
const string jsonContent((istreambuf_iterator<char>(in)), istreambuf_iterator<char>());
in.close();
Document jsonFile;
//read json and check for error
if ((jsonFile.Parse(jsonContent.c_str()).HasParseError()) || !(jsonFile.HasMember("testMember"))) {
cout << "Invalid json file!\n";
return;
}
Value testMember;
//attempt to pass testMember value to processJsonValue
testMember = jsonFile["testMember"];
processJsonValue(testMember);
}
when I encountered the error E0330:
"rapidjson::GenericValue<Encoding, Allocator>::GenericValue(const rapidjson::GenericValue<Encoding, Allocator> &rhs) [with Encoding=rapidjson::UTF8, Allocator=rapidjson::MemoryPoolAllocatorrapidjson::CrtAllocator]" (declared at line 574 of "C:\Users\DrBlindriver\source\repos\RapidJsonTest\RapidJsonTest\json\document.h") is inaccessible
at
processJsonValue(testMember);
I never encountered such error before and have been seeking a solution for a long time on the Internet, But no use. Please help or give some ideas how I can solve this problem.
| The error says
rapidjson::GenericValue<Encoding, Allocator>::GenericValue(const
rapidjson::GenericValue<Encoding, Allocator> &rhs) (...) is
inaccessible
That looks like a copy constructor to me. If the error is thrown at processJsonValue(testMember), try making your processJsonValue function take parameters by reference:
static void processJsonValue(Value& jsonValue) {
// code here
}
|
70,402,420 | 70,402,475 | Is it safe to reassign *this inside a class' method? | I have an object that is related to some file stored on the disk. The object's constructor accepts this file as an argument, reads it and creates an actual object with the settings depending on the file's content. During the runtime there is a probability for this file to be modified by the user. The object has a method that checks if the file has been modified since the last read, and if this is true, the object has to be updated. There are enough members to be updated inside the object, so instead of manually update each of them it is more convenient to simply create a new object and move it into the existing one(less typing and better readability). But is it actually safe to change *this during the method execution like in the example below?
void Object::update()
{
if (this->isModified(file)) // Check if a file has been modified since the last read
{
try
{
Object newObject(file); // May throw
*this = std::move(newObject); // Is it safe?
}
catch (const std::exception& ex)
{
// Invalidate and rethrow exception
this->invalidate();
throw(ex);
}
}
// ...
}
| You seem to be worried about this appearing on the left hand side, though *this = ... merely calls operator=. Typically the assignment operator that takes a rvalue reference just moves the members.
Consider this simpler example:
struct foo {
int x = 42;
foo& operator=(foo&& other){
x = std::move(other.x);
return *this;
}
void bar(){
foo other;
operator=(std::move(other));
}
};
Nothing wrong with that.
Another way to convince yourself that *this = std::move(newObject); is not problematic is to inline all code from the assignment operator to update. For the example above that would be:
struct foo {
int x = 42;
void bar(){
foo other;
x = std::move(other.x);
}
};
|
70,402,662 | 70,402,985 | How to replace the content of an element in a std::map with the content of another element | I have a class "Token" and a class "ASTNode". ASTNode is a tree representation of a list of "Token"'s.
#define INTEGER "INTEGER"
#define ARRAY "ARRAY"
class Token {
private:
std::string type_t;
std::string value_t;
public:
Token() {
type_t = "";
value_t = "";
}
Token(std::string type, std::string value) {
type_t = type;
value_t = value;
}
~Token(){};
std::string value() {
return value_t;
}
std::string type() {
return type_t;
}
std::string str() {
return ("Token(" + type_t + ", " + value_t + ")");
}
};
Class ASTNode
class ASTNode {
public:
std::vector<ASTNode*> child;
Token _token;
ASTNode() {};
ASTNode(Token token) {
_token = token;
}
~ASTNode() {};
void make_child(ASTNode _node) {
ASTNode *temp = new ASTNode(_node.token());
temp->child = _node.child;
child.push_back(temp);
}
Token token() {
return _token;
}
};
Now i have a std::map<std::string, ASTNode> where i want to store these "Array" nodes
std::map<std::string, ASTNode> ARRAYS;
// create a node
ASTNode arr1(Token(ARRAY, "a"));
arr1.make_child(Token(INTEGER, "1"));
arr1.make_child(Token(INTEGER, "2"));
arr1.make_child(Token(INTEGER, "3"));
// store as ARRAYS["a"]
ARRAYS.insert(std::pair<std::string, ASTNode>("a", arr1));
// create another node
ASTNode arr2(Token(ARRAY, "b"));
arr2.make_child(Token(INTEGER, "4"));
arr2.make_child(Token(INTEGER, "5"));
arr2.make_child(Token(INTEGER, "6"));
// store as ARRAYS["b"]
ARRAYS.insert(std::pair<std::string, ASTNode>("b", arr2));
My problem is when i want to create a new array to be a copy of an existing array. Lets say i want to create array c to be the same as array a
ARRAYS.insert( std::pair<std::string, ASTNode>("c", arr1) );
Now i want to change the value of the 1st "array element" of the copy stored as c.
ASTNode tmp = ARRAYS["c"];
tmp.child[0]->_token = Token(INTEGER, "0");
//ARRAYS["c"] = tmp;
ARRAYS.insert(std::pair<std::string, ASTNode>("c", tmp));
but instead of only array c has been modified, array a also has been. How to change this so i can change only the copy of it?
| Just create a deep copy constructor of ASTNode and everything works well:
ASTNode(ASTNode const & other) {
_token = other._token;
for (auto ochild: other.child)
child.push_back(new ASTNode(*ochild));
}
You may also wish to add similar assignment operator = method implementation (but it is not needed to fix your current error, only above copy constructor is needed), assignment needs Clear() method for cleanup, which can be used in destructor also for freeing memory:
ASTNode & operator = (ASTNode const & other) {
Clear();
_token = other._token;
for (auto ochild: other.child)
child.push_back(new ASTNode(*ochild));
return *this;
}
void Clear() {
for (auto c: child)
delete c;
child.clear();
_token = Token();
}
~ASTNode() { Clear(); }
Full working code:
Try it online!
#include <string>
#include <vector>
#include <map>
#include <iostream>
#define INTEGER "INTEGER"
#define ARRAY "ARRAY"
class Token {
private:
std::string type_t;
std::string value_t;
public:
Token() {
type_t = "";
value_t = "";
}
Token(std::string type, std::string value) {
type_t = type;
value_t = value;
}
~Token(){};
std::string value() {
return value_t;
}
std::string type() {
return type_t;
}
std::string str() {
return ("Token(" + type_t + ", " + value_t + ")");
}
};
class ASTNode {
public:
std::vector<ASTNode*> child;
Token _token;
ASTNode() {};
ASTNode(Token token) {
_token = token;
}
ASTNode(ASTNode const & other) {
_token = other._token;
for (auto ochild: other.child)
child.push_back(new ASTNode(*ochild));
}
ASTNode & operator = (ASTNode const & other) {
Clear();
_token = other._token;
for (auto ochild: other.child)
child.push_back(new ASTNode(*ochild));
return *this;
}
void Clear() {
for (auto c: child)
delete c;
child.clear();
_token = Token();
}
~ASTNode() { Clear(); }
void make_child(ASTNode _node) {
ASTNode *temp = new ASTNode(_node.token());
temp->child = _node.child;
child.push_back(temp);
}
Token token() {
return _token;
}
};
int main() {
std::map<std::string, ASTNode> ARRAYS;
// create a node
ASTNode arr1(Token(ARRAY, "a"));
arr1.make_child(Token(INTEGER, "1"));
arr1.make_child(Token(INTEGER, "2"));
arr1.make_child(Token(INTEGER, "3"));
// store as ARRAYS["a"]
ARRAYS.insert(std::pair<std::string, ASTNode>("a", arr1));
// create another node
ASTNode arr2(Token(ARRAY, "b"));
arr2.make_child(Token(INTEGER, "4"));
arr2.make_child(Token(INTEGER, "5"));
arr2.make_child(Token(INTEGER, "6"));
// store as ARRAYS["b"]
ARRAYS.insert(std::pair<std::string, ASTNode>("b", arr2));
std::cout << "a token " << arr1.child[0]->_token.value() << std::endl;
ARRAYS.insert( std::pair<std::string, ASTNode>("c", arr1) );
ASTNode tmp = ARRAYS["c"];
tmp.child[0]->_token = Token(INTEGER, "0");
//ARRAYS["c"] = tmp;
ARRAYS.insert(std::pair<std::string, ASTNode>("c", tmp));
std::cout << "a token " << arr1.child[0]->_token.value() << std::endl;
}
Output before change:
a token 1
a token 0
Output after change:
a token 1
a token 1
|
70,402,974 | 70,412,248 | Why is only static_cast able to return new object of requested type? | Among static_cast, dynamic_cast, reinterpret_cast and const_cast, only static_cast is able to return an object of desirable type, whereas the other type can return only pointer or reference to representation. Why is it so?
Examples:
int y = 3;
double z = reinterpret_cast<double> (y);//error
double z = reinterpret_cast<double&> (y);//ok
double z = static_cast<double> (y);//but this is ok!!!
const int y = 3;
int z = const_cast<int> (y);//error
int z = const_cast<int&> (y);//ok
and for dynamic_cast:
using namespace std;
class Gun
{
public:
virtual void shoot(){
cout << "BANG!\n";
}
};
class MachineGun : public Gun{
public:
void shoot() override{
cout <<"3X-BANG\n";
}
};
int main()
{
Gun gun;
MachineGun tt;
Gun* gunp = &gun;
Gun* gunp1 = &tt;
Gun* newGun = dynamic_cast<Gun*>(gunp1);//ok
Gun newGun1 = dynamic_cast<Gun>(tt);//error
}
| I'm making attempt to explain based on example, as addition to other answer that did explain nature of casts.
int y = 3;
double z = reinterpret_cast<double> (y);//error
This is not one of 11 allowed casts with reinterpret_cast. Also std::bit_cast can't cast it on most platforms as the int typically does not have enough bits for double. So it is unsure what you wanted to achieve.
double z = reinterpret_cast<double&> (y);//ok
This is present in list of valid reinterpret_cast but likely causes undefined behaviour for same reason why std::bit_cast refuses. In typical implementation your z is bigger than y and so takes bits beyond memory location of y. In such places prefer std::bit_cast that does not compile to undefined behaviour but refuses to compile.
double z = static_cast<double> (y);//but this is ok!!!
But that is fully valid. It is effectively same as
double z = y;
Compilers do not even warn about the latter. However when the value range of y does not fully fit to z then it is not clear if it was intentional. On such cases it is better to use former to indicate intent.
const int y = 3;
int z = const_cast<int> (y);//error
That is good. Absurd const_cast does not compile! Or how does the effect that you tried to achieve differ from lot more readable
int z = y;
I would write that. Please describe the situation where you would write former.
int z = const_cast<int&> (y);//ok
Works, but is similarly unneeded and confusing like previous. I would only use const_cast for situations like that:
int x;
const int& y = x;
int& z = const_cast<int&> (y);
z = 42;
Here I know that thing referred by reference to const y is really not const originally and so it is not undefined behaviour to modify it to 42.
About dynamic_cast your example does not make sense at all what it wants to do:
Gun newGun1 = dynamic_cast<Gun>(tt);//error
It could be perhaps trying to do something like that:
Gun newGun1 = tt;
That compiles. However that results with newGun1 initialised with sliced out Gun base sub-object of MachineGun tt and that is often programming error. What you tried to achieve with cast remains totally dark however.
|
70,403,666 | 70,404,599 | std::views has not been declared | I am trying to use the ranges library from c++20 and I have this simple loop.
for (const int& num : vec | std::views::drop(2)) {
std::cout << num << ' ';
}
I get an error message saying error: 'std::views' has not been declared. I don't get any errors about including the header.
This is my g++
g++.exe (MinGW-W64 x86_64-ucrt-posix-seh, built by Brecht Sanders) 11.2.0
Copyright (C) 2021 Free Software Foundation, Inc.
As far as I know it should work as long as you have c++20.
The following example does not compile on my machine:
#include <iostream>
#include <ranges>
#include <vector>
int main() {
std::cout << "Hello world!";
std::vector <int> vec = {1, 2, 3, 4, 5};
// print entire vector
for (const int& num : vec) {
std::cout << num << ' ';
}
std::cout << "\n";
// print the vector but skip first few elements
for (const int& num : vec | std::views::drop(2)) {
std::cout << num << ' ';
}
return 0;
}
| Depending on the version of your compiler, different standards are the default. For 11.2 it is C++ 17 AFAIK.
Cou can just add a flag and it compiles:
g++ --std=c++20 main.cc
|
70,403,985 | 70,404,051 | Is there any options to make clang-format produce the following effect? | I use clang-format to format the following code, but the effect is not what I want:
void f(int, int, std::vector<int>, std::map<int, int>)
{}
int main()
{
f(
{
},
{}, {1, 2, 3},
{
{1, 2},
{3, 4},
});
}
Is there any options to make clang-format produce the following effect?
void f(int, int, std::vector<int>, std::map<int, int>)
{}
int main()
{
f({},
{},
{1, 2, 3},
{
{1, 2},
{3, 4},
});
}
| Yes there is, use the style you want. (it's really that easy!)
clang-format -h tells you about the available options that clang-format has.
--style=<string> - Coding style, currently supports:
LLVM, GNU, Google, Chromium, Microsoft, Mozilla, WebKit.
Use -style=file to load style configuration from
.clang-format file located in one of the parent
directories of the source file (or current
directory for stdin).
In your case, you probably want something like clang-format --style=LLVM.
But it's not going to be exactly what you want. So, you'll need to write your own style file. It's not that hard. Use clang-format --style=file and put the style definitions in a file called .clang-format in the same, or one of its parent directories.
The documentation explains exactly what you need to do. If you're more of the visual type, this generator might be helpful.
Note, though, that you're probably better off making only minor adjustments to a "common" base style; other programmers might not like it when you do wildly different than other code they're used to. For an example of a modified-as-far-as-necessary-to-deal-with-specific-project-needs style file, see GNU Radio's .clang-format file.
|
70,404,090 | 70,404,124 | Where to use std::span? | I want to write a function that can accept any type of contiguous buffer (e.g. std::array, std::vector, raw array, etc) from its call site. I have come up with two methods.
Method #1:
void func( int* const buffer, const std::size_t expectedTokenCount );
Here, expectedTokenCount is the maximum number of elements that will be inserted into the buffer.
Method #2:
void func( const std::span<int> buffer, const std::size_t expectedTokenCount );
In this approach, I think that I better write the function in a way that first checks the size of the buffer via buffer.size( ) and compares it with expectedTokenCount to make sure that its capacity is greater than or equal to expectedTokenCount otherwise it throws some kind of exception. Is this a valid and safer method than the 1st method? Which one is better? Will the behavior of span and its size member function change if a vector is passed to it or will it be the same as for array?
|
Where to use std::span?
Where-ever you would have otherwise used a pointer and a size, you can use std::span instead of the pointer and the size.
Is [#2] a valid ... method?
Sure. You did however change the constness of the pointer. You should use std::span<const int>.
Which one is better?
Each have their uses. But in most cases passing two sizes is redundant
The use of std::span is orthogonal to the change of using two sizes. You can do #1 as void(std::span<const int>) and you can do #2 as void(int* const buffer, const std::size_t buffer_size, const std::size_t expectedTokenCount).
Using std::span is generally an improvement.
|
70,404,302 | 70,407,198 | Track text insertion in QTextBrowser | I am making an application and using QTextBrowser to show messages. It should parse ascii colors, so my class (say MessageBoard) is inheriting from QTextBrowser. I can replace ascii color code and set MessageBoard's text color according to the ascii code before insertion.
But there are many ways of inserting text into the QTextBrowser, so MessageBoard should be able to detect exactly where text is inserted and what is its length.
The problem is, QTextBrowser (through QTextEdit) provides only textChanged signal but there is no way to get where changes happened.
So is there no way to get it or I missing something?
I've solved the problem but this was the issue I was having, (See main.cpp).
MessageBoard.h
#ifndef MESSAGEBOARD_H
#define MESSAGEBOARD_H
#include <QTextBrowser>
#define AC_BLACK "\u001b[30m"
#define AC_RED "\u001b[31m"
#define AC_GREEN "\u001b[32m"
#define AC_YELLOW "\u001b[33m"
#define AC_BLUE "\u001b[34m"
#define AC_MAGENTA "\u001b[35m"
#define AC_CYAN "\u001b[36m"
#define AC_WHITE "\u001b[37m"
#define AC_RESET "\u001b[0m"
using AsciiStringPos = std::pair<int /*index*/,int /*length*/>;
class MessageBoard : public QTextBrowser
{
public:
MessageBoard(QWidget *parent = nullptr);
void appendText(const QByteArray &text);
~MessageBoard();
private:
std::pair<AsciiStringPos,QColor> find_ascii(const QByteArray &text, int starts_from);
private:
std::map<QByteArray, QColor> m_colors;
};
#endif // MESSAGEBOARD_H
MessageBoard.cpp
#include "MessageBoard.h"
#include <QRegularExpression>
#include <climits>
MessageBoard::MessageBoard(QWidget *parent)
: QTextBrowser(parent),
m_colors({
{QByteArray(AC_BLACK) , Qt::black},
{QByteArray(AC_RED) , Qt::red},
{QByteArray(AC_GREEN) , Qt::green},
{QByteArray(AC_YELLOW) , Qt::yellow},
{QByteArray(AC_BLUE) , Qt::blue},
{QByteArray(AC_MAGENTA) , Qt::magenta},
{QByteArray(AC_CYAN) , Qt::cyan},
{QByteArray(AC_WHITE) , Qt::white}
})
{
m_colors.insert({QByteArray(AC_RESET) , textColor()});
}
void MessageBoard::appendText(const QByteArray &text)
{
int index = 0;
QTextCursor text_cursor = textCursor();
text_cursor.movePosition(QTextCursor::End);
auto res = find_ascii(text,0);
while(res.first.first != -1) //color string's index
{
text_cursor.insertText(text.mid(index,res.first.first - index));//append text before the color
QTextCharFormat format;
format.setForeground(res.second); //set color to charformat
text_cursor.setCharFormat(format); //set charformat
index = res.first.first //color string started from
+ res.first.second; //color string length
res = find_ascii(text,index); //find next color
}
text_cursor.insertText(text.mid(index));
}
std::pair<AsciiStringPos, QColor> MessageBoard::find_ascii(const QByteArray &text, int starts_from)
{
QByteArray first_color;
int min_index = INT_MAX;
for(const auto &p : m_colors)
{
int index = text.indexOf(p.first,starts_from);
if(index != -1 && min_index > index)
{
min_index = index;
first_color = p.first;
}
}
if(first_color.isNull())
return {{-1,0},m_colors[QByteArray(AC_RESET)]};
else
return {{min_index,first_color.length()},m_colors[first_color]};
}
MessageBoard::~MessageBoard()
{
}
main.cpp
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MessageBoard w;
//appendText is manually created, so I can parse text before inserting.
w.appendText(AC_GREEN "This is written with " AC_RED " Ascii " AC_GREEN " escaped words." AC_RESET);
//append, can't do the same because I don't know the location where it was inserted.
w.append(AC_MAGENTA "This won't be written in magenta.");
w.appendText(AC_CYAN "This will be written in cyan" AC_RESET);
w.zoomIn(5);
w.show();
return a.exec();
}
Output Image
| If I understand your request well, I guess you may want to use this signal https://doc.qt.io/qt-5/qtextdocument.html#contentsChange
You will get access to QTextDocument with this https://doc.qt.io/qt-5/qtextedit.html#document-prop
|
70,404,549 | 70,405,002 | Cartesian product of std::tuple | For unit testing a C++17 framework that relies heavily on templates I tried to write helper template classes which generate a Cartesian product of two sets of data types given by two tuples:
**Input**: std::tuple <A, B> std::tuple<C,D,E>
**Expected output**: Cartesian product of the two tuples:
std::tuple<std::tuple<A,C>, std::tuple<A,D>, std::tuple<A,E>,
std::tuple<B,C>, std::tuple<B,D>, std::tuple<B,E>>
I am aware that Boost MP11 offers such features but I would not like to include a dependency on yet another library just for testing purposes. So far I came up with a pretty straight forward solution which though requires the class to be default-constructible (Try it here!):
template <typename T1, typename T2,
typename std::enable_if_t<is_tuple_v<T1>>* = nullptr,
typename std::enable_if_t<is_tuple_v<T2>>* = nullptr>
class CartesianProduct {
protected:
CartesianProduct() = delete;
CartesianProduct(CartesianProduct const&) = delete;
CartesianProduct(CartesianProduct&&) = delete;
CartesianProduct& operator=(CartesianProduct const&) = delete;
CartesianProduct& operator=(CartesianProduct&&) = delete;
template <typename T, typename... Ts,
typename std::enable_if_t<std::is_default_constructible_v<T>>* = nullptr,
typename std::enable_if_t<(std::is_default_constructible_v<Ts> && ...)>* = nullptr>
static constexpr auto innerHelper(T, std::tuple<Ts...>) noexcept {
return std::make_tuple(std::make_tuple(T{}, Ts{}) ...);
}
template <typename... Ts, typename T,
typename std::enable_if_t<std::is_default_constructible_v<T>>* = nullptr,
typename std::enable_if_t<(std::is_default_constructible_v<Ts> && ...)>* = nullptr>
static constexpr auto outerHelper(std::tuple<Ts...>, T) noexcept {
return std::tuple_cat(innerHelper(Ts{}, T{}) ...);
}
public:
using type = std::decay_t<decltype(outerHelper(std::declval<T1>(), std::declval<T2>()))>;
};
template <typename T1, typename T2>
using CartesianProduct_t = typename CartesianProduct<T1, T2>::type;
Also when trying to instantiate a list of template classes in a similar way (try it here) I have to make the same assumption: I can't apply it to classes which have a protected/private constructor (without a friend declaration) and are not-default-constructible.
Is it possible to lift the restriction of default constructability without turning to an std::integer_sequence and an additional helper class? From what I understand it is not possible to use std::declval<T>() directly in the methods innerHelper and outerHelper (which would solve my issue), as it seems to not be an unevaluated expression anymore. At least GCC complains then about static assertion failed: declval() must not be used! while it seems to compile fine with Clang.
Thank you in advance!
| One of the workarounds is to omit the function definition and directly use decltype to infer the return type:
template<typename T1, typename T2>
class CartesianProduct {
template<typename T, typename... Ts>
static auto innerHelper(T&&, std::tuple<Ts...>&&)
-> decltype(
std::make_tuple(
std::make_tuple(std::declval<T>(), std::declval<Ts>())...));
template <typename... Ts, typename T>
static auto outerHelper(std::tuple<Ts...>&&, T&&)
-> decltype(
std::tuple_cat(innerHelper(std::declval<Ts>(), std::declval<T>())...));
public:
using type = decltype(outerHelper(std::declval<T1>(), std::declval<T2>()));
};
class Example {
Example() = delete;
Example(const Example&) = delete;
};
using T1 = std::tuple<Example>;
using T2 = std::tuple<int, double>;
static_assert(
std::is_same_v<
CartesianProduct_t<T1, T2>,
std::tuple<std::tuple<Example, int>, std::tuple<Example, double>>>);
Demo.
|
70,404,688 | 70,406,699 | Mismatch between output of ldd --version and ldd -r -v a.out | I am trying to make sense of how output of ldd --version and ldd -v a.out
I have the below simple program
#include <iostream>
#include <string>
#include <cstring>
int main()
{
std::cout << "Hello world" << std::endl;
std::string a = "Test string";
char b[15] = {};
memcpy(b, a.c_str(), 15);
std::cout << b << std::endl;
return 0;
}
I compile it with following command
g++ --std=c++17 test.cpp
I want to find out which glibc version this program is going to use when I run say memcpy.
The output of ldd --version on this system is:
ldd --version
ldd (Ubuntu GLIBC 2.31-0ubuntu9.2) 2.31
Copyright (C) 2020 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Written by Roland McGrath and Ulrich Drepper.
The output of ldd -v a.out is
ldd -v a.out
linux-vdso.so.1 (0x00007ffe7d3f3000)
libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f050bb2f000)
libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f050bb14000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f050b922000)
libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f050b7d3000)
/lib64/ld-linux-x86-64.so.2 (0x00007f050bd3a000)
Version information:
./a.out:
libgcc_s.so.1 (GCC_3.0) => /lib/x86_64-linux-gnu/libgcc_s.so.1
libc.so.6 (GLIBC_2.4) => /lib/x86_64-linux-gnu/libc.so.6
libc.so.6 (GLIBC_2.2.5) => /lib/x86_64-linux-gnu/libc.so.6
libstdc++.so.6 (GLIBCXX_3.4.21) => /usr/lib/x86_64-linux-gnu/libstdc++.so.6
libstdc++.so.6 (CXXABI_1.3) => /usr/lib/x86_64-linux-gnu/libstdc++.so.6
libstdc++.so.6 (GLIBCXX_3.4) => /usr/lib/x86_64-linux-gnu/libstdc++.so.6
/usr/lib/x86_64-linux-gnu/libstdc++.so.6:
libm.so.6 (GLIBC_2.2.5) => /lib/x86_64-linux-gnu/libm.so.6
ld-linux-x86-64.so.2 (GLIBC_2.3) => /lib64/ld-linux-x86-64.so.2
libgcc_s.so.1 (GCC_4.2.0) => /lib/x86_64-linux-gnu/libgcc_s.so.1
libgcc_s.so.1 (GCC_3.4) => /lib/x86_64-linux-gnu/libgcc_s.so.1
libgcc_s.so.1 (GCC_3.3) => /lib/x86_64-linux-gnu/libgcc_s.so.1
libgcc_s.so.1 (GCC_3.0) => /lib/x86_64-linux-gnu/libgcc_s.so.1
libc.so.6 (GLIBC_2.14) => /lib/x86_64-linux-gnu/libc.so.6
libc.so.6 (GLIBC_2.6) => /lib/x86_64-linux-gnu/libc.so.6
libc.so.6 (GLIBC_2.4) => /lib/x86_64-linux-gnu/libc.so.6
libc.so.6 (GLIBC_2.18) => /lib/x86_64-linux-gnu/libc.so.6
libc.so.6 (GLIBC_2.16) => /lib/x86_64-linux-gnu/libc.so.6
libc.so.6 (GLIBC_2.3) => /lib/x86_64-linux-gnu/libc.so.6
libc.so.6 (GLIBC_2.3.4) => /lib/x86_64-linux-gnu/libc.so.6
libc.so.6 (GLIBC_2.17) => /lib/x86_64-linux-gnu/libc.so.6
libc.so.6 (GLIBC_2.3.2) => /lib/x86_64-linux-gnu/libc.so.6
libc.so.6 (GLIBC_2.2.5) => /lib/x86_64-linux-gnu/libc.so.6
/lib/x86_64-linux-gnu/libgcc_s.so.1:
libc.so.6 (GLIBC_2.14) => /lib/x86_64-linux-gnu/libc.so.6
libc.so.6 (GLIBC_2.2.5) => /lib/x86_64-linux-gnu/libc.so.6
/lib/x86_64-linux-gnu/libc.so.6:
ld-linux-x86-64.so.2 (GLIBC_2.3) => /lib64/ld-linux-x86-64.so.2
ld-linux-x86-64.so.2 (GLIBC_PRIVATE) => /lib64/ld-linux-x86-64.so.2
/lib/x86_64-linux-gnu/libm.so.6:
ld-linux-x86-64.so.2 (GLIBC_PRIVATE) => /lib64/ld-linux-x86-64.so.2
libc.so.6 (GLIBC_2.4) => /lib/x86_64-linux-gnu/libc.so.6
libc.so.6 (GLIBC_2.2.5) => /lib/x86_64-linux-gnu/libc.so.6
libc.so.6 (GLIBC_PRIVATE) => /lib/x86_64-linux-gnu/libc.so.6
What I can not understand is that if ldd --version says that I have GLIBC version 2.31 available then why did my executables ldd output say GLIBC_2.4 and GLIBC_2.2.5 for a.out.
What is the right way to understand this?
What would happen if I have compiled a binary on a system that has old version of libc.so (suppose has highest version of GLIBC as 2.17) and then run the binary on a system with new version of libc.so (suppose has highest version of GLIBC as 2.31) ?
Thanks
| You should read this answer, and look at the output from readelf -V a.out.
When a program is linked, it records the symbol version(s) used (current) at the time of the link.
Many of the symbols your program is using have not changed since e.g. GLIBC_2.2.5, so ldd says: you need at least version GLIBC_2.2.5 (for these symbols). Some of the symbols you use have changed in GLIBC-2.16, GLIBC-2.17 and GLIBC-2.18, so ldd says that you need these as well.
What would happen if I have compiled a binary on a system that has old version of libc.so (suppose has highest version of GLIBC as 2.17) and then run the binary on a system with new version of libc.so (suppose has highest version of GLIBC as 2.31) ?
The recorded symbols (encoded into a.out) will all be GLIBC_2.17 or older, and the program will run fine on a newer system, because GLIBC guarantees backward compatibility (programs built on an older system continue to run fine on newer ones).
But if you did the inverse -- built on a GLIBC-2.31 system and tried to run the program on a GLIBC-2.17 one, it may (or may not, depending on which symbols it actually uses) fail.
In the example you provided, the highest required version of GLIBC is GLIBC_2.18. Therefore, this particular a.out will work fine on a GLIBC-2.18 or newer system, but will fail on GLIBC-2.17 or older one.
Update:
What happens if an executable that is compiled on an old system which has highest version of GLIBC_2_17, is run on a system that has GLIBC_2_31 available? Will the executable pick the latest symbols (if they are ABI complaint) eg say memcpy - exec compiled on old system (with GLIBC without vector support) when run on new system (with GLIBC that has memcpy with vector support) will pick memcpy from new GLIBC that has vector support.
Yes, the executable will pick up the version it was linked with, and so long as the ABI for a given function hasn't changed, it will be the most recent version.
The case of memcpy in particular is a bit more complicated. On Fedora 35 x86_64 system (GLIBC-2.34):
nm /lib64/libc.so.6 | grep ' memcpy'
00000000000a1560 i memcpy
00000000000a1560 i memcpy@@GLIBC_2.14
00000000000b9c30 T memcpy@GLIBC_2.2.5
What you can see here is that the memcpy ABI changed in GLIBC-2.14, and it became a GNU indirect function. You can read the details at the link, but TL;DR is that the actual function called by your program will depend on processor capabilities. It could be any one of these:
00000000001870b0 t __memcpy_avx512_no_vzeroupper
0000000000189f00 t __memcpy_avx512_unaligned
0000000000189f70 t __memcpy_avx512_unaligned_erms
00000000001828f0 t __memcpy_avx_unaligned
0000000000182960 t __memcpy_avx_unaligned_erms
000000000018b0e0 t __memcpy_avx_unaligned_erms_rtm
000000000018b070 t __memcpy_avx_unaligned_rtm
00000000000b9ca0 t __memcpy_erms
00000000001920b0 t __memcpy_evex_unaligned
0000000000192120 t __memcpy_evex_unaligned_erms
00000000000b9c30 t __memcpy_sse2_unaligned
00000000000b9d10 t __memcpy_sse2_unaligned_erms
000000000015d400 t __memcpy_ssse3
0000000000162990 t __memcpy_ssse3_back
|
70,405,396 | 70,405,455 | how can I have a public method only show up when the template has a specific type? | I have a template that is intended to take int, float, double, char and std::string.
I want a method to only exist if the template typename is std::string
Is this possible?
| If you can use C++20, you can use a requires expression on the desired method to cause it to only be available under certain circumstances.
#include <iostream>
#include <string>
#include <concepts>
template<class T>
struct Foo
{
void alwaysAvailable() { std::cout << "Always available\n"; }
void conditionallyAvailable() requires std::same_as<T, std::string>
{
std::cout << "T is std::string\n";
}
};
int main()
{
Foo<int> fooInt;
fooInt.alwaysAvailable();
//fooInt.conditionallyAvailable(); // Constraint not satisfied
Foo<std::string> fooString;
fooString.alwaysAvailable();
fooString.conditionallyAvailable();
}
Foo<T>::alwaysAvailable is, as the name suggests, always available no matter what T is. Foo<T>::conditionallyAvailable is only available when T is std::string.
Demo here
The C++17 version is a little uglier. We have to make conditionallyAvailable a method template and then place some SFINAE constraints on the method:
#include <type_traits>
template<class T>
struct Foo
{
void alwaysAvailable() { std::cout << "Always available\n"; }
template<class U = T>
std::enable_if_t<std::is_same_v<U, T> && std::is_same_v<U, std::string>, void> conditionallyAvailable()
{
std::cout << "T is std::string\n";
}
};
Demo here
C++14 and C++11 versions are similar to the C++17 version, except for needing to expand out enable_if_t and is_same_v.
|
70,405,530 | 70,405,777 | Problem extracting formatted input from an istringstream that has been set twice | Thanks for the help.
My program reads lines from stdin. The first one has a single number which determines the mode at which the program is running, and the rest contain sequences of numbers of undetermined length. The number of lines is determined by the mode. I want to parse those lines into vectors of int. To do this, I am using getline and istringstream. I then get the numbers with formatted extraction >>. The first time I pass the string to the stream, there isn't any problem, the string is correctly passed to the stream, and I can read formatted input from it. However, if I get another line and pass it to the same stream, then something weird happens. The string is correctly copied to the stream, which I confer by writing
std::cout << iss.str() << std::endl
However, when I try to extract the numbers from the line, it doesn't.
Here is a Minimum Reproducible Example:
(I have tried to do it with two different streams and it works, the problem is that I have the cases inside a switch block, so it doesn't let me initialize streams inside it, and the number of streams changes quite a bit from mode to mode.)
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
int main()
{
string line;
int problem_type = -1, input_number = -1;
vector<int> sequence;
istringstream iss;
/* Get the problem type */
getline(cin, line);
iss.str(line);
if (!iss)
return -1;
cout << "Stream contents: " << iss.str() << endl;
iss >> problem_type;
cout << "Extracted numbers: " << problem_type << endl;
getline(cin, line);
iss.str(line);
if (!iss)
return -1;
cout << "Stream contents: " << iss.str() << endl;
cout << "Extracted numbers:";
while(iss >> input_number) {
cout << " " << input_number;
sequence.push_back(input_number);
}
cout << endl;
return 0;
}
Input:
1
1 2 3 4 5
Output:
Stream contents: 2
Extracted numbers: 2
Stream contents: 1 2 3 4 5
Extracted numbers:
Expected Output:
Stream contents: 2
Extracted numbers: 2
Stream contents: 1 2 3 4 5
Extracted numbers: 1 2 3 4 5
| Once you read iss >> problem_type;,
cout << "eof: " << iss.eof() << endl;
outputs
eof: 1
The next iss.str(line); does not reset the stream state, the loop condition is false. You want
iss.clear();
while(iss >> input_number) {
cout << " " << input_number;
sequence.push_back(input_number);
}
Output
Stream contents: 1
Extracted numbers: 1
Stream contents: 1 2 3 4 5
Extracted numbers: 1 2 3 4 5
|
70,405,583 | 70,405,723 | i am always getting segmentation fault | i am always getting 10861 segmentation fault (core dumped) in c++ sorry i came from java
it always says that head -> next how to allocate memory to that
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
};
class lisp
{
public:
Node *head;
void create(int d)
{
this->head->data = d;
cout << head->data;
}
void insert(int d)
{
Node *n = head;
Node *add;
add->data = d;
cout << head -> next << endl;
}
};
int main()
{
lisp test;
test.create(0);
test.insert(1);
test.insert(2);
return 0;
}
| You need to initialize the pointer before assigning some values to it. So, you need Node *add = new Node(); to do so. And suppose you want to append a new node to the list, maybe you need to keep track of the tail of the list (Node *tail). Every time you add a new node, you move the tail.
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
};
class lisp
{
public:
Node *head;
Node *tail;
void create(int d)
{
head = new Node();
head->data = d;
tail = head;
cout << head->data << endl;
}
void insert(int d)
{
Node *add = new Node();
add->data = d;
add->next = NULL;
tail->next = add;
tail = add;
cout << add->data << endl;
}
};
int main()
{
lisp test;
test.create(0);
test.insert(1);
test.insert(2);
return 0;
}
|
70,405,765 | 70,406,500 | Is defining functions in header files malpractice? | We have this header file:
headerA.h
#pragma once
#include <iostream>
void HeaderADefinedFunction()
{
std::could << "HeaderDefinedFunction called!\n";
}
Then inside sourceB.cpp
#include "headerA.h"
void FunctionB()
{
HeaderADefinedFunction();
}
And inside sourceC.cpp
#include "headerA.h"
void FunctionC()
{
HeaderADefinedFunction();
}
What are the negative aspects of defining the function HeaderADefinedFunction() in the header file itself. Would that definition be in an optimal form for link-time symbol resolution of that particular function?
| The code as-shown should produce a link failure with multiply-defined HeaderADefinedFunction() symbol.
The make the code actually valid, the function must be made inline.
Is defining functions in header files malpractice?
Not at all. In fact, template functions must be defined in the header1.
What are the negative aspects of defining the function HeaderADefinedFunction() in the header file itself.
One negative is that if you change the definition, you must rebuild every .cpp which #includes this header, increasing rebuild times.
Another is that your object files are larger.
Would that definition be in an optimal form for link-time symbol resolution of that particular function?
IF you define the function in the header (and make it inline), the compiler may choose to inline it into some (or all) of the call sites. No LTO required.
If you don't, the compiler will not be able to perform such inlining, unless you use LTO.
1 Unless you know all types the template is instantiated with and provide explicit instantiation for all of them.
|
70,406,035 | 70,406,836 | Why don't C++ error messages describe the actual problem in the code? | Why do the Visual Studio error logs show the things caused by some error, rather than the error itself? I often find the error messages to be useless and meaningless.
When I make a mistake, like for example a circular dependency, it throws a bunch of errors like
syntax error: missing ';' instead of something like circular dependency detected.
When I forget to include some header and use it in my code, for example the std::map, it only says 'map' is not a member of 'std'
It never shows you what's actually wrong, it only shows the symptoms. I know that sometimes you can clearly see what's wrong based only on that, but I don't want to spend time figuring out what's wrong. I just want to fix it as soon as possible.
Why can't it be like Python with Pycharm IDE which actually shows you the actual error?
| Even though this question might be considered out of topic, I'll attempt to give an answer to make it clear why one might find the experssed opinion (useless and meaningless) as "unfair".
Firstly this is not a Visual studio thing. If you've used other C++ compilers (gcc/clang/intel compiler) you'll notice the errors are pretty similar. Even though they might seem "useless", a little experience goes a long way. Not only are the errors precise, exact and reproducible, but they follow a standard specification and adhere to the formal description of the language.
Secondly we have to draw a line when comparing C++ to Python. C++ is a compiled language meaning that prior to creating an executable the entirety of your code must be written according to the language rules. This means that a runtime branch is checked even if it's not executed. Python on the other hand is an interpreted language. This means that it verifies code on the fly (having richer information on the execution context) so the following code will probably run fine:
def main():
a = []
a.append(1)
print(a)
# return 9'999 out of 10'000 times
a.shoot_foot(2) # list object has no attribute 'shoot_foot'
if __name__ == '__main__':
main()
This comes with the price that an error (not even calling this a bug since it violates language rules) may remain hidden and manifest in production.
Thirdly C++ is a strongly typed language. This means that types are statically checked, at the price of requiring you to be correct about them. Unlike the dynamically typed Python the type of an object cannot be modified at runtime which means increased type safety at the price of "being careful" when programming. It's a JS vs TS kind of thing, and people get accustomed to different styles; for me the lack of type safety is the thing I miss the most when working with Python. This power comes at the price of some of the most intricate error messages when doing type checking.
Lastly C++ is actively evolving towards improving error messages, making them more informative and shorter. This is not an easy task but features like concepts allow programmers to be explicit on the restrictions they impose to the type sytem. Additionally defensive programming techniques like static assertions can introduce a "fail switch" that stops compilation early resulting in less errors and keeping only the information about the offensive code.
|
70,406,647 | 70,406,667 | Using pointers in Class Templates with Subclasses | I have a problem with using pointers with Class templates. I can't properly access vv from the B subclass if 'vv' stores pointers to vectors; if I simply store vectors it works. But what I'm trying to do requires me to store pointers. I honestly have no idea what I'm doing wrong so here is the code:
template<typename T>
class A{
public:
std::vector<std::vector<T>*> vv;
void add(std::vector<T> new_vec)
{
vv.push_back(&new_vec);
}
virtual void print(){}
virtual ~A(){}
};
template<typename T>
class B : public A<T>{
public:
void print() override{
std::cout << this->vv[0]->at(0) << std::endl;
}
};
int main(){
int i = 10;
std::vector<int> v;
v.push_back(i);
A <int>*a = new B<int>();
a->add(v);
a->print();
return 0;
}
a->print() prints 0 instead of 10. Also I can't change what is inside main().
I would be very thankful for some help!
| Here:
void add(std::vector<T> new_vec)
{
vv.push_back(&new_vec);
}
You store a pointer to the local argument new_vec in vv. That local copy will only live till the method returns. Hence the pointers in the vector are useless. Dereferencing them later invokes undefined behavior. If you really want to store pointers you should pass a pointer (or reference) to add. Though, you should rather use smart pointers.
|
70,406,684 | 70,406,734 | Check whether the first row is filled | I have a matrix, and I want to check whether the first row is filled with "0" or "x"'s.
In my case that means that it's not "-"(empty).
The code below works only for each element of the board but I want it to check for the entire row at once.
bool checkBoardFull(string board[N][N], int n) {
for (int i = 0; i < n; i++) {
if (board[0][i] != "-") {
return false;
}
}
return true;
}
| Modify the method to not return within the loop:
bool checkBoardFull(string board[N][N], int n) {
bool full = true;
for (int i = 0; i < n; i++) {
if (board[0][i] == "-") {
full = false;
break;
}
}
return full;
}
Or, if you don't want that extra variable:
bool checkBoardFull(string board[N][N], int n) {
for (int i = 0; i < n; i++) {
if (board[0][i] == "-") {
return false;
}
}
return true;
}
|
70,406,941 | 70,406,987 | Function with parameter pack with sizeof ... (args) == 0 as base case doesn't compile | Here's the code of my function:
#include <iostream>
#include <type_traits>
#include <algorithm>
template <typename Head, typename ... Args>
std::common_type_t<Head, Args...> mx(Head n, Args ... args)
{
if (sizeof ... (args) == 0)
return n;
else
return std::max(n, mx(args ...));
}
int main()
{
std::cout << mx(3, 4, 5);
}
I got compile errors:
main.cpp: In instantiation of 'std::common_type_t<Head, Args ...>
mx(Head, Args ...) [with Head = int; Args = {};
std::common_type_t<Head, Args ...> = int]': main.cpp:11:24:
recursively required from 'std::common_type_t<Head, Args ...> mx(Head,
Args ...) [with Head = int; Args = {int}; std::common_type_t<Head,
Args ...> = int]' main.cpp:11:24: required from
'std::common_type_t<Head, Args ...> mx(Head, Args ...) [with Head =
int; Args = {int, int}; std::common_type_t<Head, Args ...> = int]'
main.cpp:16:25: required from here main.cpp:11:24: error: no
matching function for call to 'mx()' 11 | return std::max(n,
mx(args ...));
| ~~^~~~~~~~~~ main.cpp:6:35: note: candidate: 'template<class Head, class ... Args>
std::common_type_t<Head, Args ...> mx(Head, Args ...)'
6 | std::common_type_t<Head, Args...> mx(Head n, Args ... args)
| ^~ main.cpp:6:35: note: template argument deduction/substitution failed: main.cpp:11:24: note:
candidate expects at least 1 argument, 0 provided 11 | return
std::max(n, mx(args ...));
| ~~^~~~~~~~~~
Of course I can write this more properly, like this:
template <typename Head>
std::common_type_t<Head> mx(Head n)
{
return n;
}
template <typename Head, typename ... Args>
std::common_type_t<Head, Args...> mx(Head n, Args ... args)
{
return std::max(n, mx(args ...));
}
But still, I don't understand why my first option doesn't work. Judging by errors, it somehow tries to call recursive version of function even if there's no arguments in parameter pack. But that does not make any sense to me since I considered this case. What's the problem and can I fix it?
| Even if
if (sizeof ... (args) == 0)
the entire function must be well-formed C++.
return std::max(n, mx(args ...));
This still must be valid C++, even if won't get executed. If, outside of template context, you have an if (1), the else part must still be valid C++, you can't just throw randomly-generated gibberish in there, and this is the same thing. And when sizeof...(args) is 0 the function call becomes mx() and that, of course, has no valid overload.
What you want to do, instead, is use if constexpr instead of your garden-variety if.
if constexpr (sizeof ... (args) == 0)
|
70,407,273 | 70,409,094 | Merge 2 c++ functions | So I have two codes, one to swap the diagonals of a matrix, and the second is to square root of the moved numbers.
How can I merge these two codes together so that I have an output matrix with interchanged diagonals and squareddiagonals at the same time?
This is the first code - swaps diagonals
#include<bits/stdc++.h>
using namespace std;
#define N 3
// Function to interchange diagonals
void interchangeDiagonals(int array[][N])
{
// swap elements of diagonal
for (int i = 0; i < N; ++i)
if (i != N / 2)
swap(array[i][i], array[i][N - i - 1]);
for (int i = 0; i < N; ++i)
{
for (int j = 0; j < N; ++j)
cout<<" "<< array[i][j];
cout<<endl;
}
}
int main()
{
int array[N][N] = {1, 2, 3,
4, 5, 6,
7, 8, 9};
interchangeDiagonals(array);
return 0;
}
This is the second code - squares the diagonals
// Simple CPP program to print squares of
// diagonal elements.
#include <iostream>
using namespace std;
#define MAX 100
// function of diagonal square
void diagonalsquare(int mat[][MAX], int row,
int column)
{
// This loop is for finding square of first
// diagonal elements
cout << "Diagonal one : ";
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
// if this condition will become true
// then we will get diagonal element
if (i == j)
// printing square of diagonal element
cout << mat[i][j] * mat[i][j] << " ";
}
// This loop is for finding square of second
// side of diagonal elements
cout << " \n\nDiagonal two : ";
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
// if this condition will become true
// then we will get second side diagonal
// element
if (i + j == column - 1)
// printing square of diagonal element
cout << mat[i][j] * mat[i][j] << " ";
}
}
// Driver code
int main()
{
int mat[][MAX] = { { 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 } };
diagonalsquare(mat, 3, 3);
return 0;
}
| Define and declare the two functions interchangeDiagonals and diagonalsquare and call them in the required order in the main function like this
#include<bits/stdc++.h>
using namespace std;
#define N 3
#define MAX 100
// Function to interchange diagonals
void interchangeDiagonals(int array[][N])
{
// swap elements of diagonal
for (int i = 0; i < N; ++i)
if (i != N / 2)
swap(array[i][i], array[i][N - i - 1]);
for (int i = 0; i < N; ++i)
{
for (int j = 0; j < N; ++j)
cout<<" "<< array[i][j];
cout<<endl;
}
}
// function of diagonal square
void diagonalsquare(int mat[][3], int row, int column)
{
// This loop is for finding square of first
// diagonal elements
cout << "Diagonal one : ";
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
// if this condition will become true, then we will get diagonal element
if (i == j)
// printing square of diagonal element
cout << mat[i][j] * mat[i][j] << " ";
}
// This loop is for finding square of second side of diagonal elements
cout << " \n\nDiagonal two : ";
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
// if this condition will become true, then we will get second side diagonal element
if (i + j == column - 1)
// printing square of diagonal element
cout << mat[i][j] * mat[i][j] << " ";
}
}
int main()
{
int array[N][N] = {1, 2, 3,
4, 5, 6,
7, 8, 9};
interchangeDiagonals(array);
diagonalsquare(array, 3, 3);
return 0;
}
|
70,407,696 | 70,407,902 | How to access a 16 bits variable as two 8 bits variables ? And two 8 bits variables as one 16 bit variable | I am using C++17.
Let's imagine I have two variables a and b. These variables are of type uint8_t. I would like to be able to access them as uint8_t but also as uint16_t.
For example :
#include <memory>
int main()
{
uint8_t a = 0xFF;
uint8_t b = 0x00;
uint16_t ab; // Should be 0xFF00
}
I thought that using an array would be a good solution, as the two variable should be next to each other in memory. So I did this :
#include <memory>
int main()
{
uint8_t data[] = {0xFF, 0x00};
uint8_t * a = data;
uint8_t * b = data + sizeof(uint8_t);
uint16_t * ab = reinterpret_cast<uint16_t*>(data);
std::cout << std::hex << (int) *a << "\n";
std::cout << std::hex << (int) *b << "\n";
std::cout << std::hex << (int) *ab << "\n";
}
Output:
ff
0
ff
But I would expect :
ff
0
ff00
Can you explain what I am doing wrong here, any red flags or better ways of doing this ?
Thanks !
| There are a few other ways to convert between two 8- and one 16-bit value.
But be aware that the results of every solution which directly addresses a single byte in the 16-bit value depend on the byte order of the machine executing it. Intel, for example, uses 'little endian' where the least significant bits are stored first. Other machines may use 'big endian' and store the most significant bits first.
use bitshift and or to calculate the 16-bit value
const uint8_t a = 0xff;
const uint8_t b = 0x00;
const uint16_t ab = a | (b << 8); // works because b is promoted to int before being shifted
use bitshift and and to calculate the 8-bit values
const uint16_t ab = 0xff;
const uint8_t a = ab & 0xff;
const uint8_t b = ab >> 8;
directly address the bytes of the word
uint16_t ab;
auto& a = reinterpret_cast<uint8_t*>(&ab)[0];
auto& b = reinterpret_cast<uint8_t*>(&ab)[1];
using a union
This is explicitly not allowed by the standard (but also done everywhere)
Declare the following union:
union conv
{
struct {
uint8_t a, b;
};
uint16_t ab;
};
You now can use it for combining two 8 bit values into a single 16 bit value:
conv c;
c.a = 0xFF;
c.b = 0x00;
std::cout << c.ab << std::endl;
On Intel machines this will output 255 (0xff) because Intel uses "little endian" where the least significant bits are stored first. So a is the low byte of ab and b is the high byte.
If you redefine the union as
union conv
{
struct {
uint8_t b, a;
};
uint16_t ab;
};
The example above would output 65280 (0xff00) on Intel machines because now b represents the least significat 8 bits of ab and a represents the most significant.
Combining unions and bitfields, you can also access each single bit of the 16-bit value:
union bitconv
{
struct {
uint16_t
b0 : 1, b1 : 1, b2 : 1, b3 : 1, b4 : 1, b5 : 1, b6 : 1, b7 : 1,
b8 : 1, b9 : 1, b10 : 1, b11 : 1, b12 : 1, b13 : 1, b14 : 1, b15 : 1;
};
uint16_t word;
};
|
70,408,561 | 70,408,929 | How to call qt_sequence_no_mnemonics? | With regards to qt_sequence_no_mnemonics(), the qt documentation says "This function is not declared in any of Qt's header files. To use it in your application, declare the function prototype before calling it."
But what does that mean? I only see this function declared in a cpp file that is not distributed. How do I declare that function, so that I can call it?
When I call it, is it on an instance of QKeySequence? Is it somehow static? Can someone help me understand what is meant by that documentation?
File here: https://code.woboq.org/qt5/qtbase/src/gui/kernel/qkeysequence.cpp.html
edit 1: I tried removing every import of QKeySequence, and walling that off behind a new file that does this:
struct Configure
{
Configure()
{
// Qt::qt_set_sequence_auto_mnemonic( false );
// QKeySequence::qt_set_sequence_auto_mnemonic( false );
qt_set_sequence_auto_mnemonic( false );
}
};
Configure configure;
But that did not result in the removal of the shortcut-conflicts created by the global menus. The MenuBar menus still have "mnemonics" defined, and they still break the application.
FYI - I am trying to modify KDevelop, not writing my own application. I can post links to KDevelop files, but I have made no other changes.
| You can can declare the function by putting this near the top of your .cpp file (maybe just after the #includes):
extern void qt_set_sequence_auto_mnemonic(bool);
... that will tell your compiler that the function exists, so that code later in that same .cpp file can call it without producing a compile-time error, e.g.:
int main(int argc, char ** argv)
{
qt_set_sequence_auto_mnemonic(true);
[...]
}
|
70,408,591 | 70,408,615 | Is there a Standard Untokenize Templated Type? | Is there a standard type to untokenize a type? It'd probably be implemented as so:
template<class T>
using untokenize = T;
This way I can perform the following cast using an overloaded operator:
struct x {
int y;
operator int&() {
return y;
}
};
x a;
// int&(a); // doesn't work
// (int&)(a); // not the same thing
untokenize<int&>(a); // works great
Or is there another, more standard way to achieve my goal of avoiding a c-style cast in favor of a function-style cast?
| It would be more idiomatic to use the correct "named cast" in general. Here, static_cast is appropriate:
static_cast<int&>(a);
That said, there is a standard template that works the same as your other approach, std::type_identity, but only as of C++20:
std::type_identity_t<int&>(a);
|
70,408,799 | 70,409,331 | OpenGL: glColor3f() and glVertex3f() with shader | Can I use glColor3f(), glVertex3f() or other API functions with shader? I wrote a shader for draw a colorful cube and it works fine.
My vertex shader and fragment shader look like this
#vertext shader
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aColor;
uniform mat4 model;
uniform mat4 view;
uniform mat4 proj;
out vec4 vertexColor;
void main()
{
gl_Position = proj * view * model * vec4(aPos.x, aPos.y, aPos.z, 1.0);
vertexColor = vec4(aColor, 1.0);
};
#fragment shader
#version 330 core
in vec4 vertexColor;
out vec4 FragColor;
void main(){
FragColor = vertexColor;
};
Noe, I try to use gl functions along with my colorful cube. Let's say I have some draw code like this.
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0, 0, -1, 0, 0, 0, 0, 1, 0);
glColor3f(1.0, 0.0, 0.0);
glLineWidth(3);
glBegin(GL_LINES);
glVertex3f(-1, -1, 0);
glVertex3f(1, 1, 0);
Since I used glUseProgram() to use my own shader. The above gl functions doesn't seems to work as expect (coordinates and color are both wrong). How does function like glVertex3f() pass vertex to shader? And how do the shaders should look like when using gl function to draw?
| The glBegin()/glEnd() directives are used in compatibility profile of OpenGL as opposed to core profile which is more modern. However you are compiling your shaders in core profile using the line #version 330 core.
Even if the shaders are not compiled in the core profile, I don't think they'll work since I believe you can't pass vertex attributes with location indices (aPos, aColor) using glVertex3f.
I would recommend using the core Opengl for render calls. That means you should not use you glBegin()...glEnd() and pass vertex coordinates in every render cycle. Instead, the cube coordinates to GPU before-hand and let your shaders access those values:
Create VertexBuffer objects using glGenBuffers().
Store your vertex data in the buffer using glBufferData().
Extract the aPos and aColor attributes from the buffer and assign them indices of 0 and 1 respectively using glVertexAttribPointer().
This should work and no changes to your shader code would be necessary.
EDIT:
For rendering in compatibility profile, the data provided within glBegin/glEnd is ran through a default shader pipeline. You can't customize the pipeline using explicit shader code (like you did now), but you can modify some basic things in the pipeline (such as color, phong lighting, texture). So if you want to get the results your shader code represents, you need to do something like this:
glBegin(GL_TRIANGLES);
glColor3f(1.0f, 0.0f, 0.0f); glVertex3f(-1.0f,-0.25f,0.0f); //First vertex
glColor3f(0.0f, 1.0f, 0.0f); glVertex3f(-0.5f,-0.25f,0.0f); // Second vertex
...
glEnd();
This way of sending full object details during render call is called Immediate mode. For adding lighting, you need glEnable(GL_LIGHTING), add normal info for each vertex and a bunch of other stuff.
If you use core profile, you can define your own shaders but you can't use Immediate mode during the render calls. You need to pass the vertex data before your rendering loop. Basically glBegin,glEnd,'glVertex3f' are not supported in core profile and you need to use the 3 points above to store the data in your graphics device before your render anything (which is done using glDrawArrays()). This tutorial provides a good introduction to these concepts and can help you draw the cube you want using core profile.
|
70,409,038 | 70,409,349 | Difference between structural type and type returned from contexpr function | I was playing with C++ and got confused by this:
cppreference.com says that a non-type template parameter must be a structural type and that a literal class type is an example of a structural type. Then it says that “Literal types are the types of constexpr variables and they can be constructed, manipulated, and returned from constexpr functions” (emphasis mine). (In fact the return type of a constexpr function must be a literal type.)
So my understanding was can be returned from constexpr function implies is a literal type implies is a structural type implies can be used as a non-type template parameter.
But it appears that std::optional can be returned from a constexpr function (bar below) but cannot be used as a non-type template parameter (foo immediately below). What's going on?
#include <optional>
template <std::optional<int> Z> int foo(int x) { return x; }
int main() { return foo<std::optional{0}>(0); }
This gives the compiler errors (GCC and clang resp.)
<source>:2:30: error: 'std::optional' is not a valid type for a
template non-type parameter because it is not structural
<source>:2:30: error: type 'std::optional' of non-type template parameter
is not a structural type
But
#include <optional>
constexpr std::optional<int> bar() { return std::optional{0}; }
int main() { return *bar(); }
compiles.
| C++20 allows classes as non-type template parameters if they are:
a literal class type with the following properties:
all base classes and non-static data members are public and non-mutable and
the types of all base classes and non-static data members are structural types or (possibly multi-dimensional) array thereof.
std::optional is a literal class type, but it has non-public data members, so is not allowed as a non-type template parameter.
You could make your own optional-like class with only public data members, then it would be usable as a template parameter.
|
70,409,252 | 70,409,892 | How do I fix Visual Studio 2022 Error E1696 for WinRT | When I generate a new WinRT project in Visual Studio 2022 I get Error E1696 cannot open source file "winrt/Windows.Foundation.h" yet when I look at the Include directories the files do exist at the correct location.
| This is an artifact of the way C++/WinRT works. While the header files do exist in the Windows SDK, that's not where the project goes looking for them. Instead, they are generated on the fly into the source tree under the Generated Files directory.
So to fix the issue you will have to compile a newly created project at least once. This by itself isn't sufficient for IntelliSense to pick up the changes in environment. To help IntelliSense out you're going to have to right-click into the source editor, and select Rescan -> Rescan File.
Once that is done, all the IntelliSense errors go away, including E1696.
Historic background
It's easy to get confused why the C++/WinRT header files are part of the Windows SDK, yet the C++/WinRT VSIX templates aren't using them. A look back at C++/WinRT's history helps explain how we landed in this situation:
Initially, the code generator responsible for producing the language projection header files (modern.exe, later renamed to cppwinrt.exe) wasn't published. Instead, the header files were generated by Kenny Kerr, and published through his modern repo.
Publishing the language projection header files through a GitHub repository carried over into the cppwinrt repo owned by Microsoft, and continued to be the deployment channel for several versions of Windows.
This wasn't exactly convenient for developers, so with the release of the Windows SDK for Windows 10, version 1803 (10.0.17134.0) the headers got added to the SDK (including the code generator). This worked, but wasn't an ideal situation either, as the release cycle of C++/WinRT was now tied to that of the Windows SDK, roughly 6 months.
Decoupling the release cycles was crucial in allowing C++/WinRT to progress at its own pace, shipping frequent updates with improvements and bug fixes. This was enabled by deploying the code generator as part of a NuGet package that the C++/WinRT project templates reference. The MSBuild project drives generation of the language projection headers, and clients can freely decide, which version of the C++/WinRT library they wish to use, controlled through the NuGet package reference.
This is how things work today, but the language projection headers can no longer be yanked from the Windows SDK. They were published, with clients relying on finding them there, and expecting an SDK update to not break their builds. And this is why the Windows SDK contains header files you aren't meant to be using.
|
70,409,316 | 70,409,798 | what do you mean by base class reference or derived class reference? | I am confused about base class reference and derived class reference in the context of upcasting and downcasting.
In the following code, what is the use of &ref? In the reference, it was marked as a base class reference, to which a derived class obj was assigned.
What is the concept behind this?
#include <iostream>
using namespace std;
class Base
{
public:
void disp()
{
cout << " It is the Super function of the Base class ";
}
};
class derive : public Base
{
public:
void disp()
{
cout << "\n It is the derive class function ";
}
};
int main ()
{
// create base class pointer
Base *ptr;
derive obj; // create object of derive class
ptr = &obj; // assign the obj address to ptr variable
// create base class's reference
Base &ref = obj;
// Or
// get disp() function using pointer variable
ptr->disp();
return 0;
}
| Even though it is not clear what you're asking, i will try to clear some basics regarding this topic.
First, a reference refers to some other object. A reference is not an object by itself. So lets looks at some examples:
int n = 10;
int &r = n; // Here r is a reference to an int object
Similarly in your code snippet, when you wrote:
derive obj; //obj is an object of type derive
Base &ref = obj; // ref is bound to the Base part of derive
Base *ptr = &obj; // ptr points to the Base part of derive
In the above example, there are 2 important things to note:
Because a derived object contains subparts corresponding to its base class(es), we can use an object of a derived type as if it were an object of its base type(s). In particular, we can bind a base-class reference or pointer to the base-class part of a derived object as done above. This conversion is called derived-to-base conversion.
The static type of object named ptr is Base*. While the dynamic type of the same object ptr is derive*. So the static and dynamic type differs.
Also, note that we are able/allowed to write:
Base *ptr = &obj;
because as $11.2/5 states -
If a base class is accessible, one can implicitly convert a pointer to a derived class to a pointer to that base class.
Now coming back to your question:
what is the use of &ref?
class Base
{
public:
virtual void disp() //VIRTUAL kewword USED HERE
{
cout << " It is the Super function of the Base class ";
}
};
If in your code snippet, the method disp() was virtual as shown in the above modified snippet, then we could've used ref and ptr to call the method disp() of the derive class. This is because:
According to virtual function documentation
a virtual function is a member function you may redefine for other derived classes, and can ensure that the compiler will call the redefined virtual function for an object of the corresponding derived class, even if you call that function with a pointer or reference to a base class of the object.
So when we write:
ref.disp(); //this calls the derive class method disp() at runtime
ptr->disp(); //this calls the derive class method disp() at runtime
The result of the above is that the derive class' function named disp is called at run-time and we see It is the derive class function printed on the console.
So basically the use is that we can decide at runtime which method(whether Base's or derive's) to call.
Check out the program's output here.
|
70,409,358 | 70,409,832 | Can I make error when diamond inheritance with template? | I want to cause an error when inheritance is duplicated. Here is how I found it.
#include <utility>
class Person {};
class Man : public Person {};
class Woman : public Person {};
template <typename... Types>
class merge_class : public Types... {};
template <typename... Types>
struct condition
{
using merge = merge_class<Types...>;
using type = std::enable_if<
std::is_convertible<merge, Person>::value // condition
, merge>::type;
};
class BummooKim : public condition<Man>::type {};
class Daniel : public condition<Woman>::type {};
//class Unkown : public condition<Man, Woman>::type {}; // There is an error in the declaration.
However, I found that this way cannot be used if there is a non-default constructor.
I was wondering if there is a keyword to indicate that it must be single-inherited.
If c++ doesn`t support 'keyword', I want another way.
example
class OtherWay : public condition<Man, Other>::type
{
OtherWay() : Man() {}
};
| What you are running into is called diamond inheritance (https://www.makeuseof.com/what-is-diamond-problem-in-cpp/) and IMO is best avoided except for "interfaces". I prefer using composition of implementations also known as the mixin pattern (which in turn uses CRTP, the curiously recursing template pattern). In this pattern you make implementations for seperate capabilities (e.g. in the following examples a man can shout and a woman can smile and all persons can say hi.).
Detecting multiple inheritance at compile time is not possible (a feature in c++ that might have enabled it never made it through the standard committee).
I show a way to at least detect, at compile time, that a person cannot be a man and a woman at the same time (at least in this example).
In MSVC this program will give the following compilation error :
Error C2338 Being both a Man and a Woman, is not correct in this program
#include <iostream>
#include <string>
//-----------------------------------------------------------------------------
// multiple inheritance from interfaces (abstract base classes is fine)
// class to introduce a concept of an interface
// and set all the constructors/destructors default behavior.
class Interface
{
public:
virtual ~Interface() = default;
protected:
Interface() = default; // protected constructor, avoids accidental instantiation
};
//-----------------------------------------------------------------------------
// for each aspect/capability of a person define a seperate interface
// this will also allow client code to cast an object to either of those
// interfaces to check if functionality is available
class PersonItf :
public Interface
{
public:
virtual void SayHi() const = 0;
};
//-----------------------------------------------------------------------------
// A man can shout
class ManItf :
public Interface
{
public:
virtual void Shout() const = 0;
};
//-----------------------------------------------------------------------------
// A woman can smile
class WomanItf :
public Interface
{
public:
virtual void Smile() const = 0;
};
//-----------------------------------------------------------------------------
// mixin classes for reusable code
template<typename base_t>
class PersonImpl :
public PersonItf
{
public:
void SayHi() const override
{
std::cout << "Hi!\n";
}
};
template<typename base_t>
class ManImpl :
public ManItf
{
public:
void Shout() const override
{
std::cout << "Yohoohoooo!\n";
};
};
template<typename base_t>
class WomanImpl:
public WomanItf
{
public:
void Smile() const override
{
std::cout << "Smile!\n";
};
};
//-----------------------------------------------------------------------------
// now we can group capabilities together in classes
//
class Man :
public ManImpl<Man>
{
};
class Woman :
public WomanImpl<Woman>
{
};
class ManAndWoman :
public ManImpl<ManAndWoman>,
public WomanImpl<ManAndWoman>
{
};
//-----------------------------------------------------------------------------
// this Person class will check validity of the composition
// at compile time.
template<typename type_t>
struct Person :
public PersonImpl<type_t>,
public type_t
{
static_assert(!(std::is_base_of_v<WomanItf, type_t>&& std::is_base_of_v<ManItf, type_t>), "Being both a Man and a Woman is not correct in this program\n");
};
//-----------------------------------------------------------------------------
class Daniel : public Person<ManAndWoman> {};
class Santa : public Person<Man> {};
int main()
{
Daniel daniel;
Santa santa;
daniel.SayHi();
santa.Shout();
return 0;
}
|
70,409,489 | 70,409,535 | Passing the const-qualified object to the 'std::move' | By doing some code analysis in PVS-Studio, it gave me some warning messages.
I have the following statement in a header file:
constexpr int MIN_ALLOWED_Y { 0 };
And in a source file:
std::make_pair<const int, const int>( std::move( MIN_ALLOWED_Y ), std::move( MAX_ALLOWED_Y ) )
In the above expression, I used std::move to cast MIN_ALLOWED_Y to an xvalue because I thought std::make_pair only accepts rvalues;
// from https://en.cppreference.com/w/cpp/utility/pair/make_pair
template< class T1, class T2 >
constexpr std::pair<V1,V2> make_pair( T1&& t, T2&& u );
But I get warning messages like:
V833 Passing the const-qualified object 'MIN_ALLOWED_Y' to the 'std::move' function disables move semantics.
Is this a valid warning? If so then what should I do? Should I remove the std::move (maybe it's redundant in this case?)?
A better question would be where not to use std::move?
| Your code:
std::make_pair<const int, const int>( std::move( MIN_ALLOWED_Y ), std::move( MAX_ALLOWED_Y ) )
Is overly complicated. Not only are the moves pointless as PVS Studio told you, but using make_pair when explicitly specifying the types is pointless. You can simplify to:
std::pair<const int, const int>( MIN_ALLOWED_Y, MAX_ALLOWED_Y )
Which does the same thing without excess ceremony.
|
70,409,548 | 70,409,670 | How to add user defined variable leading zeros in C sprintf? | I am working on a program in which I need to add leading zero for 3 numbers
So the code looks like this
#include <iostream>
using namespace std;
// Check Examples
//Compiler version g++ 6.3.0
int main()
{
long int num =5;
char CNum[10];
sprintf(CNum,"%03ld",num) ;
std::cout << CNum;
return 0;
}
// Outputs 005
Now let's define the number of leading zeros in an integer variable named
int blank = 3
After that the code should look like this
#include <iostream>
using namespace std;
// Check Examples
//Compiler version g++ 6.3.0
int main()
{
int blank = 3;
long int num =5;
char CNum[10];
sprintf(CNum,"%03ld",num) ;
std::cout << CNum;
return 0;
}
Then I edited the sprintf arguments like this
sprintf(CNum,"%0%dld",blank,num);
And this outputs
%dld
Instead of
005
Now, my main questions are,
Can I add user variable defined leading zeroes like this in sprintf?
If Yes, how can I make my code do this?
If No, is there any other way to perform the same action to get desired output?
Thank you, looking forward to your kind replies...
| To make the width dynamic (not hard-coded in the format string), you write it like this:
sprintf(CNum,"%0*ld",blank,num);
Instead of a hard-coded width 3 as in "%03ld", the asterisk indicates that the next argument (which must be of type int) is to be taken as the width.
|
70,410,542 | 70,410,566 | Can one delete a function returning an incomplete type in C++? | In the following example function f() returning incomplete type A is marked as deleted:
struct A;
A f() = delete;
It is accepted by GCC, but not in Clang, which complains:
error: incomplete result type 'A' in function definition
Demo: https://gcc.godbolt.org/z/937PEz1h3
Which compiler is right here according to the standard?
| Clang is wrong.
[dcl.fct.def.general]
2 The type of a parameter or the return type for a function definition shall not be a (possibly cv-qualified) class type that is incomplete or abstract within the function body unless the function is deleted ([dcl.fct.def.delete]).
That's pretty clear I think. A deleted definition allows for an incomplete class type. It's not like the function can actually be called in a well-formed program, or the body is actually using the incomplete type in some way. The function is a placeholder to signify an invalid result to overload resolution.
Granted, the parameter types are more interesting in the case of actual overload resolution (and the return type can be anything), but there is no reason to restrict the return type into being complete here either.
|
70,410,689 | 70,410,870 | i am trying to send a 2d vector by reference but seems like its not working for pretty much same approach | 64.minimum-path-sum.cpp: In function ‘int main()’:
64.minimum-path-sum.cpp:67:23: error: cannot bind non-const lvalue reference of type ‘std::vector<std::vector<int> >&’ to an rvalue of type ‘std::vector<std::vector<int> >’
67 | if(minPathSum(vector<vector<int>> {{1 , 2, 3}}) == 12)cout << "ACC\n";
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
64.minimum-path-sum.cpp:57:46: note: initializing argument 1 of ‘int minPathSum(std::vector<std::vector<int> >&)’
57 | int minPathSum(vector<vector<int>> & grid) {
|
~~~~~~~~~~~~~~~~~~~~~~^~~~
#include<bits/stdc++.h>
#include "stringTo2dVector.h"
using namespace std;
int main(){
vector<vector<int>> c{{1 , 2, 3}};
if(minPathSum(c) == 12)cout << "ACC\n"; //No ERROR
else cout << "WA\n";
if(minPathSum(vector<vector<int>> {{1 , 2, 3}}) == 12)cout << "ACC\n"; // ERROR
else cout << "WA\n";
}
What is the difference between these 2 approach of passing a 2d vector as argument ??
| You are calling the function minPathSum creating a temporary object of the type std::vector<vector<int>> using a braced init list.
So the compiler issues an error message that you are trying to bind a temporary object with a non-coonstant lvalue reference.
Just declare the function parameter with the qualifier const
int minPathSum( const vector<vector<int>> & grid);
|
70,410,865 | 70,413,274 | Inherited struct members inaccessible during aggregate initialization | #include <vector>
#include <string>
struct BasePluginInfo
{
bool bHasGui, bIsSynth;
char cType;
std::string sCategory, sSdkVersion, sVendor, sVersion;
};
struct PluginClassInfo
{
std::string sName, sUid;
std::vector<std::string> vsParamNames;
};
struct ShellPluginInfo : BasePluginInfo
{
std::vector<PluginClassInfo> vciClasses;
};
When I do
int main() {
ShellPluginInfo
{
.bHasGui = true
};
}
The compiler complains that ShellPluginInfo has no field 'bHasGui'.
However this works:
int main() {
ShellPluginInfo info;
info.bHasGui = true;
}
| When aggregate initializing something with base classes, the base class acts like a member of the class, similar to if you had:
struct ShellPluginInfo {
BasePluginInfo __base_class_subobject;
std::vector<PluginClassInfo> vciClasses;
};
As such, the first clause in the initializer list will try to initialize it, and you have to write:
ShellPluginInfo{ // This initializer list initializes a ShellPluginInfo
{ .bHasGui = true; } // This initializer list initializes a BasePluginInfo
}
However, since this is not a designated initializer, you cannot use designated initializers for the rest of the members of the derived class. For example:
ShellPluginInfo{
{ // (note: doesn't have a designator)
.bHasGui = true,
.cType = 'a' // OK
},
.vciClasses = {} // ERROR: Can't mix designated and non-designated initializers
}
This proposal attempts to remedy that: https://wg21.link/p2287r1, making your original attempt valid. It has not been accepted yet though, but you may see it in C++23.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.