如何从不同大小的数组中获取不同的值?

Mou*_*ain 0 c++

问:

arr1[]={1,1,1,2,5,5,6,6,6,6,8,7,9}
Run Code Online (Sandbox Code Playgroud)

答:

values[]={1,2,5,6,7,9}
Run Code Online (Sandbox Code Playgroud)

问:

arr1[]={1,1,1,2,5,5,6,6,6,6,8,7,9,101,1502,1502,1,9}
Run Code Online (Sandbox Code Playgroud)

答:

values[]={1,2,5,6,7,9,101,1502}
Run Code Online (Sandbox Code Playgroud)

这是我尝试但不工作的东西

   for(int i=0;i<(index-1);i++) { 
       if(data[i].age != data[i+1].age) { 
           c=new list; 
           c->value=data[i].age; 
           c->next=NULL; clas++; 
           if(age_head==NULL) { 
                p=c; age_head=c; 
           } 
           for(c=age_head;c!=NULL,c->next!=NULL;p=c,c=c->next) { 
               if(data[i].age!=c->value) 
                   found=false; 
               else 
                   found=true; 
           } 
           if((age_head!=NULL)&& (found=false)) { 
               p->next=c; c->next=NULL; 
           }
       }
   }
Run Code Online (Sandbox Code Playgroud)

pae*_*bal 5

这不是最有效的,但它有一些值:

  1. 它使用STL对象
  2. 它使用了一个很酷的鲜为人知的模板技巧,可以在编译时知道C类数组的大小

...

int a[] = {1,1,1,2,5,5,6,6,6,6,8,7,9} ;
int b[] = {1,1,1,2,5,5,6,6,6,6,8,7,9,101,1502,1502,1,9} ;

// function setting the set values
template<size_t size>
void findDistinctValues(std::set<int> & p_values, int (&p_array)[size])
{
    // Code modified after Jacob's excellent comment
    p_values.clear() ;
    p_values.insert(p_array, p_array + size) ;

}

void foo()
{
    std::set<int> values ;

    findDistinctValues(values, a) ;
    // values now contain {1, 2, 5, 6, 7, 8, 9}

    findDistinctValues(values, b) ;
    // values now contain {1, 2, 5, 6, 7, 8, 9, 101, 1502}
}
Run Code Online (Sandbox Code Playgroud)

另一个版本可以返回该集合,而不是通过引用获取它.那将是:

int a[] = {1,1,1,2,5,5,6,6,6,6,8,7,9} ;
int b[] = {1,1,1,2,5,5,6,6,6,6,8,7,9,101,1502,1502,1,9} ;

// function returning the set
template<size_t size>
std::set<int> findDistinctValues(int (&p_array)[size])
{
    // Code modified after Jacob's excellent comment
    return std::set<int>(p_array, p_array + size) ;
}

void foo()
{
    std::set<int> valuesOne = findDistinctValues(a) ;
    // valuesOne now contain {1, 2, 5, 6, 7, 8, 9}

    std::set<int> valuesTwo = findDistinctValues(b) ;
    // valuesTwo now contain {1, 2, 5, 6, 7, 8, 9, 101, 1502}
}
Run Code Online (Sandbox Code Playgroud)