vector subscript operator overloadig

Hi,

To get a value I would always use setter and getter.
Would it be much better (performance) to use vector subscript operator overloading?

and does vector subscription operator overloading require a size for the vector?
vector<int> v(10);

because otherwise, it doesn't work


~slei
Technically, operators are syntax sugar for specific functions. So only bonus you will have is better (probably) interface.

and does vector subscription operator overloading require a size for the vector?
I don't get your question.
std::vector subscript operator takes integral value representing index of element you want to access.
You are not limited to integers (or single argument) if you want to provide overload for your own class. For example std::map has operator[] overload for key type. That means if you have std::map<std::string int> x, you can do x["hello"] = 5;
Last edited on
just using vector<int> v;
doesn't work
It works:
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <vector>

int main()
{
    std::vector<int> v;
    std::cout << v.size() << '\n';
    v.push_back(42);
    std::cout << v.size() << '\n';
}
0
1


But you should know that default constructed vector has 0 elements and does not have valid indexes, so using subscript operator on it is meaningless and illegal. As soon as you add at least one element, you can use index of that element in subscript operator.
Last edited on
So this doesnt work?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
vector<int> vec;

int& v::operator [](int i)
{
    return vec[i];
}


int main()
{
    QCoreApplication a(argc, argv);

    v vi;
    cout << "before" << endl;
    vi[0] = 3;
    cout << "after " << endl;
    cout << vi[0] << endl;


    return 0;
}
What is the v class? why its operator refers to some global vector?
And no, vec does not contain any elements yet, so you cannot access them until you add them.
vector and the operator overload should be in a own class called v

so first i have to use vec.push_back() anyway ?
or give it a size like vector<int> vec(size)
Last edited on
Or use a vec.resize(size) or any other of many variants of vector manipulation
i thought, using vector[0] = 1 would automatically add it as item to the vector, by using the operator overload.
ok, now i understand :)
For maps it does add unexistent elements to it. For vector it is just access to existing element without bouds checking.

It would be a problem if vector creates elements when they are accessed.
For example you have vector with one element and you do v[100] = 42. What should happen to elements 1-99? What state they should be in? How to effectively store all that information?
Because of that, vector do not add or remove values automatically.

In your class, you can make your overload to do those things if you want.
Topic archived. No new replies allowed.