I want to write a function which can modify element for all container which space is continueous, like, vector, int*. char* ....
here is my code:
#include <vector>
#include <string>
#include <iostream>
using namespace std;
template <typename T>
void test(T* t, size_t size) {
for (size_t i = 0; i < size; ++i) {
// *(t + i * sizeof(size_t)) += 2;
*(t + i * sizeof(size_t)) = *(t + i * sizeof(size_t)) + 2;
// cout << *reinterpret_cast<int*>(t + sizeof(size_t) * i) << endl;
}
}
int main() {
std::vector<size_t> a = {1,2,3,4};
test(&a[0], 4); // print result is: 3, 2,3,4, which only modify the first element
int b[4] = {1,2,3,4};
test(b, 4); // print result is: 3, 2,3,4, which only modify the first element
for (size_t i = 0; i < a.size(); ++i) {
cout << a[i] << " ";
}
for (size_t i = 0; i < 4; ++i) {
cout << b[i] << " ";
}
}
please see the notes in code, i think when i use *(t + i * sizeof(size_t))
, it will find the next int position, but it failed, can anyone help on this?