Create map using two arrays - c++

I am trying to create a map using two arrays. Here is the code:
#include <algorithm>
#include <iostream>
#include <map>
#include <utility>
#include <iterator>
#include <string>
using namespace std;
using std::transform;
int main(){
const char* word[]={"A","B","C","D","E"};
const char * clue[]={"a","b","c","d","e"};
map<string,string>dictionary;
map<string,string>::iterator it;
transform(word, word+sizeof(word)/sizeof(word[0]), clue,
inserter(dictionary,dictionary.end()), make_pair<string,string>);
for (it=dictionary.begin(),it!=dictionary.end();it++)
cout<<it->first<< " "<<it->second<<endl;
return 0;
}
But here are the mistakes:
1>------ Build started: Project: map_array, Configuration: Debug Win32 ------
1>Build started 8/21/2010 4:27:25 PM.
1>PrepareForBuild:
1> Creating directory "c:\users\david\documents\visual studio 2010\Projects\map_array\Debug\".
1>InitializeBuildStatus:
1> Creating "Debug\map_array.unsuccessfulbuild" because "AlwaysCreate" was specified.
1>ClCompile:
1> map_array.cpp
1>c:\users\david\documents\visual studio 2010\projects\map_array\map_array\map_array.cpp(16): error C2784: '_OutTy *std::transform(_InIt1,_InIt1,_InTy (&)[_InSize],_OutTy (&)[_OutSize],_Fn2)' : could not deduce template argument for '_OutTy (&)[_OutSize]' from 'std::insert_iterator<_Container>'
1> with
1> [
1> _Container=std::map<std::string,std::string>
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\algorithm(1293) : see declaration of 'std::transform'
1>c:\users\david\documents\visual studio 2010\projects\map_array\map_array\map_array.cpp(16): error C2784: '_OutTy *std::transform(_InIt1,_InIt1,_InIt2,_OutTy (&)[_OutSize],_Fn2)' : could not deduce template argument for '_OutTy (&)[_OutSize]' from 'std::insert_iterator<_Container>'
1> with
1> [
1> _Container=std::map<std::string,std::string>
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\algorithm(1279) : see declaration of 'std::transform'
1>c:\users\david\documents\visual studio 2010\projects\map_array\map_array\map_array.cpp(16): error C2914: 'std::transform' : cannot deduce template argument as function argument is ambiguous
1>c:\users\david\documents\visual studio 2010\projects\map_array\map_array\map_array.cpp(16): error C2784: '_OutIt std::transform(_InIt1,_InIt1,_InTy (&)[_InSize],_OutIt,_Fn2)' : could not deduce template argument for '_OutIt' from 'std::insert_iterator<_Container>'
1> with
1> [
1> _Container=std::map<std::string,std::string>
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\algorithm(1267) : see declaration of 'std::transform'
1>c:\users\david\documents\visual studio 2010\projects\map_array\map_array\map_array.cpp(16): error C2914: 'std::transform' : cannot deduce template argument as function argument is ambiguous
1>c:\users\david\documents\visual studio 2010\projects\map_array\map_array\map_array.cpp(16): error C2784: '_OutIt std::transform(_InIt1,_InIt1,_InIt2,_OutIt,_Fn2)' : could not deduce template argument for '_OutIt' from 'std::insert_iterator<_Container>'
1> with
1> [
1> _Container=std::map<std::string,std::string>
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\algorithm(1249) : see declaration of 'std::transform'
1>c:\users\david\documents\visual studio 2010\projects\map_array\map_array\map_array.cpp(16): error C2780: '_OutTy *std::transform(_InIt,_InIt,_OutTy (&)[_OutSize],_Fn1)' : expects 4 arguments - 5 provided
1> c:\program files\microsoft visual studio 10.0\vc\include\algorithm(1127) : see declaration of 'std::transform'
1>c:\users\david\documents\visual studio 2010\projects\map_array\map_array\map_array.cpp(16): error C2780: '_OutIt std::transform(_InIt,_InIt,_OutIt,_Fn1)' : expects 4 arguments - 5 provided
1> c:\program files\microsoft visual studio 10.0\vc\include\algorithm(1111) : see declaration of 'std::transform'
1>c:\users\david\documents\visual studio 2010\projects\map_array\map_array\map_array.cpp(20): error C2143: syntax error : missing ';' before ')'
1>c:\users\david\documents\visual studio 2010\projects\map_array\map_array\map_array.cpp(20): error C2451: conditional expression of type 'std::_Tree_iterator<_Mytree>' is illegal
1> with
1> [
1> _Mytree=std::_Tree_val<std::_Tmap_traits<std::string,std::string,std::less<std::string>,std::allocator<std::pair<const std::string,std::string>>,false>>
1> ]
1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:02.19
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
How do I fix this problem?
EDITED
I have tried another version of the solution to this problem (using by the Internet and C++ sites), and I have found a way to solve this problem like this
#include <algorithm>
#include <iostream>
#include <map>
#include <utility>
#include <iterator>
#include <string>
using namespace std;
template<typename KeyType, typename ValueType, int N>
class mapmaker
{
std::pair<KeyType, ValueType> (&table)[N];
const KeyType (&keys)[N];
const ValueType (&vals)[N];
template<int pos> void fill_pair()
{
table[pos].first = keys[pos];
table[pos].second = vals[pos];
fill_pair<pos-1>();
}
template<> void fill_pair<0>()
{
table[0].first = keys[0];
table[0].second = vals[0];
}
public:
mapmaker( std::pair<KeyType, ValueType> (&t)[N], const KeyType (&k)[N], const ValueType (&v)[N] )
: table(t), keys(k), vals(v)
{
fill_pair<N-1>();
}
};
template<typename KeyType, typename ValueType, int N>
std::map<KeyType,ValueType> make_map(const KeyType (&keys)[N], const ValueType (&vals)[N])
{
std::pair<KeyType, ValueType> table[N];
mapmaker<KeyType, ValueType, N>( table, keys, vals );
return std::map<KeyType, ValueType>(table, table+N);
}
int main(){
static const string word[]={"A","B","C","D","E"};
static const string clue[]={"a","b","c","d","e"};
static map<string,string>dictionary=make_map(word,clue);
map<string,string>::iterator it;
//transform(word,word+sizeof(word)/sizeof(word[0]),clue,clue,inserter(dictionary,dictionary.end()));
for (it=dictionary.begin();it!=dictionary.end();it++)
cout << it->first << " " << it->second << endl;
//cout<<dictionary.size();
return 0;
}

The code looks valid, and it compiles with GCC, after changing the syntax error in your for loop (the comma should be a semicolon after the initial part).
Note that C++03 compilers are not necessarily required to correctly get a function pointer with make_pair<string,string>. Only C++0x allows directly getting the address of a function template specialization without casting but merely giving a template argument list, but usually C++03 compilers backpart that feature and implement it even in C++03 mode. But i think it is unlikely that this is the source of your problem here.

Maybe can we make something simpler.
vector<string> aKeys = {"#1", "#2", "#3", "#4"};
vector<int> aValues = {1, 2, 3, 4};
map<string,int> createdDict = {};
for (auto i = 0; i < aKeys.size(); i++) {
createdDict[aKeys[i]] = aValues[i];
}

Related

MSVC 2015 - compiler error in std::for_each for custom iterator (only when in DEBUG)

I've implemented a custom container class together with its iterator, and trying to use a for_each on it. Everything compiles fine in VC6, online cpp.sh and MSVC15, the latter only in release: when in debug I got a series of errors I report, under, the oversimplified version of my code.
struct Functor {
void operator()(int&) {}
} func;
struct Container {
typedef int value_type;
struct iterator {
bool operator!=(iterator const&) { return true; }
iterator& operator++() { return *this; }
value_type& operator*() { return i; } //this is just to compile, not for real
int i; //this is just to compile, not for real
};
iterator begin() { return iterator(); }
iterator end() { return iterator(); }
};
#include <algorithm>
int main() {
Container c;
std::for_each(c.begin(), c.end(), func); // compile errors
return 0;
}
Errors:
1>c:\program files\microsoft visual studio 14.0\vc\include\xutility(838): error C2672: '_Iter_cat': no matching overloaded function found
1> c:\program files\microsoft visual studio 14.0\vc\include\algorithm(31): note: see reference to function template instantiation 'void std::_Debug_range_ptr<_InIt,_Fn1>(_InIt,_InIt,_Pty &,std::_Dbfile_t,std::_Dbline_t)' being compiled
1> with
1> [
1> _InIt=Container::iterator,
1> _Fn1=Functor,
1> _Pty=Functor
1> ]
1> [...]: note: see reference to function template instantiation '_Fn1 std::for_each<Container::iterator,Functor>(_InIt,_InIt,_Fn1)' being compiled
1> with
1> [
1> _Fn1=Functor,
1> _InIt=Container::iterator
1> ]
1>c:\program files\microsoft visual studio 14.0\vc\include\xutility(838): error C2893: Failed to specialize function template 'iterator_traits<_Iter>::iterator_category std::_Iter_cat(const _Iter &)'
1> c:\program files\microsoft visual studio 14.0\vc\include\xutility(838): note: With the following template arguments:
1> c:\program files\microsoft visual studio 14.0\vc\include\xutility(838): note: '_Iter=Container::iterator'
1>c:\program files\microsoft visual studio 14.0\vc\include\xutility(838): error C2672: '_Debug_range_ptr2': no matching overloaded function found
1>c:\program files\microsoft visual studio 14.0\vc\include\xutility(838): error C2780: 'void std::_Debug_range_ptr2(_RanIt,_RanIt,_Pty &,std::_Dbfile_t,std::_Dbline_t,std::random_access_iterator_tag)': expects 6 arguments - 5 provided
1> c:\program files\microsoft visual studio 14.0\vc\include\xutility(820): note: see declaration of 'std::_Debug_range_ptr2'
1>c:\program files\microsoft visual studio 14.0\vc\include\xutility(838): error C2780: 'void std::_Debug_range_ptr2(_InIt,_InIt,_Pty &,std::_Dbfile_t,std::_Dbline_t,std::input_iterator_tag)': expects 6 arguments - 5 provided
1> c:\program files\microsoft visual studio 14.0\vc\include\xutility(811): note: see declaration of 'std::_Debug_range_ptr2'
MSVC has more extensive debug checks when using iterators. Presumably this requires a more complete definition of the iterator with all its embedded types.
Traditionally iterators have been derived from std::iterator<> that provides default definitions for the embedded types required.
template<
class Category,
class T,
class Distance = std::ptrdiff_t,
class Pointer = T*,
class Reference = T&
> struct iterator;
A change to the code as follows should clear things up;
struct iterator : std::iterator<
std::input_iterator_tag, // or as required
int
>
Usually iterators are defined as derived classes of the standard class std::iterator that is declared like
template<class Category, class T, class Distance = ptrdiff_t,
class Pointer = T*, class Reference = T&> struct iterator;
One of its template parameters is Category that determinates the category tag of the iterator such as for example std::input_iterator_tag.
In the debug mode the compiler performs some checks based on the category of the iterator.
You should follow this standard model of defining iterators.

Error on compiling template function of Queue of std::functions

I want to make a template function to queue both general functions and also class member functions. With internet search, I came up with the following code but have error in compiling it.
#include <iostream>
#include <functional>
#include <queue>
#include <string>
double MyFunction(double num1, double num2)
{
std::cout << "MyFunction( " << num1 << ", " << num2 << " )\n";
return num1 + num2;
}
class MyClass
{
public:
double MyClassFunction(double num1, double num2, double num3) const
{
std::cout << "MyClass::MyClassFunction( " << num1 << ", " << num2 << ", " << num3 << " )\n";
return num1 + num2 + num3;
}
};
struct MyFunctionQueue
{
template <typename FUNC, typename... ARGS>
void QueueFunction(FUNC fn, ARGS&&... args)
{
std::function<std::result_of_t<FUNC(ARGS...)> () > rFunc = std::bind(fn, args...);
_myFQ.push(rFunc);
}
void Execute()
{
while (!_myFQ.empty())
{
_myR.push(_myFQ.front()());
_myFQ.pop();
}
}
double PopResult()
{
double r = _myR.front();
_myR.pop();
return r;
}
std::queue<std::function<double()>> _myFQ;
std::queue<double> _myR;
};
int main()
{
MyFunctionQueue funcQue;
funcQue.QueueFunction(MyFunction, 1.234, 2.345);
MyClass obj;
funcQue.QueueFunction(&MyClass::MyClassFunction, std::ref(obj), 1.234, 2.345, 3.456);
funcQue.Execute();
std::cout << "MyFunction result: " << funcQue.PopResult() << std::endl;
std::cout << "MyClass::MyClassFunction result: " << funcQue.PopResult() << std::endl;
}
I know the error is with the template code generation on the class member function. With my limited knowledge in using templates I cannot figure out what's wrong with it. Can anyone help to point out the mistake in the code? And the error I've got from VC++ is:
1>------ Build started: Project: TestFunctionQueue, Configuration: Debug Win32 ------
1> TestFunctionQueue.cpp
1>c:\program files (x86)\microsoft visual studio 14.0\vc\include\type_traits(1469): error C2672: 'std::invoke': no matching overloaded function found
1> c:\users\siu.chan\documents\visual studio 2015\projects\testfunctionqueue\testfunctionqueue\testfunctionqueue.cpp(31): note: see reference to class template instantiation 'std::result_of<FUNC (std::reference_wrapper<MyClass>,double,double,double)>' being compiled
1> with
1> [
1> FUNC=double (__thiscall MyClass::* )(double,double,double) const
1> ]
1> c:\users\siu.chan\documents\visual studio 2015\projects\testfunctionqueue\testfunctionqueue\testfunctionqueue.cpp(63): note: see reference to function template instantiation 'void MyFunctionQueue::QueueFunction<double(__thiscall MyClass::* )(double,double,double) const,std::reference_wrapper<MyClass>,double,double,double>(FUNC,std::reference_wrapper<MyClass> &&,double &&,double &&,double &&)' being compiled
1> with
1> [
1> FUNC=double (__thiscall MyClass::* )(double,double,double) const
1> ]
1>c:\program files (x86)\microsoft visual studio 14.0\vc\include\type_traits(1469): error C2893: Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...)'
1> c:\program files (x86)\microsoft visual studio 14.0\vc\include\type_traits(1469): note: With the following template arguments:
1> c:\program files (x86)\microsoft visual studio 14.0\vc\include\type_traits(1469): note: '_Callable=double (__thiscall MyClass::* )(double,double,double) const'
1> c:\program files (x86)\microsoft visual studio 14.0\vc\include\type_traits(1469): note: '_Types={std::reference_wrapper<MyClass>, double, double, double}'
1>c:\users\siu.chan\documents\visual studio 2015\projects\testfunctionqueue\testfunctionqueue\testfunctionqueue.cpp(31): error C2440: 'initializing': cannot convert from 'std::_Binder<std::_Unforced,FUNC &,std::reference_wrapper<MyClass> &,double &,double &,double &>' to 'std::function<unknown-type (void)>'
1> with
1> [
1> FUNC=double (__thiscall MyClass::* )(double,double,double) const
1> ]
1> c:\users\siu.chan\documents\visual studio 2015\projects\testfunctionqueue\testfunctionqueue\testfunctionqueue.cpp(31): note: No constructor could take the source type, or constructor overload resolution was ambiguous
1>c:\users\siu.chan\documents\visual studio 2015\projects\testfunctionqueue\testfunctionqueue\testfunctionqueue.cpp(32): error C2664: 'void std::queue<std::function<double (void)>,std::deque<_Ty,std::allocator<_Ty>>>::push(const std::function<double (void)> &)': cannot convert argument 1 from 'std::function<unknown-type (void)>' to 'std::function<double (void)> &&'
1> with
1> [
1> _Ty=std::function<double (void)>
1> ]
1> c:\users\siu.chan\documents\visual studio 2015\projects\testfunctionqueue\testfunctionqueue\testfunctionqueue.cpp(32): note: Reason: cannot convert from 'std::function<unknown-type (void)>' to 'std::function<double (void)>'
1> c:\users\siu.chan\documents\visual studio 2015\projects\testfunctionqueue\testfunctionqueue\testfunctionqueue.cpp(32): note: No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
So, I think this is an issue with vc++. Passing a member function works just fine when the next parameter is a pointer, but fails when it is a reference.
template <class F, class... A>
std::result_of_t<F(A...)> Foo::bar(F f, A... a)
{
return 0;
}
Foo f;
f.bar(&Foo::other_function, std::ref(f)); //error
f.bar(&Foo::other_function, &f); //success
Additionally, result_of in vc++ fails when the function type is a function (like void()), but clang and gcc both succeed.
template <class F, class... A>
struct Foo
{
typedef std::result_of_t<F(A...)> type;
};
Foo<int(int), int> //fails in only vc++

Cannot instantiate abstract class using c++11

Why can't I use an abstract class like an interface at runtime.
I get the output:
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\xmemory0(615): error C2259: 'Creature' : cannot instantiate abstract class
1> due to following members:
1> 'std::string Creature::Move(std::vector<std::string,std::allocator<_Ty>> &)' : is abstract
1> with
1> [
1> _Ty=std::string
1> ]
1> visual studio 2013\projects\cpp_demo\cpp_demo\creature.h(9) : see declaration of 'Creature::Move'
1> c:\program files (x86)\microsoft visual studio 12.0\vc\include\xmemory0(614) : while compiling class template member function 'void std::allocator<_Ty>::construct(_Ty *,const _Ty &)'
1> with
1> [
1> _Ty=Creature
1> ]
1> c:\program files (x86)\microsoft visual studio 12.0\vc\include\xmemory0(752) : see reference to function template instantiation 'void std::allocator<_Ty>::construct(_Ty *,const _Ty &)' being compiled
1> with
1> [
1> _Ty=Creature
1> ]
1> c:\program files (x86)\microsoft visual studio 12.0\vc\include\type_traits(580) : see reference to class template instantiation 'std::allocator<_Ty>' being compiled
1> with
1> [
1> _Ty=Creature
1> ]
1> c:\program files (x86)\microsoft visual studio 12.0\vc\include\vector(650) : see reference to class template instantiation 'std::is_empty<_Alloc>' being compiled
1> with
1> [
1> _Alloc=std::allocator<Creature>
1> ]
1> visual studio 2013\projects\cpp_demo\cpp_demo\main.cpp(7) : see reference to class template instantiation 'std::vector<Creature,std::allocator<_Ty>>' being compiled
1> with
1> [
1> _Ty=Creature
1> ]
My code:
int main()
{
unique_ptr<vector<Creature>> pCreatures(new vector<Creature>);
unique_ptr<Creature> pHuman(new Human());
pCreatures->push_back(*pHuman);
}
#include "stdafx.h"
#include "Creature.h"
class Human : public Creature
{
public:
virtual string Move(vector<string> &log);
};
#include "stdafx.h"
#include "IMove.h"
class Creature : public IMove
{
public:
virtual string Move(vector<string> &log) = 0;
virtual string GetState(vector<string> &log);
};
Please help.
You CAN use abstract class in vector or unique_ptr, e.g.
#include <vector>
#include <memory>
using namespace std;
class Interface {
public:
virtual ~Interface() = 0;
};
Interface::~Interface() {}
class Implementation : public Interface {
};
int main(int argc, char** argv) {
unique_ptr<Interface> p(new Implementation);
vector<unique_ptr<Interface>> v;
v.emplace_back(new Implementation);
vector<Interface> vi;
// This leads to compile error: vi.emplace_back();
}
Moreover, you CAN use vector<Interface> as long as you don't call any methods that potentially calls new Interface. For example, if you just declare a variable vector<Interface> v; it compiles, but if you push_back or emplace_back or resize, then it will have compile error because they will call new Interface.
The above code is tested under gcc-4.6.3.
You can use, but instead of using:
unique_ptr<vector<Creature>> pCreatures(new vector<Creature>);
use
vector<unique_ptr<Creature>> pCreatures;
so you will have a vectors of Creatures pointers, managed by unique_ptr.
There are, at least, two ways to use this vector:
Creating the objects directly into the vector:
pCreatures.emplace_back(new Human());
Moving an unique_ptr to it:
unique_ptr pHuman(new Human());
pCreatures.push_back(move(pHuman));
Below is a compact usage:
int main()
{
vector<unique_ptr<Creature>> pCreatures;
pCreatures.emplace_back(new Human());
unique_ptr<Creature> pHuman(new Human());
pCreatures.push_back(move(pHuman));
// example of usage
pCreatures[0]->Move();
}

C++ lambda error: no appropriate default constructor available

Well this is my first experience with lambda, and I know I might be misusing this feature but I'm wondering why should I get a compile error?
GameMap::MoveDirection AIPlayer::getSafeRouteTo(const GameMap::PlayerInfo& s, const Point& e)
{
struct node : public Point
{
GameMap::MoveDirection parent;
float d;
node():Point(){};
node(Point p) : Point(p)
{
};
};
auto lambdaFunction = [this,&e](node&left,node&right)->bool
{
return this->getDistance(left,e) + left.d < this->getDistance(right,e) + right.d;
};
priority_queue<node,vector<node>, decltype(lambdaFunction)> Q;
//do stuff
return GameMap::MD_None;
}
and for the sake of argument let me say that MoveDirection is an enum, and Point does have a default constructor. as I commented by removing that specific line I don't get the error but I really need it to be there. here are the errors VC2010 is generating:
d:\program files (x86)\microsoft visual studio 10.0\vc\include\queue(225): error C2512: '`anonymous-namespace'::<lambda0>' : no appropriate default constructor available
1> d:\program files (x86)\microsoft visual studio 10.0\vc\include\queue(223) : while compiling class template member function 'std::priority_queue<_Ty,_Container,_Pr>::priority_queue(void)'
1> with
1> [
1> _Ty=AIPlayer::getSafeRouteTo::node,
1> _Container=std::vector<AIPlayer::getSafeRouteTo::node>,
1> _Pr=`anonymous-namespace'::<lambda0>
1> ]
1> c:\users\ali\documents\visual studio 2010\projects\bokhorbokhor\aiplayer.cpp(147) : see reference to class template instantiation 'std::priority_queue<_Ty,_Container,_Pr>' being compiled
1> with
1> [
1> _Ty=AIPlayer::getSafeRouteTo::node,
1> _Container=std::vector<AIPlayer::getSafeRouteTo::node>,
1> _Pr=`anonymous-namespace'::<lambda0>
1> ]
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
The lambda is not default constructible. You have to pass it to this constructor of the priority_queue:
explicit priority_queue(const Compare& x = Compare(), Container&& = Container());
Like this:
priority_queue<node,vector<node>, decltype(lambdaFunction)> Q ( lambdaFunction );

Syntax error with template in c++

I have following code:
#include <iostream>
using namespace std;
template<class T>
T max(T *data,int len){
int i;
T Max=data[0];
for (int i=1;i<len;i++){
if (data[i]>max){
Max=data[i];
}
}
return Max;
}
int mai(){
int i[]={12,34,10,9,56,78,30};
int len=sizeof(i)/sizeof(i[0]);
cout<<max(i,len)<<"\n";
return 0;
}
But when I compile it, I get the following errors:
generic_max, Configuration: Debug Win32 ------
1>Build started 7/29/2010 1:03:25 AM.
1>InitializeBuildStatus:
1> Touching "Debug\generic_max.unsuccessfulbuild".
1>ClCompile:
1> generic_max.cpp
1>c:\users\david\documents\visual studio 2010\projects\generic_max\generic_max\generic_max.cpp(10): error C2563: mismatch in formal parameter list
1> c:\users\david\documents\visual studio 2010\projects\generic_max\generic_max\generic_max.cpp(22) : see reference to function template instantiation 'T max<int>(T *,int)' being compiled
1> with
1> [
1> T=int
1> ]
1>c:\users\david\documents\visual studio 2010\projects\generic_max\generic_max\generic_max.cpp(10): error C2568: '>' : unable to resolve function overload
1> c:\users\david\documents\visual studio 2010\projects\generic_max\generic_max\generic_max.cpp(4): could be 'T max(T *,int)'
1> c:\program files\microsoft visual studio 10.0\vc\include\xutility(2086): or 'const _Ty &std::max(const _Ty &,const _Ty &,_Pr)'
1> c:\program files\microsoft visual studio 10.0\vc\include\xutility(2078): or 'const _Ty &std::max(const _Ty &,const _Ty &)'
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:00.95
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Please help me to fix this problem.
C++ is case-sensitive.
#include <iostream>
// Note the omission of `using namespace std;`. The declaration can
// introduce clashes if one of your functions happen to have the same name
// as the functions in the std namespace.
template<class T>
T max(T *data,int len) {
//int i; <-- Not needed? The for loop already has an `i` declared in it.
T Max=data[0];
for (int i=1;i<len;i++) {
/****** Note `Max`, not `max` ******/
// The typo in your code snippet is what's causing the C2563.
// `max` (in this context) refers to the function
// `template<class T> T max(T *data,int len)` that has been declared.
// `Max` refers to the variable declared in this function.
// (For the sake of readability, variable names should not similar
// to the function name).
if (data[i]>Max) {
Max=data[i];
}
}
return Max;
}
/****** Note `main()`, not `mai()` ******/
int main() {
int i[]={12,34,10,9,56,78,30};
int len=sizeof(i)/sizeof(i[0]);
// `cout` should be just qualified with `std::` instead of
// `using namespace std`.
std::cout<<max(i,len)<<"\n";
return 0;
}
Your max function is conflicting with the standard C++ function std::max because you have written using namespace std at the top of your program, which brings everything in the std namespace into the default namespace. The compiler can't tell if you wanted to call your max or some version of std::max.
Either change the name of your function, or remove using namespace std and explicitly prefix things in your program in the std namespace with std::.
if (data[i]>max) - change max to Max
In line 10, you probably mean >Max and not >max.