向量数组 C++ - 添加元素时的奇怪行为
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13728685/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Array of Vectors C++ - curious behaviour when adding elements
提问by Andrey Lujankin
for google and stackoverflow search could not help me I have no choice but to ask you guys for help.
对于 google 和 stackoverflow 搜索无法帮助我,我别无选择,只能向你们寻求帮助。
I would like to use an array of vectors - I know that this array will only have to contain two vectors. Thus
我想使用向量数组 - 我知道这个数组只需要包含两个向量。因此
vector<double> testVect[1];
Now when I want to add an Element to the first vector contained in the array I use
现在,当我想将一个 Element 添加到我使用的数组中包含的第一个向量时
testVect[0].push_back(0);
So far everything seems ok - unfortunately adding an Element to the first vector somehow also adds the same element (in this case the 0) to the second vector as well.
到目前为止,一切似乎都没问题——不幸的是,向第一个向量添加一个元素也会以某种方式向第二个向量添加相同的元素(在本例中为 0)。
Could anybody tell me the reason for this kind of behaviour ? (please) - and perhaps a workaround. Currently I have to use Visual Studio 6 (employer won't install a new compiler - I am already riling up my coworkers :D
有人能告诉我这种行为的原因吗?(请) - 也许是一种解决方法。目前我必须使用 Visual Studio 6(雇主不会安装新的编译器 - 我已经激怒了我的同事:D
回答by Basile Starynkevitch
If you want two vectors, you should declare:
如果你想要两个向量,你应该声明:
vector<double> testVect[2];
then use testVect[0]
and testVect[1]
in your code.
然后在您的代码中使用testVect[0]
和testVect[1]
。
And you should enable all warnings on your compiler.
您应该在编译器上启用所有警告。
BTW, you could install a recent Linux distribution, with a recent GCC compiler (e.g. 4.7), and run it as g++ -Wall -g
it would certainly have warned you if you statically accessed the testVect
out of bounds, like it seems that you have had.
顺便说一句,您可以安装带有最新 GCC 编译器(例如 4.7)的最新 Linux 发行版,然后运行它,因为g++ -Wall -g
如果您静态访问testVect
越界,它肯定会警告您,就像您已经这样做了一样。
Both GNU/Linux and GCC are free, so your manager could be happy.
GNU/Linux 和 GCC 都是免费的,所以你的经理会很高兴。