如何设置0索引的矢量值?

时间:2014-05-11 12:13:40

标签: c++

我在Array类的构造函数中用n个元素初始化了数组。现在,如果我想设置这些元素的值,那么通过使用'set function',在n + 1索引之后设置值。如何设置矢量0索引的值?

    #include<iostream>
    #include<stdio.h>
    #include<vector>
    using namespace std;
    class Array{
        vector<int> array;
    public:
        Array(int n):array(n){}

        int binarySearch(int n,int i,int f)
        {
            int mid= (i+f)/2;
            if(i!=f || array[mid]==n){     
                if(array[mid] == n)            
                    return mid;           
                else if(array[mid] < n)
                    return binarySearch(n,mid+1,f);
                else
                return binarySearch(n,i,mid-1);
            }
            else
               return NULL;
        }

        int set(int n){
            array.push_back(n);
        }

        int size(){
            return array.size();
        }

        void print(){
            int i=0;
            while(i<array.size()){
                cout<<array[i]<<endl;i++;
            }
        }
     };

int main()
{
    cout<<"ENter no. of element for the array to be initialized with"<<endl;
    int n,x;
    cin>>n;
    Array a(n);
    for(int i=0;i<n;i++){
        cin>>x;
        a.set(x);
    }
    cout<<"Enter the no. to be searched"<<endl;
    cin>>x;
    cout<<a.binarySearch(x,0,a.size());
    return 1;
}

2 个答案:

答案 0 :(得分:0)

push_back推送到数组的后面,即追加在构造函数中创建的n元素之后。您可以使用[]运算符单独设置元素。或者如果你将它们全部设置为相同,我认为有一个构造函数。

答案 1 :(得分:0)

无需使用a对象创建n数组。 只需从用户处获取n个数字,然后使用set方法将其推送到向量中