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

标签 c++

问:

arr1[]={1,1,1,2,5,5,6,6,6,6,8,7,9}

和:

values[]={1,2,5,6,7,9}

问:

arr1[]={1,1,1,2,5,5,6,6,6,6,8,7,9,101,1502,1502,1,9}

答案:

values[]={1,2,5,6,7,9,101,1502}

这是我试过但没有用的

   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; 
           }
       }
   }

最佳答案

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

  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}
}

另一个版本可以返回集合,而不是引用它。那么它将是:

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}
}

关于c++ - 如何从不同大小的数组中获取不同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3616205/

相关文章:

c++ - 在 C/C++ 中使用单个初始化来初始化具有相同值的多个指针

c++ - 使用 C++17 或更高版本对 vector 中的元素对求和的大多数 'functional' 方法?

c++ - 在循环内删除文件时 boost recursive_directory_iterator 失效

c++ - 当操作返回 0.#INF 时,我可以得到异常吗?

c++ - 如何在给定数组中找到某个固定给定长度的每个子数组的最大值

c++ - 使 -std=c++11 成为 mac 终端的默认值

c++ - 下面最后一句话(粗体)与复制抛出的异常有什么关系?

c++ - thread_local 的替代方法,用于在 OSX 上调用遗留 C 代码

c++ - 在 .NET Core 3.1 中运行托管 C++/CLI 程序集时出现错误的图像格式

c++ - 局部变量模板的实例化