Menu
  • HOME
  • TAGS

Remove smallest non-unique value from vector

c++,algorithm,c++11,unique

(Am adding an additional answer, since 1) the focus of the first answer was using ready STL components, and 2) Howard Hinnant raised some interesting points since.) Thanks to Howard Hinnant for the principle of benchmarking the different approaches (as well as a very unique solution)! It has led to...

C++ why does SFINAE fail with only a class template parameter?

c++,templates,c++11,sfinae

SFINAE comes to us from [temp.deduct]/8, emphasis mine: If a substitution results in an invalid type or expression, type deduction fails. An invalid type or expression is one that would be ill-formed, with a diagnostic required, if written using the substituted arguments. [ Note: If no diagnostic is required, the...

Syntax help. Template operator() in template function object

c++,templates,c++11,functor

I don't think you can manually specify template arguments for operator overloads. However, you can write f.operator()<bool, char, long>(); ...

Simple thread/mutex test application is crashing

c++,multithreading,c++11,mutex,mingw-w64

workers.clear(); is not going to join all of the threads. Calling clear() will call the threads' deconstructors. std::thread::~thread will call std::terminate() if the thread is joinable(). Since you are calling clear() on the vector right after you create the vector the threads are still processing and are joinable. You have...

Spin locked stack and memory barriers (C++)

c++,multithreading,c++11,concurrency,memory-barriers

The acquiring of the lock already establishes the memory guarantees that you need. When a thread releases the lock it has to write to the atomic flag. This guarantees that when the next thread acquires the lock and sees the write to the flag, that the acquiring thread is guaranteed...

Template specialization with std::enable_if<>

c++,templates,c++11,template-specialization

You can't declare a function with one signature: template<typename UNSIGNED_TYPE> UNSIGNED_TYPE toUnsigned() const; and then define it with a different signature: template<typename UNSIGNED_TYPE, typename std::enable_if< std::numeric_limits<UNSIGNED_TYPE>::is_signed==false && (sizeof(UNSIGNED_TYPE) >= sizeof(UnsignedBox::box_type)), int>::type = 0 > UNSIGNED_TYPE UnsignedBox::toUnsigned() const; The first one there takes one template argument, the second one takes two...

Pointer not working anymore after second iteration

c++,c++11

After the feedback on the internal working of std::vector from Joachim Pileborg, I realised I needed on other container structure. With the structure std::forward_list I don't have the problem I've encounterd before.

C++ vector error C2036: 'int (*)[]' : unknown size

c++,templates,c++11,vector

Your problem comes from this line: unique_ptr<vector<int[]>> m_indices; You should use a stl container instead, in this case it could be a vector of vector Also, why would you need a unique_ptr in this case? vectors support move semantics and you could just have a vector<vector<int>> m_indices; An extra hint...

Why doesn't std::string contain a split() method? [on hold]

c++,string,c++11

You might be interested to read this: std::split(): An algorithm for splitting strings Splitting strings into substrings is a common task in most general-purpose programming languages, and C++ is no exception. When the need arises, programmers need to search for an existing solution or write one of their own. A...

Why is the common type of bool and int8_t an int32_t in C++?

c++,c++11,boolean,std

Short answer: integral promotion. In numerical arithmetic, small integral types (including bool, char, unsigned char, signed char, short, unsigned short, etc) are promoted to int if all the possible values fit in int, otherwise they are promoted to unsigned int. On most machines today, int32_t is the same as int....

std::vector::resize(size_type) requires CopyInsertable?

c++,c++11,language-lawyer

You are correct. It was a defect in C++11 that was fixed for C++14 by http://cplusplus.github.io/LWG/lwg-defects.html#2033 The current wording says: Effects: If sz < size(), erases the last size() - sz elements from the sequence. Otherwise, appends sz - size() default-inserted elements to the sequence. Requires: T shall be MoveInsertable...

can't understand variadic templates in c++

c++,templates,c++11,variadic-templates

A variadic expression can capture 0 arguments or more. Take for example the call print(1). Then T captures int and Types = {} - it captures no arguments. Thus the call print(args...); expands to print();, which is why you need a base case. You don't need the recursion at all....

Implicit use of initializer_list

c++,c++11,initializer-list

Your program is not ill-formed because <vector> is guaranteed to include <initializer_list> (the same is true for all standard library containers) §23.3.1 [sequences.general] Header <vector> synopsis #include <initializer_list> ... Searching the standard for #include <initializer_list> reveals the header is included along with the following headers <utility> <string> <array> <deque> <forward_list>...

c++ vector bubble sort

c++,c++11,vector,bubble-sort

You need to pass by reference; by making a copy, you sort a temporary copy, and then that's it; it disappears and the original is still unsorted, because, once again, you sorted only a temporary copy of the entire vector. So change vector<int> a to vector<int>& a. Here's the code,...

Finding all keys that correspond to same value in std::unordered_map

c++,c++11,stl,c++14

I think the "obvious" way is excellent: it is simple, short and easy to read. Another option is to use stl algorithms. What you need is transform_if algorithm so you can say: std::transform_if(std::begin(theMap), std::end(theMap), std::back_inserter(arrKeys), check_value, get_value); but there is no such in stl. What I can suggest is: std::vector<int>...

Win32 Message Pump and std::thread Used to Create OpenGL Context and Render

multithreading,winapi,opengl,c++11

A Win32 window is bound to the thread that creates it. Only that thread can receive and dispatch messages for the window, and only that thread can destroy the window. So, if you re-create the window inside of your worker thread, then that thread must take over responsibility for managing...

Alias the return type of a const overloaded function

c++,c++11,const,decltype

Yes, the first one uses the const overload and the second one the non-const one. That's because _t is const in the first case and non-const in the second one. Which one is used in the type alias depends on the type of data. Is it const? If so, the...

Error with stoi and debugged with gdb [closed]

c++,c++11,segmentation-fault,coredump

Yeah, I think you're doing something pretty silly. You probably compiled the first code, which doesn't have the std::cout statement, and you probably executed the compilation steps without -std=c++11 which would result in std::stoi not being included beecause std::stoi is from C++11 and onward. The result is still the old...

why sort function of STL is not working?

c++,c++11,stl

The error in line sort((lst+con)->begin(),(lst+con)->end(),fnct(con)); says In instantiation of 'void std::__sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = std::_List_iterator<int>; _Compare = __gnu_cxx::__ops::_Iter_comp_iter<sortg(std::list<int>*, int*)::fnct>]' Now, List is built as a doubly linked list (hence iteration in both directions) with its primary feature being the support for constant time insert and erase operations. But...

I think assigning JsonValue values to JsonValues might be very slow, in comparison to having a Value be a key

c++,json,c++11

Assuming that you are using JsonCpp. What you would want to do is something like: b["features"] = std::move(a); This would move-assign the Value rather than copy-assigning it. Unfortunately, that class does not declare a move-assignment operator and one will not be implicitly generated. Fortunately, that class defines a swap function...

How to re-write templated function to handle type deduction

c++,templates,c++11

The problem is a mismatch between the type of the Map and the key types. But I would fix it not by correcting the order of the parameters std::map argument, but by changing the definition to be more generic. template <typename MapType, typename KeyType> void searchInMapByKey(const MapType & Map, KeyType...

Why do the const accessors of std::string return a reference?

c++,c++11,stl,language-design,stdstring

Because the caller might want a reference to the char, that reflects any changes made to it through non-const avenues. std::string str = "hello"; char const& front_ref = static_cast<std::string const&>(str).front(); str[0] = 'x'; std::cout << front_ref; // prints x ...

namespace and extern 'C' compilation errors

c,c++11

The main problem seems to be, that you use c++ syntax in a .c file. C does not support namespaces! It does not make much sense to put a extern "C" function into an namespace. in C++ the compiler does something called 'name mangeling' it actually puts the name space...

construction of thread using lambda expression

multithreading,c++11,lambda,threadpool

ThreadPools constructor is using the emplace_back function of std::vector to construct a std::thread to the back of the workers_m variable. emplace_back differs from push_back in that it directly constructs the element type by forwarding the parameters passed to the constructor of the element type (std::thread). push_back, on the other hand,...

Calling variadic template function with no args failing

c++,c++11

You have to specify a version of the function without args: #include <iostream> template <typename... Args> void foo(Args&&... bargs, Args&&... aargs) { std::cout << "Hello with args" << std::endl; } void foo() { std::cout << "Hello without args" << std::endl; } int main() { foo<int, double>(1, 2.0, 3, 4.0); //OK...

C++ operator []

c++,c++11,operator-overloading

C++ does not easily allow distinction of appple[2] = X; y=apple[2]; The most common solution is to return a proxy object: struct AppleProxy { Security & obj; unsigned index; AppleProxy(Security &, unsigned) : ... {} operator double() // your getter { return obj.GetAt(index); } operator=(double rhs) { obj.SetAt(index, rhs); }...

std::move on a C++ class does not move all members?

c++,c++11,move

You create a variable foo Foo foo{"Hello",2.0f}; Then declare a vector std::vector<Foo> v; Then call push_back which invokes a copy of your Foo v.push_back(foo); std::cout << foo << std::endl; Then you std::move(foo), which invalidates your foo instance v.push_back(std::move(foo)); Trying to cout foo is now undefined behavior, as the internals are...

Why is my code failing to compile? (perfect forwarding and parameter packs)

c++,c++11,perfect-forwarding,variadic-parameter

When a template parameter (or parameter pack) is used in two deduced contexts, deduction is done independently for each and the result must match. This makes things like template<typename ...Args> void foo(B* b, void (B::*func)(Args...), Args&&... args) { /* ... */ } tricky to use at best, because Args is...

How to match one of multiple alternative patterns with C++11 regex [duplicate]

c++,regex,c++11

It looks like regex is not fully implemented in gcc version 4.8.2 but rather in later versions of gcc (i.e., version > 4.9.0). https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53631 In gcc version 4.9.0 works ok LIVE DEMO So I guess you'll have to upgrade to newer version of gcc....

Atomic/not-atomic mix, any guarantees?

c++,multithreading,c++11,atomic

As long as your used memory order is at least acquire/release (which is the default), you are guaranteed to see all updates (not just the ones to atomic variables) the writing thread did before setting the flag to true as soon as you can read the write. So yes, this...

Can't compile C++11 source using GCC 5.1 toolchain

c++,c++11,gcc5

You're not doing anything wrong. The library's source is missing an #include <memory>. This is simply an unfortunate error by the author of the library. It's surprisingly commonplace for people to rely on certain standard headers just so happening to include other standard headers on their particular implementation, without checking...

Insert std::string and shared pointer to object in map

c++,c++11,dictionary,singleton

Not sure which version of Visual Studio you are using, but at least Visual Studio 2013 seems fine with this: #include <map> #include <string> #include <memory> class House { public: House(const char* name); virtual ~House(); private: House(const House& copy) { } House& operator=(const House& assign) { } }; class Obj...

Transforming a two-variable std::function to a single-variable one

c++,c++11,lambda

In C++11 std::bind is essentially obsolete with introduction of lambdas. Here's an example of binding using a lambda. int add(int a, int b) {return a + b;} int main() { auto add2 = [](int a){ return add(a,2); }; return 0; } For reference concerning preference of lambdas over std::bind one...

Releasing memory with std::move()?

c++,c++11,move-semantics

std::move leaves the moved-from object in a valid but unspecified state. In particular it might stay exactly the way it was before, so while this might actually work with your implementation of the stl, it will certainly not work for all third-party containers. (And might break at any point in...

How can I simulate a nested function without lambda expressions in C++11?

c++,function,c++11,lambda,allegro

Simply put the image inside the visual_plot function and make it static: void visual_plot() { static Image img("sample.png"); x.draw(); // Problem. } This will initialize img the first time visual_plot is called, and only then. This will solve both the performance problem and the "it must be initialized after app.run()"...

Access to reference in member variable discards constness

c++,c++11,reference,compiler-errors,const

Yes, this is correct behaviour. The type of ref is Foo &. Adding const to a reference type1 does nothing—a reference is already immutable, anyway. It's like having a member int *p. In a const member function, its type is treated as int * const p, not as int const...

No match for 'operator=' in sort function

c++,c++11,g++,codeblocks

The sort method itself returns a void, so what you're trying to do is assigning string to void. Just write sort(begin(input), end(input)) instead. Update: Well, let's analyze the error message that your compiler gives: error: no match for 'operator=' in 'input = std::sort<__gnu_cxx::__normal_iterator<char*, std::basic_string<char> > > (std::begin<std::basic_string<char> >((* & input)),...

Why is initialization of enum class temporaries with arbitrary values allowed?

c++,c++11

Scoped enumeration types have an implicit underlying type of int, assuming no other underlying type is specified. All possible values of type int can be represented. 7.2p5: [...] For a scoped enumeration type, the underlying type is int if it is not explicitly specified. In both of these cases, the...

Is there a syntax for incomplete nested type without a forward declaration?

c++,c++11,nested,forward-declaration

No there isn't. However, you shouldn't need to avoid the forward declarations at all. This works: class Containing { class NestedInterface; typedef std::shared_ptr<NestedInterface> Ptr; class NestedObject { Ptr ptr_; //... }; class NestedInterface { // ... }; }; Sometimes cross-dependencies inside the classes might make this hard to do. In...

Is there a flat unsorted map/set implementation?

c++,c++11,boost,stl,containers

Something like this? template<class Key, class Value, template<class...>class Storage=std::vector> struct flat_map { struct kv { Key k; Value v; template<class K, class V> kv( K&& kin, V&& vin ):k(std::forward<K>(kin)), v(std::forward<V>(vin)){} }; using storage_t = Storage<kv>; storage_t storage; // TODO: adl upgrade using iterator=decltype(std::begin(std::declval<storage_t&>())); using const_iterator=decltype(std::begin(std::declval<const storage_t&>())); //...

Setting the content of a std::stringstream with str(const char*) has strange consequences

c++,c++11,stringstream

You forgot to set flag mode: std::ios_base::out. This will work: std::stringstream ssb(std::ios_base::out | std::ios_base::ate); ssb.str("Setting string"); std::cout << ssb.str() << std::endl; ssb << " adding to string"; std::cout << ssb.str() << std::endl; Output: Setting string Setting string adding to string ...

std::push_heap and std::pop_heap with MoveConstructible objects

c++,c++11,stl,heap,move-semantics

Never mark your copy constructor or move constructor as explicit. It isn't illegal. It is just unusual enough to be confusing. There is no benefit to it, and only downside. The explicit on your move constructor is the cause of this error....

Passing something as this argument discards qualifiers

c++,c++11

There are no operator[] of std::map which is const, you have to use at or find: template<> struct Record::getDispatcher<std::string> { static std::string impl(Record const& rec, std::string& const field) { return rec.fieldValues_.at(field); // throw if field is not in map. } }; or template<> struct Record::getDispatcher<std::string> { static std::string impl(Record const&...

Address of an instance emplaced to std::vector is invalid

c++11,vector,standards,emplace

Two options: 1) You can simply fix your test. You just need in you test preallocate enough memory first with vec1.reserve(10); Well, this is implementation details for std::vector. As more and more items are added to std::vector it needs to get more space for them. And this space must be...

need help to search element from vector of struct

c++,function,c++11,std

A lambda is just a convenience functor that was introduced so that you can write these algorithms simpler. But it's just a convenience. If you can't use them in this case, it's not the end of the world. After all, we couldn't for many many years. The solution is to...

Using the assert macro while global variables are initialized

c++,c++11,assert,assertion

Two issues here. First, only declarations (e.g. variable, class, function) can go in global scope. assert() is not a declaration, that's why you can't do there. That might lead to a workaround to just shove it into a declaration, like: int x = 1; namespace assert_x_is_1 { bool _ =...

Can you put a pimpl-Class inside a vector

c++,class,c++11,smart-pointers

Since std::unique_ptr is not copyable, class Foo does not have a valid copy constructor. You could either deep copy or use a move constructor: #include <memory> #include <vector> class FooImpl {}; class Foo { std::unique_ptr<FooImpl> myImpl; public: Foo( Foo&& f ) : myImpl( std::move( f.myImpl ) ) {} Foo(){} ~Foo(){}...

Same function with and without template

c++,c++11

The main reason to do something like this is to specialize void integerA(int x) to do something else. That is, if the programmer provides as input argument an int to member function abc::integerA then because of the C++ rules instead of instantiating the template member function the compiler would pick...

Junk varchar entries in MSSQL database using ODBC

c++,sql-server,c++11,odbc

Thanks to @erg, here is the solution that worked for me: char mMessageText[100]; bool initConnection() { (...) // bind parameters SQLBindParameter(mSqlStatementHandle, 5, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_LONGVARCHAR, 100, 0, (SQLPOINTER)mMessageText, 100, NULL); (...) } bool fillDb() { (...) std::string lMessageText = "This text is longer than 15"; strcpy(mMessageText, lMessageText.c_str()); mMessageText[sizeof(mMessageText) - 1]...

Call to implicitly-deleted copy constructor in LLVM(Porting code from windows to mac)

c++,osx,c++11,compiler-errors,llvm

This line of code is very ambiguous: for (auto it : _unhandledFiles)//ERROR HERE auto uses template argument deduction, so std::string s; std::string& sr = sr; auto x = sr; in the above code x is deduced to be of type std::string, not std::string&. So your loop is equivalent to: for...

Read a variable in another thread

multithreading,c++11,atomic,stdatomic

You can indeed just declare it as std::atomic<int>, and things should work as you want. volatile is about preserving the sequence of addresses and values that the generated code must present to the processor for reading/writing. It doesn't at all constrain what the hardware does with that for purposes of...

How can I convert an int to a string in C++11 without using to_string or stoi?

c++,string,c++11,gcc

Its not the fastest method but you can do this: #include <string> #include <sstream> #include <iostream> template<typename ValueType> std::string stringulate(ValueType v) { std::ostringstream oss; oss << v; return oss.str(); } int main() { std::cout << ("string value: " + stringulate(5.98)) << '\n'; } ...

Lock Free Bounded Stack C++11 atomics

c++,multithreading,c++11,stack,lock-free

I'm not an expert in lock free programming, but I'm pretty sure that your code is NOT thread safe. Let's first look at register_idle(): What could happen here is that Thread1 increments idle_pos but before it stores its id, another thread calls wakeup_once and uses an outdated id (in the...

Sorting vector of Pointers of Custom Class

c++,sorting,c++11,vector

The only error that I see is this>current_generation_.end() instead that ->. In addition you should consider declaring your compare fuction as accepting two const FPGA* instead that just FPGA*. This will force you to declare fitness() as const int fitness() const but it makes sense to have it const. Mind...

Mapping const char * to duck-typed T at compile-time or run-time

c++,templates,c++11

Fatal allows you to trivially solve the compile time version of your problem using compile-time strings, type maps and type prefix trees. Let's first start with the headers we'll be using: // type_map so we can associated one type to another #include <fatal/type/map.h> // type_prefix_tree for efficient compile-time string lookups...

Dereferencing a temporary unique_ptr

c++,c++11,unique-ptr

The unique_ptr will pass the ownership to another unique_ptr, but in your code there is nothing to capture the ownership from the returning pointer. In other words, It can not transfer the ownership, so it will be destructed. The proper way is: unique_ptr<A> rA = myFun(); // Pass the ownership...

C++ Create shared_ptr from Object

c++,c++11,dictionary,shared-ptr

You can simply construct the shared pointer first rather than inline when inserting it into the map. House& Obj::CreateHouse(const char *name) { // make the ptr first! auto aaa = std::make_shared<House>("apartment"); _myHouseMap.insert(std::make_pair("apartment", aaa)); return *aaa; } ...

Is executing C++ code in comments with certain Unicode characters allowed, like in Java?

c++,c++11,unicode,comments

If I read this translation phase reference correctly, then the sequence // \u000d some code here is mapped in phase 1 to itself, i.e. the parser does not translate or expand \u000d. Instead the translation of such sequences happens in phase 5, which is after the comments are replaced by...

In c++11 what should happen first: raw string expansion or macros?

c++,c++11,preprocessor,rawstring

GCC and clang are right, VC++ is wrong. 2.2 Phases of translation [lex.phases]: [...] The source file is decomposed into preprocessing tokens (2.5) and sequences of white-space characters (including comments). Preprocessing directives are executed, [...] And 2.5 Preprocessing tokens [lex.pptoken] lists string-literals amongst the tokens. Consequently, parsing is required to...

Arithmentic operator(+) operator will check both return type and passing arguments or not?

c++,c++11,visual-c++

The return type of a function does not participate in overload resolution. Only the function name and parameter list (and cv qualifiers for a member function) matter. But I can see no multiple definition in your code. The error is that you have re-declarations of the same function with different...

How best to prevent unused variable warnings in custom assert without sizeof?

c++,c++11,lambda,assert,sizeof

I believe I figured out a solution. Since lambda expressions not allowed in unevaluated operands but they ARE allowed in the unevaluated portions of constant expressions, we should be able to exploit that fact. Specifically, I've set my #define when NDEBUG is ON to: #define emp_assert(EXPR) { \ constexpr bool...

How can I pass unique_ptr into a function

c++,c++11

There's basically two options here: Pass the smart pointer by reference void MyFunc(unique_ptr<A> & arg) { cout << arg->GetVal() << endl; } int main(int argc, char* argv[]) { unique_ptr<A> ptr = unique_ptr<A>(new A(1234)); MyFunc(ptr); } Move the smart pointer into the function argument Note that in this case, the assertion...

Issue using std::atomic_flag with worker thread

c++,multithreading,c++11,stdatomic

Just replace thread SanityTestThread(&SanityTest::_rx, *this); with thread SanityTestThread(&SanityTest::_rx, this); You probably intended to pass a pointer to the object and not the object itself (which would result in that object being copied and the member function pointer &SanityTest::_rx being invoked on that copy instead of the original object). The reason...

How to parameterize the number of parameters of a constructor?

c++,templates,c++11,constructor

You could create a variadic constructor and just assert that it was provided the right number of arguments: template <size_t SZ> struct Foo { template <typename... Args> Foo(Args... args) { static_assert(sizeof...(Args) <= SZ, "Invalid number of arguments"); // ... stuff ... } }; So that: Foo<3> f; // OK Foo<3>...

VS2015: Variadic template specialization

c++,templates,c++11,c++14,visual-studio-2015

You have an extra template<> here: template<> // <=== template<typename T> struct Is_Admitted<T> : public std::false_type{}; Your code gives me the same error via webcompiler. Simply remove it and it compiles fine. I do not understand how this compiles on either gcc or clang. Two template declarations are only necessary...

Call template function for the value of a pointer out of a template function, in C++

c++,templates,pointers,c++11

The whole body of your template function needs to compile for the types it's instantiated with, regardless of whether or not a branch will ever be taken. To get around this issue, you can define separate functions for when T is a pointer and when it's not. Using SFINAE: template...

Output MySql table to Console Output [on hold]

c++,mysql,sql,c++11

mysql --host=localhost --user=fred7 --password=OpenSesame DBName < "/fullpath/myScript.sql" write a select statement inside myScript.sql you can output to a txt file too with > outFile.txt...

Why is erasing via a const_iterator allowed in C++11?

c++,c++11,stl,const,erase

erase and insert are non-const member functions of the collection. Non-const member functions are the right way to expose mutating operations. The constness of the arguments are irrelevant; they aren't being used to modify anything. The collection can be modified because the collection is non-const (held in the hidden this...

Why does C++ allow a semicolon at the start of a line? [duplicate]

c++,c++11,visual-c++

This is the C and C++ standards for NOP (short for No Operation). The simplest possible statement in C/C++ that behaves like a NOP is the so-called null statement, which is just a semi-colon in a context requiring a statement. (A compiler is not required to generate a NOP instruction...

Reordering vector of vectors based on input vector

c++,c++11,vector,stl,idioms

If you transpose the data, it's as easy as sorting the vectors by the index of the first element in them. This will be slower than your solution but may be more readable: void fix_order(std::vector<std::vector<std::string>>& data, const std::vector<std::string>& correct) { // setup index map, e.g. "first" --> 0 std::unordered_map<std::string, size_t>...

Segmentation fault when initializing a std::vector

c++11,segmentation-fault,stdvector

What are the possible causes of a segmentation fault at the following line? The line itself is exceedingly unlikely to cause a segmentation fault. The only way that could happen is if you've exhausted stack. Do (gdb) x/i $pc. Is the crashing instruction a PUSH or a CALL? If...

syntax for calling a method on a member with multiple instances

c++11,inheritance,c++14

Just use a class name qualifier like you usually would: h.helper<int>::t.test(); It's bizarre syntax, to be sure, but it is no different from writing foo.Base::member to access a hidden base class member from a derived class instance....

How to check a value like “#define VERSION 3.1.4” at compile time?

c++,c++11,preprocessor

Here is what I am doing now: #define str(x) #x #define xstr(x) str(x) #include xstr(libwhatever.version.is.VERSION.should.be.3.1.4) Along with this, I add an empty file named libwhatever.version.is.3.1.4.should.be.3.1.4 to the project. So if the version is correct, the preprocessor will successfully include this file. Otherwise, it will fail with "Cannot open 'libwhatever.version.is.2.7.2.should.be.3.1.4', no...

C++ unordered_map move beginner error

c++11,move,unordered-map

Okay. The problem is in this line: _nodes[key] = std::move(newNode); You are trying to move-assign Node<T, U>. However, Node will not have a move assignment operator implicitly declared as defaulted because there is a user-declared destructor: ~Node() = default; As a result, that line actually calls the copy assignment operator...

Type function that returns a tuple of chosen types

c++,templates,c++11,metaprogramming

You can do this without recursion by simply expanding the parameter pack directly into a std::tuple: template<My_enum... Enums> struct Tuple { using type = std::tuple<typename Bind_type<Enums>::type...>; }; To answer your question more directly, you can declare a variadic primary template, then write two specializations: for when there are at least...

“Emulating” std::declval issues. Works (kind of) in g++, fails to compile in clang++

c++,c++11,decltype

Minimized to struct Meow {}; int main(){ decltype(Meow.purr()) d; } This is plainly invalid code, yet GCC 5.1 and trunk accept it. Not much to say about it other than "bug". Interestingly, both correctly rejects struct Meow {}; decltype(Meow.purr()) d; ...

Sorting based on the rules set by a string variable

c++,qt,sorting,c++11

You can make a map between their choice and a functor to sort by, for example using SortFun = bool(*)(Hotel const&, Hotel const&); std::map<char, SortFun> sorters { {'s', [](Hotel const& lhs, Hotel const& rhs){ return lhs.stars < rhs.stars; }}, {'f', [](Hotel const& lhs, Hotel const& rhs){ return lhs.freeRoomCount < rhs.freeRoomCount;...

When the main exits where does the console output go?

multithreading,c++11

When main exits it calls exit which terminates all threads, regardless detached or not. This is because exit terminates the entire process. The C++ runtime runs main as exit(main(argc, argv)), so that returning from main causes exit to be called. You can terminate your main thread, if you wish, by...

C++ Opengl - How to load tgas and pngs in modern OpenGL? [on hold]

image,opengl,c++11,png,tga

Writing a loader for TGA is relatively straightforward, so for an exercise: go for it. PNG on the other hand is a different kind of beast. It has a gazillion features, supports multiple compression schemes and encodings, all of which you have to support to load PNG files generated by...

C++11 Allocation Requirement on Strings

c++,string,c++11,memory,standards

Section 21.4.1.5 of the 2011 standard states: The char-like objects in a basic_string object shall be stored contiguously. That is, for any basic_string object s, the identity &*(s.begin() + n) == &*s.begin() + n shall hold for all values of n such that 0 <= n < s.size(). The two...

Function with variable parameters as parameter to function C++

c++,templates,c++11

You should pass a callable object, &someClass::measuredF is not callable, its requires a someClass object. You may do: void someClass::someFunction() { long int end = 10; auto duration = ChronoTimer<>::duration([this](long int end) { this->measuredF(end); }, end).count(); } or capture all: void someClass::someFunction() { long int end = 10; auto duration...

Camera calibration and conversion of coordinates(OpenCV)

c++,opencv,c++11,computer-vision

The camera calibration process estimates the intrinsic camera parameters: the camera matrix, usually denoted K, and the lens distortion coefficients, D. (NB: the rotation translation matrices of the camera with respect to the pattern are also computed for each image used for the calibration, see "Extrinsic_Parameters", but they are generally...

No match for 'operator*' error

c++,c++11

As @101010 hints at: pay is a string, while hours_day is a float, and while some languages allow you to multiply strings with integers, c++11 (or any other flavor of c) doesn't, much less allow strings and floats to be multiplied together.

Why is the boolean value within a structure within a vector not being updated?

c++,c++11

This: auto student_to_check = *it; declares a local variable that is a copy of the structure in the vector. The iterator points to the structure in the vector, so you can use: auto student_to_check = it; and: student_to_check->disabled = true; or more simply the following to access anything in the...

Configuring Flycheck to work with C++11

c++,c++11,emacs,flycheck

Flycheck provides the option flycheck-gcc-language-standard for this purpose. You should not set it globally, because that will break checking of C files, but you can set it from c++-mode-hook with the following code in your init file: (add-hook 'c++-mode-hook (lambda () (setq flycheck-gcc-language-standard "c++11"))) However, I would recommend against this....

Should checking loop conditions be counted towards total number of comparisons?

c++,algorithm,sorting,c++11

If you look at your inserstion sort As you already put count =1 because as for exits on exit condition of for loop. for same reason then it also make sense that when while loop cancels the count++ inside will not get executed but there was a comparison made. but...

Relationship of std::unique_lock and conditional_variable cond

c++,multithreading,c++11

To start with, your code has a data race (and hence undefined behavior) since if(x == 0) in createFood() accesses x unprotected. Every access to x, both reads and writes, must be protected by the mutex. is it automatically unlocked so that the other thread can access it while waiting?...

C++ error: deduced conflicting types for parameter 'T' string vs const char *

c++,string,templates,c++11,char

Well, std::string and const char* (<- this is what "pear" decays to when calling the function) are two different types you both want to deduce T from, just as the compiler says. To fix the issue, call the function with the correct type: searchInDequeFor(myDeque,std::string("pear")); ...

What does (&) — ampersand in parentheses — mean in this code?

c++,c++11

It's shorthand for something like this: template <typename T, size_t N> constexpr size_t size_of(T (&anonymous_variable)[N]) { return N; } In the function, you don't actually need the name of the variable, just the template deduction on N - so we can simply choose to omit it. The parentheses are syntactically...

C++ lambda, not seeing function and argument?

c++,multithreading,c++11,lambda,boost-asio

In the lambda that is calling callAFunctionHere, the this that is captured is the one for the instance of class A::TimerService, but you are trying to implicitly use members of an class A instance. You need a reference to an object of type A, and use that object's members. class...

Error using range-based for loop - Eclipse CDT Luna

templates,c++11,for-loop,mingw,eclipse-luna

To use a range based for loop you'll need to use std::array instead of C-style array. I modified your code so it works. Note that you'll need to pass -std=c++11 flag to the compiler. #include <array> #include <iostream> using namespace std; template <typename T> void display (T myArray) { int...