Iterator/IEnumerator in c++ and c# as Function/Method Parameters and Arguments 65

Опубликовано: 14 Февраль 2026
на канале: Arif Mahmood
140
1

Shows how to #define and #use #iterator and #IEnumerator in a c plus plus and c sharp #program. Shows how to use Iterators and IEnumerators as #function #parameters and #arguments.How to #pass iterators as function parameters.

c++ code:


#include <iostream> //for cout
#include <fstream> // for ofstream/ifstream
#include <string> //for << and getline
#include<list> //for lists

void show(std::ostream &out, std::list<std::string>::const_iterator iter)
{
out << *iter << std::endl;
}

void pushin(std::ofstream &output_file, std::list<std::string>::const_iterator iter)
{
output_file << *iter << std::endl;
}

int main()
{
std::string in_file = "test.txt";
std::string out_file= in_file + ".out";

std::ifstream input_file(in_file.c_str());
std::ofstream output_file(out_file.c_str());

std::list<std::string> elements;

std::string line;
for (; std::getline(input_file, line); )
{
elements.push_back(line);
}

std::list<std::string>::const_iterator iter = elements.begin();
for (; iter != elements.end(); ++iter)
{
//std::cout << (*iter) << std::endl;
//output_file << (*iter) << std::endl;
show(std::cout, iter);
pushin(output_file, iter);
}

if (input_file)
{
input_file.close();
output_file.close();
}
std::cin.get();
return 0;
}

c# code:

using System;
using System.Collections.Generic;//for string
using System.IO;//to use StreamReader
namespace lec2csharp
{
class Program
{
static void Show(StreamWriter Out, IEnumerator< string> iter)
{
Console.WriteLine(iter.Current);
}

static void Pushin(StreamWriter output_file, IEnumerator<string> iter)
{
output_file.WriteLine(iter.Current);
}

static void Main()
{
StreamWriter output = null;

string in_file = "test.txt";
string out_file = in_file + ".out";

StreamReader input_file = new StreamReader(in_file.ToString());
StreamWriter output_file = new StreamWriter(out_file.ToString());

List<string> elements = new List<string>();

string line = "";
for (; (line = input_file.ReadLine()) != null;)
{
elements.Add(line);
}

IEnumerator<string> iter = elements.GetEnumerator();
for (; iter.MoveNext();)
{
//Console.WriteLine(iter.Current);
//output_file.WriteLine(iter.Current);
Show(output, iter);
Pushin(output_file, iter);
}

if (input_file != null)
{
input_file.Close();
output_file.Close();
}
Console.ReadLine();
}
}
}


#cplusplus #csharp #tutorial