简体   繁体   中英

Iterate a vector in C++

I have a vector:

std::vector<std::pair<int, long> > v;
v.push_back(std::make_pair(1, 2L));
etc...

How can I iterate through it and get out the int and the long elements from it?

Using C++03:

for (std::vector<std::pair<int, long> >::iterator i = v.begin(); i != v.end(); ++i)
{
    std::cout << "int: " << i->first << " long: " << i->second << std::endl;
}

Using C++11:

for (std::pair<int, long> p : v) // could also do auto p, auto& p, or (const) std::pair<int, long>& p
{
    std::cout << "int: " << p.first << " long: " << p.second << std::endl;
}

The short answer is: "by strong preference, with an algorithm". The real question is what you're going to do with the items. To use @cornstalks' example, if you want to print them out, you could do something like this:

typedef std::pair<int, long> v_t;

std::vector<v_t> v;

std::ostream &operator<<(std::ostream &os, v_t const &p) { 
    return os << p.first << "\t" << p.second;
}

std::copy(v.begin(), v.end(), std::ostream_iterator<v_t>(std::cout, "\n"));

Let's try something else. Maybe you want to add the items together -- ie, get a pair<int, long> in which each item is the sum of the corresponding items from the array:

std::accumulate(v.begin(), v.end(), std::make_pair(0,0L), 
               [](v_t const &a, v_t const &b) { 
                    return std::make_pair(a.first+b.first, a.second+b.second); 
               });

Note that in this case, I'm assuming a (reasonably) recent C++ compiler. The [](params){statement;} part is a "lambda" -- basically an in-place definition of a function object. It was officially added to C++ in the 2011 standard, but was known about enough before 2011 that most compilers since around 2009 implement them (eg, Visual Studio 2010 and gcc going back to at least 4.7 both do).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM