zoukankan      html  css  js  c++  java
  • Essential C++ 3.1 节的代码练习——指针方式

    //
    //  PointerToValue.cpp
    //  Working
    //
    //  Created by Hawkins, Dakota Y on 6/3/16.
    //  Copyright  2016 Hawkins, Dakota Y. All rights reserved.
    //
    
    #include "PointerToValue.hpp"
    #include <cstdio>
    #include <vector>
    #include <iostream>
    
    using namespace std;
    
    
    
    template <typename element> 
    element *find_value(vector<element> &vec, element value)
    {
        for (int i = 0; i < vec.size(); i++)
        {
            if (vec[i] == value)
            {
                return &vec[i];
            }
        }
        return 0;
    }
    
    
    
    
    template <typename T> 
    T *find_value(T *array, int size, T value)
    {
        if (! array || size < 1)
        {
            return 0;
        }
        for (int i = 0; i < size; i++)
        {
            if (array[i] == value)
            {
                return &array[i];
            }
        }
        return 0;
    }
    
    
    template <typename element>
    int find_pos(vector<element> &vec, element value)
    {
        int pos_val;
        for (int i = 0; i < vec.size(); i++)
        {
            if (vec[i] == value)
            {
                pos_val = i;
                return pos_val;
            }
        }
        return 0;
    }
    
    int main()
    {
        int int_array[5] = {13, 3, 34, 42, 53};
        string str_array[5] = {"Hello", ",", "how", "are", "you?"};
        float float_array[5] = {0.123, 4.5, 10.1, 5.7, 10};
    
        vector<int> int_vector(int_array, int_array + 5);
        vector<string> str_vector(str_array, str_array + 5);
        vector<float> float_vector(float_array, float_array + 5);
    
        cout << "pos of 3 = " << find_pos(int_vector,53) <<endl;
    
        cout << "Pointer of '3' in 'int_vector': " << find_value(int_vector, 3) << endl;
        //cout <<*(find_value(int_vector, 3))<<endl;    //cout the value of 3
    
        cout << "Pointer of 'Hello' in 'str_vector': " << find_value(str_vector, string("Hello")) << endl;
    
        float f_test = 11.1;
        cout << "Pointer of '11.1' in 'float_vector': " << find_value(float_vector, f_test) << endl;
    
        float first_value = float_array[1];
        cout << "Pointer of 4.5 in 'float_array': " << find_value(&first_value, int(5), float(4.5)) << endl;
        return 0;
    }

    输出:

    pos of 3 = 4
    Pointer of '3' in 'int_vector': 0x1c1554
    Pointer of 'Hello' in 'str_vector': 0x1c1a50
    Pointer of '11.1' in 'float_vector': 0
    Pointer of 4.5 in 'float_array': 0x73fc8c
  • 相关阅读:
    c/c++:字符串输入输出流
    POJ 1036Gangsters【DP】
    POJ 1157LITTLE SHOP OF FLOWERS【DP】
    一个月后....
    http://poj.org/problem?id=1258
    POJ 2677 Tour【DP】
    POJ 1160Post Office【DP】
    C基础
    linux面试fork函数题
    linux学习
  • 原文地址:https://www.cnblogs.com/CodeWorkerLiMing/p/10991926.html
Copyright © 2011-2022 走看看