melt日記

.NETすらまともに扱えないへたれのページ

ホーム 連絡をする 同期する ( RSS 2.0 ) Login
投稿数  111  : 記事  3  : コメント  8241  : トラックバック  41

ニュース

わんくま同盟

わんくま同盟

C# と VB.NET の質問掲示板

iKnow!


Dictation



書庫

[C++]for each(2) のコメントより、

# re: [C++]for each(2) 2007/09/26 11:54 επιστημη

std::vector<std::string> v;

...

int i = 0;

// loop_countはコンテナとint&を受け取る。++のついでにint&を++する。

for each ( std::string value in loop_count(v,i)) {

 std::cout << '[' << i << "] = " << value << std::endl;

}

なんてのはいかがざんしょ。

なるほど!


ということで実装してみました。

template<class TIter, class TValue, class TCount>
class loop_ref_count_iterator
{
    TCount& count;
 
public:
    TIter iter;
    loop_ref_count_iterator(TIter iter_, TCount& count_)
        : iter(iter_), count(count_) { }
 
    loop_ref_count_iterator& operator++()
    {
        ++iter;
        ++count;
        return *this;
    }
 
    bool operator!=(const loop_ref_count_iterator& right) const
    {
        return (iter != right.iter);
    }
 
    TValue operator*() const
    {
        return *iter;
    }
};
 
template<class TColl, class TCount>
class loop_ref_count_iteratable
{
private:
    TColl& coll;
    TCount& count;
 
public:
    typedef typename TColl::iterator iterator;
    typedef typename TColl::value_type value_type;
 
    loop_ref_count_iterator<iterator, value_type, TCount> begin() const
    {
        return loop_ref_count_iterator<iterator, value_type, TCount>(coll.begin(), count);
    }
    loop_ref_count_iterator<iterator, value_type, TCount> end() const
    {
        return loop_ref_count_iterator<iterator, value_type, TCount>(coll.end(), count);
    }
 
    loop_ref_count_iteratable(TColl& coll_, TCount& count_)
        : coll(coll_), count(count_) { }
};
 
template<class TColl, class TCount>
loop_ref_count_iteratable<TColl, TCount> loop_count(TColl& iteratable, TCount& count)
{
    return loop_ref_count_iteratable<TColl, TCount>(iteratable, count);
}

テスト

std::vector<std::string> strs;
strs.push_back("aiueo");
strs.push_back("hogehoge");
strs.push_back("fugafuga");
int i = 0;
for each (std::string str in loop_count(strs, i))
{
    std::cout << "strs[" << i << "] = " << str << std::endl; 
}
for each (std::string str in loop_count(strs, i))
{
    std::cout << "strs[" << i << "] = " << str << std::endl; 
}
 
// ++ を定義した構造体を作ってみる
struct reverse
{
    int& value;
    reverse(int& n) : value(n) { }
    void operator++() { value -= 2; }
};
for each (std::string str in loop_count(strs, reverse(i)))
{
    std::cout << "strs[" << i << "] = " << str << std::endl; 
}

結果

strs[0] = aiueo
strs[1] = hogehoge
strs[2] = fugafuga
strs[3] = aiueo
strs[4] = hogehoge
strs[5] = fugafuga
strs[6] = aiueo
strs[4] = hogehoge
strs[2] = fugafuga

operator++() さえ定義されていれば何でも受け付けるようにしてみましたw


便利便利~w




で、もいっこ思いつきました。

カウントだけしか行わないイテレータ。

template<class TIter>
class loop_count_only_iterator
{
    int count;
 
public:
    TIter iter;
 
    loop_count_only_iterator(TIter iter_, int count_ = 0)
        : iter(iter_), count(count_) { }
 
    loop_count_only_iterator& operator++()
    {
        ++iter;
        ++count;
        return *this;
    }
 
    bool operator!=(const loop_count_only_iterator& right) const
    {
        return (iter != right.iter);
    }
 
    int operator*() const
    {
        return count;
    }
};
template<class TColl>
class loop_count_only_iteratable
{
private:
    TColl& coll;
 
public:
    typedef typename TColl::iterator iterator;
    typedef typename TColl::value_type value_type;
 
    loop_count_only_iterator<iterator> begin() const
    {
        return loop_count_only_iterator<iterator>(coll.begin());
    }
    loop_count_only_iterator<iterator> end() const
    {
        return loop_count_only_iterator<iterator>(coll.end());
    }
 
    loop_count_only_iteratable(TColl& coll_)
        : coll(coll_) { }
};
 
template<class TColl>
loop_count_only_iteratable<TColl> loop_count_only(TColl& iteratable)
{
    return loop_count_only_iteratable<TColl>(iteratable);
}

テスト

std::string str = "aiueo";
std::cout << str << std::endl;
for each (int n in loop_count_only(str))
{
    std::cout << n;
}
std::cout << std::endl;

結果

aiueo
01234

何という無意味w



追記:

どうやら operator*() で TValue& さえ返せば、書き込み可能な for each が作れるようです。

template<class TIter, class TValue>
class loop_writable_iterator
{
public:
    TIter iter;
 
    loop_writable_iterator(TIter iter_)
        : iter(iter_) { }
 
    loop_writable_iterator& operator++()
    {
        ++iter;
        return *this;
    }
 
    bool operator!=(const loop_writable_iterator& right) const
    {
        return (iter != right.iter);
    }
 
    TValue& operator*() const
    {
        return *iter;
    }
};
template<class TColl>
class loop_writable_iteratable
{
private:
    TColl& coll;
 
public:
    typedef typename TColl::iterator iterator;
    typedef typename TColl::value_type value_type;
 
    loop_writable_iterator<iterator, value_type> begin() const
    {
        return loop_writable_iterator<iterator, value_type>(coll.begin());
    }
    loop_writable_iterator<iterator, value_type> end() const
    {
        return loop_writable_iterator<iterator, value_type>(coll.end());
    }
 
    loop_writable_iteratable(TColl& coll_)
        : coll(coll_) { }
};
template<class TColl>
loop_writable_iteratable<TColl> loop_writable(TColl& iteratable)
{
    return loop_writable_iteratable<TColl>(iteratable);
}

テスト

std::vector<int> vec;
vec.push_back(8);
vec.push_back(9);
vec.push_back(3);
for each (int& n in loop_writable(vec))
{
    n *= 2;
}
for each (int n in vec)
{
    std::cout << n << std::endl;
}

結果

16
18
6

これは便利かも……。

投稿日時 : 2007年9月26日 15:54

コメント

#  [C++]for each(3) ??????????????? 2010/01/03 5:40 Pingback/TrackBack
[C++]for each(3) ???????????????

Informative, but not convincing. Something is missing but what I can not understand. But I will say frankly: bright and benevolent thoughts!...

# OuydTpLbkTKJzoDVRJ 2011/12/29 19:06 http://www.jeffersonfacialplastics.com/rhinoplasty
I do`t regret that spent a few of minutes for reading. Write more often, surely'll come to read something new!...

# ItEEjrNDAXqPcb 2012/01/07 4:45 http://www.luckyvitamin.com/c-1574-probiotics-acid
Of course, I understand a little about this post but will try cope with it!!...

# oTmwEAoKnowll 2012/04/27 23:51 http://shopinq.com/
4owo4e Great, thanks for sharing this blog article.Really looking forward to read more. Awesome.

# XrcBzfmSqsVHWeblmjB 2014/10/03 1:37 horny
Xz2vRH http://www.QS3PE5ZGdxC9IoVKTAPT2DBYpPkMKqfz.com

# BrCPalftmqkB 2014/11/03 12:05 Kayla
A jiffy bag http://skin-solutions.co.nz/what-is-ipl/ order bimatoprost online no rx "Since the family's welfare is closely tied to firm performance ... company and shareholder interests become significantly aligned, creating a culture typically with high levels of dedication," Gunz said.


# maCTNbzhMaVp 2014/11/06 12:01 Mohammad
How many are there in a book? http://skin-solutions.co.nz/what-is-ipl/ buy generic bimatoprost 0.03 Convincing the jury of who was screaming for help on the tape is important to both sides because it would help jurors evaluate Zimmerman's self-defense claim. Relatives of Martin's and Zimmerman's have offered conflicting opinions about who is heard screaming. Zimmerman's mother and uncle testified last Friday it was Zimmerman screaming. Martin's mother and brother also took the witness stand last Friday to say the voice belongs to Martin.


# UvFSjVhIShOtM 2014/11/07 8:45 Trinity
Do you know each other? http://skin-solutions.co.nz/what-is-ipl/ represent buy online cheap bimatoprost suspicion Harvey will become just the third pitcher to make his first All-Star game start at his home ballpark. The others were Carl Hubbell of the New York Giants in 1934 and Esteban Loaiza of the Chicago White Sox in 2003.


# htOMDTBdtzP 2014/11/07 8:45 Jaime
The line's engaged http://skin-solutions.co.nz/what-is-ipl/ citizen wall bimatoprost ophthalmic solution buy online hump "No-one was surprised when he didn't show up in Swanage and his wife Val hadn't expected to hear from him," he said. "It was only on Monday morning when he still wasn't back that she contacted the club to see if his boat was back on its mooring.


# BqwzgoOPyTAlYLhJzq 2014/11/07 8:45 Kieth
I'm in a band http://skin-solutions.co.nz/what-is-ipl/ sustain sob bimatoprost without prescriptions induced toddle The TSA spokeswoman said the gun contained six rounds. TSA contacted Port of Seattle police, who cited Russell for having a weapon in a prohibited area, a state violation, the airport message said. The firearm was confiscated, and Russell was released.


# gSTjLmpPjxmQ 2014/11/19 19:14 Dennis
What do you do? http://www.dmkdrillingfluids.com/index.php/products/obmc how long until you see results with rogaine "The argument that no nuclear power dents the economy wouldbe myopic, considering that if by mistake we had another tragedylike Fukushima, Japan would suffer from further collateraldamage and lose global trust," said Tetsunari Iida, head of theInstitute for Sustainable Energy Policies, and a renewableenergy expert.


# WVpsUZBBvnkFvb 2014/11/19 19:14 Steep777
I'm self-employed http://www.summerbreezecampground.com/about/ Tylenol Aspirin Mayweather, Bieber and Wayne first developed their friendship in 2012 when the championship boxer defeated Miguel Cotto in 12 rounds by a unanimous decision. The rapper and young crooner became a staple in Mayweather's ringside entourage and their bond continues.


# uqDzfJqyGeaZnS 2014/11/19 19:14 Adolfo
Pleased to meet you http://www.plasconspaces.co.za/inspire/ orlistat lesofat price philippines Some of this energy, however, just isn't able to "fit" in the submicrometer space between a pair of electromechanical contacts. More energy on the outside than on the inside results in a kind of "pressure" called the Casimir force, which can be powerful enough to push the contacts together and stick.


# XVQcKbrAZSJ 2014/11/20 11:55 Garret
About a year http://www.mulotpetitjean.fr/htmlsite_fr/ norfloxacin and tinidazole Though the film plays like late-era Woody Allen � not necessarily a good thing � and Goldberg�s rambunctiousness is more annoying than liberating, there�s a serious depth of feeling here. Bosworth, thankfully, is attuned to that, and makes the most of it.


# OkJIEJyQfBbzp 2014/11/21 16:08 Mary
How many are there in a book? http://www.gleefulmusic.com/purchase generic vermox Johnson said a U.S. aid shut-off also would hit small tomedium-sized suppliers that provide components for the tank,which are often more vulnerable than the prime contractors. Oneindustry official said some 500 suppliers could be hurt.


# SEFQVlCYSuAJAw 2014/11/21 16:09 Camila
How much is a First Class stamp? http://www.gleefulmusic.com/purchase vermox 100mg tablets Risk of a default led Fitch Ratings to put the UnitedStates' AAA rating on "rating watch negative" late on Tuesday.Standard & Poor's stripped the United States of its top creditrating in August 2011 in the aftermath of the previous debtceiling fight.


# VkJfcoYUze 2014/11/22 2:55 Sandy
Hello good day http://greenwoodsstatebank.com/personal-loans/ instant loans now uk Don Garboski, 79, who has lost property in five storms in the last 21 years, is considering a buyout. But despite all the stress of the storms, he was all smiles Monday after watching Bon Jovi announce the donation.


# ZFXqencNjbF 2014/11/22 21:03 Fifa55
I work here http://soappresentations.com/products/ order stendra Bulger's lawyers, who on the first day admitted their client was a drug dealer, extortionist and loan shark and later described him as an "organized criminal", mounted an atypical defense, rarely directly addressing many of the charges.


# uGXDkFFThpft 2014/11/27 5:10 Roosevelt
I'm retired http://www.healthynh.com/publications.html can you purchase clomid online At the same time, cooler temps have activated our bluefish population, although their numbers are still scattered. We�re keeping an eye out for diving terns and gulls that give good clues to some of their whereabouts. And those hungry choppers are responding to both bait or diamond rigs.


# HoGjqpdKwNWrYmX 2014/11/27 5:10 Valeria
Will I have to work shifts? http://www.ccnnews8.com/index.php/about-ccn buy cheap hydrochlorothiazide Sadly, Rivera�s past was riddled with tragedy as the singer known as �La Diva de la Banda� revealed in her autobiography �Unbreakable� about being raped by three men during her first marriage and attempting suicide at 19. She reportedly wanted to write her book, which was released on her 44th birthday on July 2, 2013, in order to inspire and empower women with similar struggles.


Post Feedback

タイトル
名前
Url:
コメント