我想检查一个元素是否存在于特定的向量位置,比如 i,然后像 v[i] 一样访问它。你能让我知道我该怎么做吗?
谢谢你。
if (0 <= i && i < v.size()) {
// OK
std::cout << v[i]; // Example
} else {
// Wrong
}
保证元素存在于每个位置i,因为向量是元素的连续序列,i >= 0并且i < v.size()不可能出现“洞”。
使用v.size().
如果你想知道向量中是否存在某个元素,最快的方法是对数组进行排序,然后使用搜索方法,例如二分查找。
如果多次执行此操作,则更改数据结构可能会产生更好的性能。std::map 对此很有用,如果您的编译器有,请使用哈希表或映射。
否则,在不访问向量的情况下确定向量中是否存在值的唯一方法是使用第二个数据结构来记住值和位置。
I understand you have a std::vector preallocated at a specific dimension, let's say n, and you want to see if the element at index i (i < n) was initialized or is just allocated.
Like @Thomas Matthews said, you can use a second data structure, a simple bool[n], in which, at index k, you store true if the element at index k in your vector exists and false otherwise.
0 1 2 3 4 5
v = [ * * * * ]
0 1 2 3 4 5
exists = [ true, false, true, false, true, true ]