Reputation: 3076
Can we use pair as an argument for another pair in C++.
Here is a test program to do that.
#include <iostream>
#include <utility>
int main()
{
std::pair<int,int> m;
m=std::make_pair(1,3);
int r = 3;
int *q = &r;
int **p =&q;
int **t = p;
std::pair<int**,<std::pair<int,int> > > i(p,m);
std::cout<<i[t];
return 0;
}
This is the error, I am getting.
Test.cpp: In function ‘int main()’:
Test.cpp:12:45: error: template argument 2 is invalid
std::pair<int**,<std::pair<int,int>>> i(p,m);
^
If I changed the format of declaration and wrote the program in the following way,
#include <iostream>
#include <utility>
int main()
{
std::pair<int,int> m;
m=std::make_pair(1,3);
int r = 3;
int *q = &r;
int **p =&q;
int **t = p;
std::pair<
int**,
<
std::pair<
int,
int
>
>
> i(p,m);
std::cout<<i[t];
return 0;
}
There is an additional error.
Test.cpp: In function ‘int main()’:
Test.cpp:20:7: error: template argument 2 is invalid
> i(p,m);
^
Test.cpp:20:14: error: expression list treated as compound expression in initializer [-fpermissive]
> i(p,m);
What might be the issue and how to solve it?
On a side note, I did a program and compiled it in an very old Dev-c++ compiler on a windows 7 machine which used a code similar to the above and it ran perfectly fine. It was a lab program in my college which had only that compiler.
The above code, I ran on both windows 7 and Ubuntu 16.04 using GNU g++ 5.4.0
Ideone: Link to the actual program for reference
You might also have a look at the actual error, I faced in the above link.
Upvotes: 1
Views: 34
Reputation: 1
There are two problems with your code.
cout
parameter makes no sense#include <iostream>
#include <utility>
int main()
{
std::pair<int,int> m;
m=std::make_pair(1,3);
int r = 3;
int *q = &r;
int **p =&q;
int **t = p;
std::pair<
int**,
// < Omit this
std::pair<
int,
int
>
// > also this
> i(p,m);
// std::cout<<i.[t]; indexing with a pointer value doesn't make sense
// i. for a pair doesn't make sense, specify either first or second
std::cout<<i.first[0]; // <<<< Did you mean something like this?
return 0;
}
Check the compiling version live
Upvotes: 1
Reputation: 534
This is incorrect:
std::pair<int**,<std::pair<int,int> > > i(p,m);
Just remove the extra <>
:
std::pair<int**, std::pair<int,int > > i(p,m);
Also, I'm not sure what you're trying to do in the cout
part, but pair
doesn't have a []
operator. You can access the elements with first
and second
:
i.first
i.second
i.second.first
i.second.second
You may also be interested in std::tuple
if you don't want to nest one pair into another:
std::tuple<int**, int, int> i;
Upvotes: 1