#Vector/#List and #Array of Vector/List in c++ and c#. #Add #Elements Using #push_back and =. #Differences 80
c++ code:
#include <iostream>
#include <vector>
#include <map>
#include<algorithm>// for find
#include <iterator> //for distance
using namespace std;
int IndexOf(vector<int> p, int i) {
return distance(p.begin(), find(p.begin(), p.end(), i));
}
void PE(int (&p)[5], int y[]) {
//vector<int> PE(vector<int> p) {
int n = sizeof(p)/sizeof(p[0]);
//int n = p.size();
//vector< int> y;
//vector<int>y(n);
//int y[5];
//for (int i = 0; i < n; i++) {
for (int i = 1; i <= n; i++) {
y[p[p[i - 1] - 1] - 1] = i;
//y[p[p[i]-1]-1] = i + 1;
//int index1 = distance(p.begin(), find(p.begin(), p.end(), i)) +1;
//int index2 = distance(p.begin(), find(p.begin(), p.end(), index1)) +1;
//y.push_back(index2);
//y.push_back(IndexOf(p,(IndexOf(p,i) + 1)) + 1);
cout << "p[" << i << "] =" << p[i - 1] << endl;
//cout << "p[" << (IndexOf(p, i) + 1) << "] =" << i << endl;
}
cout << endl;
//vector<int> v(y, y + n);
//return v;
//return y;
}
int main()
{
//vector <int> p = {4,3,5,1,2};// prints y = {1,3,5,4,2}
//x = 1 = p(4) = p(p(1)) = p(p(y)) = > y = 1
//vector<int> p = { 5,2,1,3,4 };// prints y = {4,2,5,1,3}
// x = 1 = p(3) = p(p(4)) = p(p(y)) => y = 4
const int s = 5;
int p[s] = { 5,2,1,3,4 };// prints y = {4,2,5,1,3}
int result[s];
PE(p, result);
//vector<int> result = PE(p);
int n = sizeof(result) / sizeof(result[0]);
//int n = result.size();
for (int i = 0; i < n; i++)
cout << result[i] << endl;
std::cin.get();
return 0;
}
c# code:
using System;
using System.Collections.Generic;//for string and list
using System.IO;//to use StreamReader
using System.Linq;//for Count
namespace lec1csharp
{
class Program
{
public static void PE(int[] p, int[] y)
//public static List<int> PE(List<int> p)
{
int n = p.Count();
//List<int> y = new List<int>();
//int[] y = new int[p.Count];
//int[] x = new int[p.Count];
//List<int> y = new List<int>(x);
//for (int i = 0; i < n; i++){
for (int i = 1; i <= n; i++){
y[p[p[i - 1] - 1] - 1] = i;//both foreach and for
//y[p[p[i]-1]-1] = i + 1;//both foreach and for
//int index1 = p.IndexOf(i)+1 ;
//int index2 = p.IndexOf(index1) + 1;
//y.Add(index2);
//y.Add(p.IndexOf(p.IndexOf(i) + 1) + 1);//use for loop only
Console.WriteLine("p[{0}] = {1}", i, p[i - 1]);
//Console.WriteLine("p[{0}] = {1}", (p.IndexOf(i) + 1),i);
}
Console.WriteLine();
//List<int> v = y.ToList();
//return v;
//return y;
}
static void Main()
{
//List<int> p = new List<int>(){4,3,5,1,2};// prints y = {1,3,5,4,2}
//x = 1 = p(4) = p(p(1)) = p(p(y)) = > y = 1
//List<int> p = new List<int>() { 5, 2, 1, 3, 4 };// prints y = {4,2,5,1,3}
// x = 1 = p(3) = p(p(4)) = p(p(y)) => y = 4
int s = 5;
int[] p = { 5, 2, 1, 3, 4 };
int[] result = new int[s] ;
PE(p, result);
int n = result.Length;
//List<int> result = new List<int>(PE(p));
//int n = result.Count();
for (int i = 0; i < n; i++)
Console.WriteLine(result[i]);
Console.ReadLine();
}
}
}