user1871268
user1871268

Reputation: 13

Loop for container class c++

I have this loop

for(int i=0;i<vec1.size();++i)
{
    if(vec1[i]==*p)
    {
        vec1[i]=*p;
        cout<<"element updated"<<endl;
    }
    else
    {
        cout<<"push_back"<<endl;
        vec1.push_back(*p);
    }
}

I'm inserting objects in container class and I've overloaded the == to check two parameters inside the object and if they match I want to update the them and if they don't match I want to put them in the vector, but I don't seem to be able to properly populate my vector, when I do vec1.size() I get 0 even when I insert 3 objects.

Upvotes: 0

Views: 196

Answers (2)

Robᵩ
Robᵩ

Reputation: 168596

You're problem is that your if is inside your search loop. Your if will never be executed, because your loop body never runs, because your .size() will never be greater than 0.

Try this:

// UNTESTED
std::vector<person> vec1;
add(person *p) {
  std::vector<person>::iterator it = std::find(vec1.begin(), vec1.end(), *p);
  if(it == vec1.end())
    vec1.push_back(*p);
  else
    *it = *p;
}

Or, if you really want to code the loop by hand:

// UNTESTED
std::vector<person> vec1;
add(person *p) {
  int i;
  for(i=0;i<vec1.size();++i) {
    if(vec1[i] == *p)
      break;
  }
  if(i == vec1.size())
    vec1.push_back(*p);
  else
    vec1[i] = *p;
}

Of course, you might consider changing your container. Using a std::map would shorten your code and reduce the time it takes to manipulate large data sets.

std::map<std::string, person> map1;
add(person *p) {
  map1[p->name] = *p;
}

Upvotes: 1

digit plumber
digit plumber

Reputation: 1172

When the vec1 starts from empty, the for loop is not going to run. So you want to have at least one element in vec1 to start with. How about add this:

vec1.push_back(*p);
for(int i=0;i<vec1.size();++i){//the rest}

Upvotes: 0

Related Questions