| |

VerySource

 Forgot password?
 Register
Search
View: 743|Reply: 3

Simple questions. How does the STL list locate an element at a specified position?

[Copy link]

1

Threads

1

Posts

2.00

Credits

Newbie

Rank: 1

Credits
2.00

 China

Post time: 2020-1-31 09:00:02
| Show all posts |Read mode
For example, I want to get the 7th element in the list from begin. How can I get this?
Please give an example!
Reply

Use magic Report

0

Threads

2

Posts

2.00

Credits

Newbie

Rank: 1

Credits
2.00

 China

Post time: 2020-3-23 12:15:01
| Show all posts
typedef yourtype ltype;
std :: list <ltype> yourlist;
typedef std :: list <ltype> :: iterator pos = yourlist.begin ();
for (unsigned int i = 0; pos! = yourlist.end (); pos ++)
{
  i ++;
  if (i == 7)
    break;
}
if (i == 7)
  ltype lt = * pos;

Where yourtype is your type in the list
Reply

Use magic Report

0

Threads

2

Posts

2.00

Credits

Newbie

Rank: 1

Credits
2.00

 China

Post time: 2020-3-23 14:15:01
| Show all posts
As for yourlist is your list variable
Reply

Use magic Report

0

Threads

5

Posts

5.00

Credits

Newbie

Rank: 1

Credits
5.00

 China

Post time: 2020-3-26 19:15:02
| Show all posts
You can use iterators directly at specified positions ++
for (it = mylist.begin (), i = 0; it! = mylist.end (); it ++, i ++)
{
    if (i> 6)
        break;
}
if (i == 7)
{...} // found
Reply

Use magic Report

You have to log in before you can reply Login | Register

Points Rules

Contact us|Archive|Mobile|CopyRight © 2008-2023|verysource.com ( 京ICP备17048824号-1 )

Quick Reply To Top Return to the list