This question already has answers here:
c++ vector initialization
(5 answers)
Closed 8 years ago.
I'm trying to initialize a vector in visual studio this way :
const vector <int> A {1,2,3,4,5};
and its giving me an error. The error says :
"error C2470: 'A' : looks like a function definition, but there is no parameter list; skipping apparent body"
Can anyone please tell me why i'm getting this error?
As I have mentioned that VS2012 does not support initializer_list and hence we get the compilation error. You can use the following to get the almost same thing.
#include<vector>
#include <iterator>
#include<iostream>
using namespace std;
int main() {
int arr[] = {1,2,3,4,5};
const std::vector <int> A(std::begin(arr), std::end(arr));
for(const auto& i: A)
std::cout<<i<<std::endl;
}
The way which you are using to initialize vector is not supported by C++98...
The support has been provided for initializer list constructor in C++11..
so instead you can use below code...
int arr[] = {1,2,3,4,5};
vector<int> A(arr, arr+sizeof(arr)/sizeof(arr[0]));
Related
I learned that from C++17, with the deduction guides, template arguments of std::vector can be deduced e.g. from the initialization:
std::vector vec = { function_that_calculate_and_return_a_specifically_templated_type() }
However I do not have the luxury of C++17 in the machine where I want to compile and run the code now.
Is there any possible workaround for C++11? If more solutions exist, the best would be the one that keep the readability of the code.
At the moment the only idea that I have is to track the various cases along the code (luckily they should not be too many) and make some explicit typedef/using.
Any suggestion is very welcome
The usual way to use type deduction for class template when CTAD is not available is providing a make_* function template, e.g. for your case (trailing return type is necessary for C++11):
#include <vector>
#include <type_traits>
#include <tuple>
template <class ...Args>
auto make_vec(Args&&... args) ->
std::vector<typename std::decay<typename std::tuple_element<0, std::tuple<Args...>>::type>::type>
{
using First = typename std::decay<typename std::tuple_element<0, std::tuple<Args...>>::type>::type;
return std::vector<First>{std::forward<Args>(args)...};
}
You can invoke the above with
const auto v = make_vec(1, 2, 3);
which gets at least kind of close to CTAD in the sense that you don't have to explicitly specify the vector instantiation.
While the answer by lubgr is a correct way, the following template is simpler and seems to work as well:
#include <vector>
#include <string>
template <typename T>
std::vector<T> make_vec(const std::initializer_list<T> &list)
{
return std::vector<T>(list);
}
int main()
{
auto v = make_vec({1,2,3});
auto v2 = make_vec({std::string("s")});
std::string s("t");
auto v3 = make_vec({s});
return v.size() + v2.size() + v3.size();
}
One advantage of using the initializer_list template directly are more clear error messages if you pass mixed types like in make_vec({1,2,"x"});, because the construction of the invalid initializer list now happens in non-templated code.
This question already has answers here:
Resolve build errors due to circular dependency amongst classes
(12 answers)
Closed 4 years ago.
I have two classes that are inter-dependent. I am pretty sure, I am designing it in a wrong way but I don't know how to fix it.
So, I have a situation like following-
My car class includes the truck class.
#include "stdafx.h"
#include "truck.h"
using namespace std;
class car {
int wheels;
float speed;
public:
car(int wheels, int speed);
int numberOfWheels();
float speedRate();
bool isFaster(truck & truck);
};
and then my truck class needs to include the car class-
#include "stdafx.h"
#include "car.h"
using namespace std;
class truck {
int wheels;
float speed;
public:
truck(int wheels, int speed);
int numberOfWheels();
float speedRate();
bool isFaster(car & car);
};
I am getting the include itself error and I know why but I can't find a way to get around that.
Can anyone please help me with it.
Use forward declaration
In any one header file you can declare other class as forward declarations
This question already has answers here:
C++ lambda with captures as a function pointer
(9 answers)
Closed 7 years ago.
UPDATED: (Rephrased). I'm looking to boost the computation efficiency of my code by make an run-time assignment of a class member function to one of many functions conditional on other class members.
One recommended solution uses #include <functional> and function<void()>, as shown in the simple test example:
#include <iostream>
using namespace std;
struct Number {
int n;
function(void()) doIt;
Number(int i):n(i) {};
void makeFunc() {
auto _odd = [this]() { /* op specific to odd */ };
auto _even = [this]() { /* op specific to even */ };
// compiles but produces bloated code, not computatinally efficient
if (n%2) doIt = _odd;
else doIt = _even;
};
};
int main() {
int i;
cin >> i;
Number e(i);
e.makeFunc();
e.doIt();
};
I'm finding that the compiled code (i.e. debug assembly) is grotesquely complicated and presumably NOT computationally efficient (the desired goal).
Does someone have an alternative construct that would achieve the end goal of a computationally efficient means of conditionally defining, at run-time, a class member function.
A capturing lambda expression cannot be assigned to a regular function pointer like you have.
I suggest using
std::function<void()> doIt;
instead of
void (*doIt)();
I encountered a weird problem just now.
The source code is simple and self-evident as follows:
#include <vector>
#include <iostream>
#include <functional>
using namespace std;
using namespace std::tr1;
template<class T_>
void show_size(T_ coll)
{
cout << coll.size();
}
int main()
{
vector<int> coll;
coll.push_back(1);
show_size(ref(coll));
return 0;
}
The VC++ 2010 reports:
error C2039: 'size' : is not a member of 'std::tr1::reference_wrapper<_Ty>'
As we know, reference_wrapper can automatically convert itself to its underlying type, here is vector<int>. Why is such simple code not valid?
No it can't that's the whole point of the reference wrapper, because it doesn't decay from the reference, unless explicitly requested using .get()
Edit: don't mix up the boosts reference wrapper with the standard one, the boost one actually has implicit conversion (but the target functionality is a little bit different)
I have the following code.
#include <set>
#include <algorithm>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
typedef set<long> MySet;
MySet a;
for( int i = 0; i < 10; ++i)
{
a.insert(i);
}
MySet::iterator start,end,last;
start = a.begin();
end = a.end();
last = remove_if(start,end,bind2nd(less_equal<long>(),5));
return 0;
}
Which under VS2005 used to compile fine. However using VS2010 I get the following error:
Error 1 error C3892: '_Next' : you cannot assign to a variable that is const c:\program files\microsoft visual studio 10.0\vc\include\algorithm
If I make the container a vector, everything is fine.
I'm guessing something has changed in the standard that I'm not aware of, can someone please shed some light on why this no longer works?
A std::set always keeps its elements in sorted order. std::remove_if attempts to move the elements you don't want removed to the beginning of the collection. This would violate set's invariant of maintaining the elements in sorted order.
The code never should have worked. Older compilers might not have enforced the rules tightly enough to let you know that it wasn't supposed to work, but (apparently) your current one does.