GeorgeCostanza
GeorgeCostanza

Reputation: 395

Iterate through vector up to specific element in vector

I'm trying to iterate through a vector, but I need it to stop at a certain element, because I only want to cout a specific number of elements within the vector

For instance, I have a vector of structs (Relevance) and I need to cout the first 2 elements in the vector (this number will depend on user input)

for(std::vector<Relevance>::const_iterator it = RelStructs.begin(); it < RelStructs[2]; ++it)
{

 cout << "\nDesc2: " << it->desc2 << "\n";  // desc2 is a variable within the Relevance struct

 cout << "Relevance2: " << it->relevance2 << "\n\n"; // relevance2 is a variable within the Relevance struct

I know this code won't work, but I'm trying to do something like this. Thanks

Upvotes: 0

Views: 461

Answers (4)

johnsyweb
johnsyweb

Reputation: 141790

Assuming your class has a suitable operator << defined, you could use std::copy_n() and std::ostream_iterator instead of rolling your own for-loop:

size_t number_of_elements = 2;
std::copy_n(std::begin(RelStructs),
    std::min(number_of_elements, RelStructs.size()),
    std::ostream_iterator<Relevance>(std::cout, "\n"));

The call to std::min() ensures you don't run off the end of RelStructs, particularly since number_of_elements comes from user input.

Your operator << would probably look something like this (and would be usable elsewhere, I am sure):

std::ostream& operator <<(std::ostream& os, Relevance const& rel)
{
    return os << "\nDesc2: " << rel.desc2 << "\n" << "Relevance2: " 
              << rel.relevance2 << "\n\n";
}

Upvotes: 1

yasouser
yasouser

Reputation: 5177

If userEnteredNumber is the number up to which you need to iterate through the vector, then the following should work:

for (int i = 0; userEnteredNumber < RelStructs.size() && i < userEnteredNumber; i++)
{
    std::vector<RelStructs> v = RelStructs[i];
    // do something with v.
}

Upvotes: 1

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153820

Just iterate over the sequence v.begin(), v.begin() + std::min<std::size_t>(count, v.size()):

for (std::vector<Relevance>::const_iterator it(RelStructs.begin()),
     end(it + std::min<std::size_t>(RelStructs.size(), count);
     it != end; ++it) {
    ...
}

Upvotes: 1

john
john

Reputation: 87959

Simple, just add the number you want to begin()

for (std::vector<Relevance>::const_iterator it = RelStructs.begin(); 
    it < RelStructs.begin() + 2; ++it)
{

Upvotes: 2

Related Questions