עבור לתוכן
View in the app

A better way to browse. Learn more.

HWzone

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

שאלה ב c++ בנוגע ל templates ו iterators

Featured Replies

פורסם

שלום לכולם

אני עובד כרגע על תוכנה (ב c++) שבה יש לי מחלקה שמקבלת את סוג ה container כטיפוס ב template:

template <class Cont> class MyClass
{
//..
}

כשה container הוא מה STL ותמיד של מחרוזות.

במחלקה יש לי פוקציה שמחזירה iterator לפי אינדקס:

template <class Cont> 
typename Cont::const_iterator MyClass<Cont>::GetIteratorOf(const Cont& c, int i)
{
Cont::const_iterator iter = c.begin();
while ((i-- > 0) && iter != c.end()
++iter;
return iter;
}

אני רוצה לעשות specialization עבור vector של מחרוזות כך שלא יעבור בלולאה אלא יבצע גישה בעזרת האינדקס. השאלה שלי היא איך אני יוצר iterator עבור איבר מסויים ב vector כך שאני אהיה בטוח שלא מתבצעת שום לולאה?

אני עובד עם VS2005.

תודה

פורסם

אני לא בטוח, אבל נראה לי שאתה יכול לממש את זה ככה:

template <> 
typename vector::const_iterator MyClass<vector>::GetIteratorOf(const vector& c, int i)
{
vector::const_iterator iter = c.begin();
iter += i;
return iter;
}

(סלח לי אם יש לי טעות ב-syntax של ה-specialization)

יכול להיות שזה יעבוד גם עבור קונטיינרים אחרים.

פורסם

בוקטור אתה יכול פשוט לבצע את זה בשביל לקבל תוכן של תא

c[i]

אם הבנתי נכון את השאלה שלך...

פורסם

הבעיה היא ש

c[i] 

לא מחזיר איטרטור, אלא את התוכן של התא - ולכן זה לא יעבוד.

פורסם
  • מחבר

בדקתי והאופרטור += מוגדר רק עבור random access iterators. זה יעבוד עבור ה vector.

תודה!

פורסם

יש את אלגוריתם STL שנקרא advance. למיטב זכרוני (אין לי רפרנס מולי):


iteratorOfIndexN = v.begin();
std::advance( iteratorOfIndexN, n );

פורסם
  • מחבר

צודק, שכחתי ממנו. בדקתי גם לגבי המימוש שלו ועבור iterator שהוא random access נעשה שימוש באופרטור += ככה שהוא מתאים לי בדיוק.

תודה

ארכיון

דיון זה הועבר לארכיון ולא ניתן להוסיף בו תגובות חדשות.

דיונים חדשים

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.